-
Notifications
You must be signed in to change notification settings - Fork 279
/
main.py
70 lines (55 loc) · 1.98 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import asyncio
import logging
import signal
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from handlers import start, forward_to_group, forward_to_user
from settings import TELEGRAM_TOKEN, TELEGRAM_SUPPORT_CHAT_ID, PERSONAL_ACCOUNT_CHAT_ID
# Configure logging
logging.basicConfig(level=logging.INFO)
# Create an event to signal when to stop the bot
stop_event = asyncio.Event()
async def main():
# Initialize bot and application
application = Application.builder().token(TELEGRAM_TOKEN).build()
# Register handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(
MessageHandler(
filters.TEXT
& ~filters.COMMAND
& ~filters.Chat(
chat_id=[TELEGRAM_SUPPORT_CHAT_ID, PERSONAL_ACCOUNT_CHAT_ID]
),
forward_to_group,
)
)
application.add_handler(
MessageHandler(
filters.TEXT
& filters.Chat(chat_id=[TELEGRAM_SUPPORT_CHAT_ID, PERSONAL_ACCOUNT_CHAT_ID])
& filters.REPLY,
forward_to_user,
)
)
logging.info("Handlers registered.")
# Set up signal handlers
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(shutdown(application)))
# Start the bot
await application.initialize()
await application.start()
await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)
logging.info("Bot started. Press Ctrl+C to stop.")
# Wait until the stop event is set
await stop_event.wait()
# Stop the bot gracefully
await application.stop()
await application.shutdown()
async def shutdown(application: Application):
"""Gracefully shut down the application."""
logging.info("Received stop signal, shutting down...")
stop_event.set()
if __name__ == "__main__":
asyncio.run(main())