-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
90 lines (73 loc) · 2.52 KB
/
main.py
File metadata and controls
90 lines (73 loc) · 2.52 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
import asyncio
import logging
import signal
from dotenv import load_dotenv
import telegram_bot
import database
import news_analyzer
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
NEWS_LIMIT = 2
running = True
async def check_news():
"""Yangi kripto xabarlarini tekshiradi va xabar yuboradi."""
try:
logger.info(f"Checking for new crypto news (limit: {NEWS_LIMIT})...")
important_news = await news_analyzer.fetch_and_process_news(limit=NEWS_LIMIT)
if important_news:
logger.info(f"Found {len(important_news)} important news items.")
await telegram_bot.send_notifications(important_news)
else:
logger.info("No important news found.")
except Exception as e:
logger.error(f"Error checking news: {e}", exc_info=True)
async def scheduler():
"""Har 5 daqiqada bir marta xabarlarni tekshiradi."""
while running:
await check_news()
await asyncio.sleep(300) # 300 soniya = 5 daqiqa
async def cleanup():
"""Botni toʻxtatishdan oldin resurslarni tozalaydi."""
global running
running = False
try:
logger.info("Stopping Telegram bot...")
await telegram_bot.stop_bot()
logger.info("Telegram bot stopped.")
except Exception as e:
logger.error(f"Error stopping Telegram bot: {e}")
logger.info("Cleanup completed.")
async def main():
"""Dasturga kirish nuqtasi."""
global running
await database.init_db()
logger.info("Database initialized.")
scheduler_task = asyncio.create_task(scheduler())
try:
logger.info("Starting Telegram bot...")
await telegram_bot.start_bot()
except Exception as e:
logger.error(f"Error running Telegram bot: {e}", exc_info=True)
finally:
logger.info("Main function finished, starting cleanup...")
await cleanup()
scheduler_task.cancel()
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(cleanup()))
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received, shutting down...")
loop.run_until_complete(cleanup())
finally:
loop.close()
logger.info("Application shutdown complete.")