-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·85 lines (69 loc) · 2 KB
/
app.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
"""
primary entry point to the bot backend
"""
import os
import time
import signal
import logging
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
import dotenv
import telebot
from telebot.types import Update
import utils
# Load environment variables
dotenv.load_dotenv()
TOKEN = os.getenv("TOKEN")
# Initialize the bot
bot = telebot.TeleBot(TOKEN)
# Initialize update ID dictionary and logger
updateid_dict = OrderedDict()
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
# Define maximum threads and updates to fetch
MAX_THREADS = 10
MAX_UPDATES = 100
# Initialize the thread pool
executor = ThreadPoolExecutor(max_workers=MAX_THREADS)
def fetch_updates(offset):
"""
Fetch updates from the Telegram server.
"""
return (
bot.get_updates()
if offset is None
else bot.get_updates(offset, MAX_UPDATES, timeout=20)
)
def process_update(update: Update):
"""
Process an incoming update.
"""
if update.update_id not in updateid_dict:
updateid_dict[update.update_id] = time.time()
try:
executor.submit(utils.address_query, update)
except Exception as exception:
logging.error(
"Unable to process update {%s}: {%s}", update.update_id, exception
)
if len(updateid_dict) > 50:
updateid_dict.popitem(last=False)
def run_bot():
"""
Main function that runs the bot.
"""
logging.info("Bot is starting...")
last_update_id = None
while True:
try:
updates_list = fetch_updates(last_update_id)
for update in updates_list:
last_update_id = update.update_id
process_update(update)
except Exception as e:
logging.error("Error while fetching or processing updates: {%s}", e)
time.sleep(5) # Sleep for a bit before retrying
if __name__ == "__main__":
run_bot()