-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
57 lines (44 loc) · 1.64 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
import asyncio
import datetime
import logging
import os
import telegram
from dotenv import load_dotenv
from telegram.ext import ApplicationBuilder
from poller_producer import Poller
from consumer import Worker
from utils.common import create_root_logger
load_dotenv()
PRACTICUM_TOKEN: str = os.environ['PRACTICUM_TOKEN']
TELEGRAM_BOT_TOKEN: str = os.environ['TELEGRAM_BOT_TOKEN']
class WordleBot:
def __init__(self, token: str, n: int):
self.bot: telegram.Bot = ApplicationBuilder().token(token).build().bot
self.queue: asyncio.Queue = asyncio.Queue()
self.producer: Poller = Poller(self.bot, self.queue)
self.consumer: Worker = Worker(self.bot, self.queue, n)
async def start(self):
await self.producer.start()
await self.consumer.start()
async def stop(self):
await self.producer.stop()
await self.consumer.stop()
def run() -> None:
loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
bot: WordleBot = WordleBot(TELEGRAM_BOT_TOKEN, 2)
try:
print('Bot has been started.')
loop.create_task(bot.start())
loop.run_forever()
except KeyboardInterrupt:
print(f'Stopping {bot.__class__.__name__}', datetime.datetime.now())
loop.run_until_complete(bot.stop())
print(f'{bot.__class__.__name__} has been stopped',
datetime.datetime.now())
if __name__ == "__main__":
create_root_logger()
if any(not v for v in (PRACTICUM_TOKEN, TELEGRAM_BOT_TOKEN)):
exit_msg: str = 'Cannot start bot, check your environment variables.'
logging.critical(exit_msg)
raise SystemExit(exit_msg)
run()