-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathbot.py
More file actions
174 lines (134 loc) · 5.59 KB
/
bot.py
File metadata and controls
174 lines (134 loc) · 5.59 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import asyncio
import logging
from typing import Dict, Any
from aiogram import Bot, Dispatcher
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
from aiohttp import web
from config import BOT_TOKEN, BOT_MODE, WEBHOOK_PATH, WEBHOOK_URL, PORT, HOST
from handlers.handlers import register_handlers
from handlers.admin import register_admin_handlers
from utils.cleanup import cleanup_temp_directory
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class VidZillaBot:
def __init__(self):
self.bot: Bot = None
self.dp: Dispatcher = None
self.app: web.Application = None
self.runner: web.AppRunner = None
self.mode = (BOT_MODE or "webhook").lower().strip()
if self.mode not in {"webhook", "polling"}:
logger.warning("Unknown BOT_MODE=%s. Falling back to 'webhook'.", self.mode)
self.mode = "webhook"
async def _create_bot_and_dispatcher(self) -> None:
# Clean up old temp files on startup
cleanup_temp_directory()
self.bot = Bot(token=BOT_TOKEN)
self.dp = Dispatcher()
async def _register_handlers(self) -> None:
register_handlers(self.dp)
register_admin_handlers(self.dp)
logger.info("All handlers registered")
async def _create_web_app(self) -> None:
self.app = web.Application()
self.app["bot"] = self.bot
# Setup webhook handler
webhook_handler = SimpleRequestHandler(
dispatcher=self.dp,
bot=self.bot,
)
webhook_handler.register(self.app, path=WEBHOOK_PATH)
setup_application(self.app, self.dp, bot=self.bot)
# Add routes
self.app.router.add_get("/", self._handle_root)
self.app.router.add_get(WEBHOOK_PATH, self._handle_webhook_status)
# Setup lifecycle handlers
self.app.on_startup.append(self._on_startup)
self.app.on_shutdown.append(self._on_shutdown)
async def _handle_root(self, request: web.Request) -> web.Response:
return web.Response(text="Vidzilla Bot - FREE Version is running!")
async def _handle_webhook_status(self, request: web.Request) -> web.Response:
return web.Response(text="Webhook is active and working")
async def _on_startup(self, app: web.Application) -> None:
webhook_url = WEBHOOK_URL + WEBHOOK_PATH
logger.info(f"Setting webhook to {webhook_url}")
await self.bot.set_webhook(webhook_url)
logger.info("Webhook set successfully")
async def _on_shutdown(self, app: web.Application) -> None:
logger.info("Shutting down bot...")
if self.bot:
await self.bot.session.close()
logger.info("Bot shutdown complete")
async def create_app(self) -> web.Application:
await self._create_bot_and_dispatcher()
await self._register_handlers()
await self._create_web_app()
logger.info("Application created successfully")
return self.app
async def _run_polling(self) -> None:
await self._create_bot_and_dispatcher()
await self._register_handlers()
logger.info("Polling mode: deleting existing webhook")
await self.bot.delete_webhook(drop_pending_updates=True)
logger.info("Starting long polling")
await self.dp.start_polling(
self.bot,
allowed_updates=self.dp.resolve_used_update_types()
)
async def run(self) -> None:
try:
if self.mode == "polling":
await self._run_polling()
else:
if not WEBHOOK_PATH or not WEBHOOK_URL:
raise ValueError(
"WEBHOOK_PATH and WEBHOOK_URL are required when BOT_MODE=webhook"
)
app = await self.create_app()
# Keep updates on Telegram side while renewing webhook.
logger.info("Webhook mode: deleting existing webhook")
await self.bot.delete_webhook(drop_pending_updates=False)
self.runner = web.AppRunner(app)
await self.runner.setup()
site = web.TCPSite(self.runner, HOST, PORT)
logger.info(f"Starting web application on {HOST}:{PORT}")
await site.start()
logger.info("Vidzilla Bot - FREE Version started successfully!")
# Run forever
await asyncio.Event().wait()
except KeyboardInterrupt:
logger.info("Received shutdown signal")
except Exception as e:
logger.error(f"Application error: {e}")
raise
finally:
await self._cleanup()
async def _cleanup(self) -> None:
logger.info("Cleaning up resources...")
if self.runner:
await self.runner.cleanup()
if self.bot and not self.bot.session.closed:
await self.bot.session.close()
logger.info("Cleanup complete")
async def main() -> None:
logger.info("Starting Vidzilla Bot - FREE Version in %s mode", (BOT_MODE or "webhook"))
bot_app = VidZillaBot()
try:
await bot_app.run()
except KeyboardInterrupt:
logger.info("Bot stopped by user")
except Exception as e:
logger.error(f"Fatal error: {e}")
raise
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Application terminated")
except Exception as e:
logger.error(f"Application failed to start: {e}")
exit(1)