From e3dc7d576bd6e2aa3377b4776647341109ef66cf Mon Sep 17 00:00:00 2001 From: sdmway Date: Fri, 31 May 2024 11:11:21 -0600 Subject: [PATCH] misc: code consistency and bot instance creation (#1482) * misc: code consistency and bot instance creation * Changelog for aiogram#1482 * misc: consistency of comments and dispatcher instance creation * misc: removed routers example * Update CHANGES/1482.misc.rst --------- Co-authored-by: Alex Root Junior --- CHANGES/1482.misc.rst | 1 + examples/echo_bot.py | 2 ++ examples/echo_bot_webhook.py | 11 ++++++----- examples/echo_bot_webhook_ssl.py | 9 +++++---- examples/error_handling.py | 9 ++++++--- examples/finite_state_machine.py | 7 ++++++- examples/multi_file_bot/bot.py | 6 ++++-- examples/multi_file_bot/handlers/start.py | 4 ++-- examples/quiz_scene.py | 10 +++++----- examples/scene.py | 12 +++++++++--- examples/specify_updates.py | 5 +++-- examples/web_app/handlers.py | 4 ++-- examples/web_app/main.py | 4 +++- 13 files changed, 54 insertions(+), 30 deletions(-) create mode 100644 CHANGES/1482.misc.rst diff --git a/CHANGES/1482.misc.rst b/CHANGES/1482.misc.rst new file mode 100644 index 00000000..782a76b3 --- /dev/null +++ b/CHANGES/1482.misc.rst @@ -0,0 +1 @@ +Improved code consistency and readability in code examples by refactoring imports, adjusting the base webhook URL, modifying bot instance initialization to utilize DefaultBotProperties, and updating router message handlers. diff --git a/examples/echo_bot.py b/examples/echo_bot.py index 2808de7f..6a720ddb 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -13,6 +13,7 @@ from aiogram.types import Message TOKEN = getenv("BOT_TOKEN") # All handlers should be attached to the Router (or Dispatcher) + dp = Dispatcher() @@ -47,6 +48,7 @@ async def echo_handler(message: Message) -> None: async def main() -> None: # Initialize Bot instance with default bot properties which will be passed to all API calls bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) + # And the run events dispatching await dp.start_polling(bot) diff --git a/examples/echo_bot_webhook.py b/examples/echo_bot_webhook.py index 1fa56c3d..056c3f71 100644 --- a/examples/echo_bot_webhook.py +++ b/examples/echo_bot_webhook.py @@ -7,7 +7,8 @@ from os import getenv from aiohttp import web -from aiogram import Bot, Dispatcher, Router, types +from aiogram import Bot, Dispatcher, Router +from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message @@ -29,7 +30,7 @@ WEBHOOK_PATH = "/webhook" WEBHOOK_SECRET = "my-secret" # Base URL for webhook will be used to generate webhook URL for Telegram, # in this example it is used public DNS with HTTPS support -BASE_WEBHOOK_URL = "https://aiogram.dev/" +BASE_WEBHOOK_URL = "https://aiogram.dev" # All handlers should be attached to the Router (or Dispatcher) router = Router() @@ -49,7 +50,7 @@ async def command_start_handler(message: Message) -> None: @router.message() -async def echo_handler(message: types.Message) -> None: +async def echo_handler(message: Message) -> None: """ Handler will forward receive a message back to the sender @@ -78,8 +79,8 @@ def main() -> None: # Register startup hook to initialize webhook dp.startup.register(on_startup) - # Initialize Bot instance with a default parse mode which will be passed to all API calls - bot = Bot(TOKEN, parse_mode=ParseMode.HTML) + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) # Create aiohttp.web.Application instance app = web.Application() diff --git a/examples/echo_bot_webhook_ssl.py b/examples/echo_bot_webhook_ssl.py index ad41bc4d..45c75015 100644 --- a/examples/echo_bot_webhook_ssl.py +++ b/examples/echo_bot_webhook_ssl.py @@ -8,7 +8,8 @@ from os import getenv from aiohttp import web -from aiogram import Bot, Dispatcher, Router, types +from aiogram import Bot, Dispatcher, Router +from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import FSInputFile, Message @@ -54,7 +55,7 @@ async def command_start_handler(message: Message) -> None: @router.message() -async def echo_handler(message: types.Message) -> None: +async def echo_handler(message: Message) -> None: """ Handler will forward receive a message back to the sender @@ -89,8 +90,8 @@ def main() -> None: # Register startup hook to initialize webhook dp.startup.register(on_startup) - # Initialize Bot instance with a default parse mode which will be passed to all API calls - bot = Bot(TOKEN, parse_mode=ParseMode.HTML) + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) # Create aiohttp.web.Application instance app = web.Application() diff --git a/examples/error_handling.py b/examples/error_handling.py index 83b5500d..fca83f82 100644 --- a/examples/error_handling.py +++ b/examples/error_handling.py @@ -1,8 +1,11 @@ import asyncio import html import logging +from os import getenv from aiogram import Bot, Dispatcher, types +from aiogram.client.default import DefaultBotProperties +from aiogram.enums import ParseMode from aiogram.filters import ( Command, CommandObject, @@ -11,7 +14,7 @@ from aiogram.filters import ( ) from aiogram.types import ErrorEvent -TOKEN = "42:TOKEN" +TOKEN = getenv("BOT_TOKEN") dp = Dispatcher() @@ -99,8 +102,8 @@ async def handle_set_name(message: types.Message, command: CommandObject) -> Non async def main() -> None: - # Initialize Bot instance with a default parse mode which will be passed to all API calls - bot = Bot(TOKEN, parse_mode="HTML") + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) # And the run events dispatching await dp.start_polling(bot) diff --git a/examples/finite_state_machine.py b/examples/finite_state_machine.py index 2905ec5b..f371d2ca 100644 --- a/examples/finite_state_machine.py +++ b/examples/finite_state_machine.py @@ -5,6 +5,7 @@ from os import getenv from typing import Any, Dict from aiogram import Bot, Dispatcher, F, Router, html +from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import Command, CommandStart from aiogram.fsm.context import FSMContext @@ -124,10 +125,14 @@ async def show_summary(message: Message, data: Dict[str, Any], positive: bool = async def main(): - bot = Bot(token=TOKEN, parse_mode=ParseMode.HTML) + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) + dp = Dispatcher() + dp.include_router(form_router) + # Start event dispatching await dp.start_polling(bot) diff --git a/examples/multi_file_bot/bot.py b/examples/multi_file_bot/bot.py index 927b52a0..0f1ba083 100644 --- a/examples/multi_file_bot/bot.py +++ b/examples/multi_file_bot/bot.py @@ -6,6 +6,7 @@ from handlers.echo import echo_router from handlers.start import start_router from aiogram import Bot, Dispatcher +from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode # Bot token can be obtained via https://t.me/BotFather @@ -21,8 +22,9 @@ async def main() -> None: echo_router, ) - # Initialize Bot instance with a default parse mode which will be passed to all API calls - bot = Bot(TOKEN, parse_mode=ParseMode.HTML) + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) + # And the run events dispatching await dp.start_polling(bot) diff --git a/examples/multi_file_bot/handlers/start.py b/examples/multi_file_bot/handlers/start.py index 804268c3..3e95f2ab 100644 --- a/examples/multi_file_bot/handlers/start.py +++ b/examples/multi_file_bot/handlers/start.py @@ -1,11 +1,11 @@ from aiogram import Router -from aiogram.filters import Command +from aiogram.filters import CommandStart from aiogram.types import Message start_router = Router() -@start_router.message(Command("start")) +@start_router.message(CommandStart()) async def command_start_handler(message: Message) -> None: """ This handler receives messages with `/start` command diff --git a/examples/quiz_scene.py b/examples/quiz_scene.py index 343fef75..b07888df 100644 --- a/examples/quiz_scene.py +++ b/examples/quiz_scene.py @@ -289,13 +289,13 @@ def create_dispatcher(): async def main(): - dispatcher = create_dispatcher() - bot = Bot(TOKEN) - await dispatcher.start_polling(bot) + dp = create_dispatcher() + bot = Bot(token=TOKEN) + await dp.start_polling(bot) if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - asyncio.run(main()) # Alternatively, you can use aiogram-cli: # `aiogram run polling quiz_scene:create_dispatcher --log-level info --token BOT_TOKEN` + logging.basicConfig(level=logging.INFO) + asyncio.run(main()) diff --git a/examples/scene.py b/examples/scene.py index 090c64c2..ab83bd44 100644 --- a/examples/scene.py +++ b/examples/scene.py @@ -16,6 +16,8 @@ from aiogram.types import ( ReplyKeyboardRemove, ) +TOKEN = getenv("BOT_TOKEN") + BUTTON_CANCEL = KeyboardButton(text="❌ Cancel") BUTTON_BACK = KeyboardButton(text="🔙 Back") @@ -195,9 +197,13 @@ def create_dispatcher() -> Dispatcher: return dispatcher +def main() -> None: + dp = create_dispatcher() + bot = Bot(token=TOKEN) + dp.run_polling(bot) + + if __name__ == "__main__": # Recommended to use CLI instead of this snippet. # `aiogram run polling scene_example:create_dispatcher --token BOT_TOKEN --log-level info` - dp = create_dispatcher() - bot = Bot(token=getenv("TELEGRAM_TOKEN")) - dp.run_polling() + main() diff --git a/examples/specify_updates.py b/examples/specify_updates.py index 56571f1a..c25613a2 100644 --- a/examples/specify_updates.py +++ b/examples/specify_updates.py @@ -4,6 +4,7 @@ import sys from os import getenv from aiogram import Bot, Dispatcher, Router +from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import LEAVE_TRANSITION, ChatMemberUpdatedFilter, CommandStart from aiogram.types import ( @@ -78,8 +79,8 @@ async def my_chat_member_change(chat_member: ChatMemberUpdated, bot: Bot) -> Non async def main() -> None: - # Initialize Bot instance with a default parse mode which will be passed to all API calls - bot = Bot(TOKEN, parse_mode=ParseMode.HTML) + # Initialize Bot instance with default bot properties which will be passed to all API calls + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) dp = Dispatcher() diff --git a/examples/web_app/handlers.py b/examples/web_app/handlers.py index 5896c0b2..843f4c63 100644 --- a/examples/web_app/handlers.py +++ b/examples/web_app/handlers.py @@ -1,5 +1,5 @@ from aiogram import Bot, F, Router -from aiogram.filters import Command +from aiogram.filters import Command, CommandStart from aiogram.types import ( InlineKeyboardButton, InlineKeyboardMarkup, @@ -11,7 +11,7 @@ from aiogram.types import ( my_router = Router() -@my_router.message(Command("start")) +@my_router.message(CommandStart()) async def command_start(message: Message, bot: Bot, base_url: str): await bot.set_chat_menu_button( chat_id=message.chat.id, diff --git a/examples/web_app/main.py b/examples/web_app/main.py index db148153..06b64566 100644 --- a/examples/web_app/main.py +++ b/examples/web_app/main.py @@ -8,6 +8,8 @@ from handlers import my_router from routes import check_data_handler, demo_handler, send_message_handler from aiogram import Bot, Dispatcher +from aiogram.client.default import DefaultBotProperties +from aiogram.enums.parse_mode import ParseMode from aiogram.types import MenuButtonWebApp, WebAppInfo from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application @@ -24,7 +26,7 @@ async def on_startup(bot: Bot, base_url: str): def main(): - bot = Bot(token=TOKEN, parse_mode="HTML") + bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) dispatcher = Dispatcher() dispatcher["base_url"] = APP_BASE_URL dispatcher.startup.register(on_startup)