refactor: Bot rewritten to webhooks, duplicate code removed

This commit is contained in:
Данил 2025-01-09 00:19:00 +03:00
parent 234e8bf244
commit a1ad2d1694

84
main.py
View file

@ -1,34 +1,83 @@
import logging from functions.convert import Converter
import sys from utils.format_number import format_number
from utils.inline_query import reply
from functions.create_chart import create_chart
import yaml import yaml
from aiohttp import web from aiohttp import web
from aiogram import Bot, Dispatcher, Router from aiogram import Bot, Dispatcher, Router, types
from aiogram.client.default import DefaultBotProperties from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from aiogram.utils.markdown import hbold
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
import hashlib
config = yaml.safe_load(open('config.yaml')) config = yaml.safe_load(open('config.yaml'))
bot = Bot(token=config['telegram_token'], default=DefaultBotProperties(parse_mode=ParseMode.HTML))
router = Router() router = Router()
@router.message() @router.inline_query()
async def echo_handler(message: Message) -> None: async def currency(query: types.InlineQuery) -> None:
try: text = query.query.lower()
# Send a copy of the received message args = text.split()
await message.send_copy(chat_id=message.chat.id) result_id = hashlib.md5(text.encode()).hexdigest()
except TypeError:
# But not all the types is supported to be copied so need to handle it if len(args) < 2:
await message.answer("Nice try!") get_bot = await bot.get_me()
return await reply(result_id,
[("2 or 3 arguments are required.",
f'@{get_bot.username} USD RUB \n'
f'@{get_bot.username} 12 USD RUB',
None, None)],
query)
conv = Converter()
from_currency, conv_currency = '', ''
if len(args) == 3:
conv.amount = float(args[0].replace(',', '.'))
from_currency = args[1]
conv_currency = args[2]
elif len(args) == 2:
from_currency = args[0]
conv_currency = args[1]
else:
return await reply(result_id,
[(
'The source and target currency could not be determined.',
None, None
)],
query)
if not conv_currency or not from_currency:
return await reply(result_id, [('The currency exchange rate could not be found.', None, None)], query)
conv.from_currency = from_currency.upper()
conv.conv_currency = conv_currency.upper()
await conv.convert()
chart = await create_chart(from_currency, conv_currency)
message = f'{format_number(conv.amount)} {conv.from_currency} = {conv.conv_amount} {conv.conv_currency}'
results = [(message, None, None)]
if chart:
results.insert(0, (f'{message}\n[График]({chart})', None, chart))
await reply(result_id, results, query)
async def on_startup(bot: Bot) -> None: async def on_startup(bot: Bot) -> None:
# Убедитесь, что передаете HTTPS URL await bot.set_webhook(
await bot.set_webhook(f"{config['webhook']['base_url']}{config['webhook']['path']}", secret_token=config['webhook']['secret_token']) f"{config['webhook']['base_url']}{config['webhook']['path']}",
secret_token=config['webhook']['secret_token'],
allowed_updates=['inline_query']
)
def main() -> None: def main() -> None:
@ -37,8 +86,6 @@ def main() -> None:
dp.include_router(router) dp.include_router(router)
dp.startup.register(on_startup) dp.startup.register(on_startup)
bot = Bot(token=config['telegram_token'], default=DefaultBotProperties(parse_mode=ParseMode.HTML))
app = web.Application() app = web.Application()
webhook_requests_handler = SimpleRequestHandler( webhook_requests_handler = SimpleRequestHandler(
dispatcher=dp, dispatcher=dp,
@ -53,5 +100,4 @@ def main() -> None:
if __name__ == '__main__': if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
main() main()