TG Bot: переписал на aiogram

This commit is contained in:
Alexey Polyakov 2026-03-30 22:34:09 +03:00
parent e5607adb9b
commit 0f5c06f80c
2 changed files with 100 additions and 95 deletions

View File

@ -1,4 +1,4 @@
pyTelegramBotAPI aiogram
aiomysql aiomysql
msgpack msgpack
lz4 lz4

View File

@ -2,15 +2,22 @@ import logging
import random import random
import json import json
import time import time
from telebot.async_telebot import AsyncTeleBot
from textwrap import dedent from textwrap import dedent
from aiogram import Bot, Dispatcher, Router
from aiogram.filters import Command
from aiogram.types import Message
from common.static import Static from common.static import Static
from common.sql_queries import SQLQueries from common.sql_queries import SQLQueries
from common.tools import Tools from common.tools import Tools
class TelegramBot: class TelegramBot:
def __init__(self, token, enabled, db_pool, whitelist_ids=None): def __init__(self, token, enabled, db_pool, whitelist_ids=None):
self.bot = AsyncTeleBot(token) self.bot = Bot(token=token)
self.dp = Dispatcher()
self.router = Router()
self.dp.include_router(self.router)
self.tools = Tools() self.tools = Tools()
self.enabled = enabled self.enabled = enabled
self.db_pool = db_pool self.db_pool = db_pool
@ -21,8 +28,13 @@ class TelegramBot:
self.static = Static() self.static = Static()
self.sql_queries = SQLQueries() self.sql_queries = SQLQueries()
@self.bot.message_handler(commands=['start']) self.router.message.register(self.handle_start, Command("start"))
async def handle_start(message): self.router.message.register(self.handle_register, Command("register"))
def get_bot_message(self, msg_type):
return dedent(self.static.BOT_MESSAGES.get(msg_type)).strip()
async def handle_start(self, message: Message):
tg_id = str(message.from_user.id) tg_id = str(message.from_user.id)
# Ищем привязанный аккаунт пользователя # Ищем привязанный аккаунт пользователя
@ -35,22 +47,20 @@ class TelegramBot:
# Извлекаем id аккаунта с телефоном # Извлекаем id аккаунта с телефоном
phone = account.get('phone') phone = account.get('phone')
await self.bot.send_message( await message.answer(
message.chat.id,
self.get_bot_message(self.msg_types.WELCOME_ALREADY_REGISTERED).format(phone=phone) self.get_bot_message(self.msg_types.WELCOME_ALREADY_REGISTERED).format(phone=phone)
) )
else: else:
await self.bot.send_message( await message.answer(
message.chat.id, self.get_bot_message(self.msg_types.WELCOME_NEW_USER) self.get_bot_message(self.msg_types.WELCOME_NEW_USER)
) )
@self.bot.message_handler(commands=['register']) async def handle_register(self, message: Message):
async def handle_register(message):
tg_id = str(message.from_user.id) tg_id = str(message.from_user.id)
# Проверка ID на наличие в белом списке # Проверка ID на наличие в белом списке
if tg_id not in self.whitelist_ids: if tg_id not in self.whitelist_ids:
await self.bot.send_message(message.chat.id, self.get_bot_message(self.msg_types.ID_NOT_WHITELISTED)) await message.answer(self.get_bot_message(self.msg_types.ID_NOT_WHITELISTED))
return return
async with self.db_pool.acquire() as conn: async with self.db_pool.acquire() as conn:
@ -58,8 +68,7 @@ class TelegramBot:
# Проверка на существование # Проверка на существование
await cursor.execute(self.sql_queries.SELECT_USER_BY_TG_ID, (tg_id,)) await cursor.execute(self.sql_queries.SELECT_USER_BY_TG_ID, (tg_id,))
if await cursor.fetchone(): if await cursor.fetchone():
await self.bot.send_message( await message.answer(
message.chat.id,
self.get_bot_message(self.msg_types.ACCOUNT_ALREADY_EXISTS) self.get_bot_message(self.msg_types.ACCOUNT_ALREADY_EXISTS)
) )
return return
@ -100,24 +109,19 @@ class TelegramBot:
) )
) )
await self.bot.send_message( await message.answer(
message.chat.id,
self.get_bot_message(self.msg_types.REGISTRATION_SUCCESS).format(new_phone=new_phone) self.get_bot_message(self.msg_types.REGISTRATION_SUCCESS).format(new_phone=new_phone)
) )
except Exception as e: except Exception as e:
self.logger.error(f"Ошибка при регистрации: {e}") self.logger.error(f"Ошибка при регистрации: {e}")
await self.bot.send_message( await message.answer(
message.chat.id,
self.get_bot_message(self.msg_types.INTERNAL_ERROR) self.get_bot_message(self.msg_types.INTERNAL_ERROR)
) )
def get_bot_message(self, msg_type):
return dedent(self.static.BOT_MESSAGES.get(msg_type)).strip()
async def start(self): async def start(self):
if self.enabled == True: if self.enabled == True:
try: try:
await self.bot.polling() await self.dp.start_polling(self.bot)
except Exception as e: except Exception as e:
self.logger.error(f"Ошибка запуска Telegram бота: {e}") self.logger.error(f"Ошибка запуска Telegram бота: {e}")
else: else:
@ -126,7 +130,8 @@ class TelegramBot:
async def send_auth_code(self, chat_id, phone, code): async def send_auth_code(self, chat_id, phone, code):
try: try:
await self.bot.send_message( await self.bot.send_message(
chat_id, self.get_bot_message(self.msg_types.INCOMING_CODE).format(phone=phone, code=code) chat_id,
self.get_bot_message(self.msg_types.INCOMING_CODE).format(phone=phone, code=code)
) )
except Exception as e: except Exception as e:
self.logger.error(f"Ошибка отправки кода в Telegram: {e}") self.logger.error(f"Ошибка отправки кода в Telegram: {e}")