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 <jroot.junior@gmail.com>
This commit is contained in:
sdmway 2024-05-31 11:11:21 -06:00 committed by GitHub
parent b08ba78898
commit e3dc7d576b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 54 additions and 30 deletions

1
CHANGES/1482.misc.rst Normal file
View file

@ -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.

View file

@ -13,6 +13,7 @@ from aiogram.types import Message
TOKEN = getenv("BOT_TOKEN") TOKEN = getenv("BOT_TOKEN")
# All handlers should be attached to the Router (or Dispatcher) # All handlers should be attached to the Router (or Dispatcher)
dp = Dispatcher() dp = Dispatcher()
@ -47,6 +48,7 @@ async def echo_handler(message: Message) -> None:
async def main() -> None: async def main() -> None:
# Initialize Bot instance with default bot properties which will be passed to all API calls # 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)) bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# And the run events dispatching # And the run events dispatching
await dp.start_polling(bot) await dp.start_polling(bot)

View file

@ -7,7 +7,8 @@ from os import getenv
from aiohttp import web 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.enums import ParseMode
from aiogram.filters import CommandStart from aiogram.filters import CommandStart
from aiogram.types import Message from aiogram.types import Message
@ -29,7 +30,7 @@ WEBHOOK_PATH = "/webhook"
WEBHOOK_SECRET = "my-secret" WEBHOOK_SECRET = "my-secret"
# Base URL for webhook will be used to generate webhook URL for Telegram, # Base URL for webhook will be used to generate webhook URL for Telegram,
# in this example it is used public DNS with HTTPS support # 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) # All handlers should be attached to the Router (or Dispatcher)
router = Router() router = Router()
@ -49,7 +50,7 @@ async def command_start_handler(message: Message) -> None:
@router.message() @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 Handler will forward receive a message back to the sender
@ -78,8 +79,8 @@ def main() -> None:
# Register startup hook to initialize webhook # Register startup hook to initialize webhook
dp.startup.register(on_startup) dp.startup.register(on_startup)
# Initialize Bot instance with a default parse mode which will be passed to all API calls # Initialize Bot instance with default bot properties which will be passed to all API calls
bot = Bot(TOKEN, parse_mode=ParseMode.HTML) bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# Create aiohttp.web.Application instance # Create aiohttp.web.Application instance
app = web.Application() app = web.Application()

View file

@ -8,7 +8,8 @@ from os import getenv
from aiohttp import web 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.enums import ParseMode
from aiogram.filters import CommandStart from aiogram.filters import CommandStart
from aiogram.types import FSInputFile, Message from aiogram.types import FSInputFile, Message
@ -54,7 +55,7 @@ async def command_start_handler(message: Message) -> None:
@router.message() @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 Handler will forward receive a message back to the sender
@ -89,8 +90,8 @@ def main() -> None:
# Register startup hook to initialize webhook # Register startup hook to initialize webhook
dp.startup.register(on_startup) dp.startup.register(on_startup)
# Initialize Bot instance with a default parse mode which will be passed to all API calls # Initialize Bot instance with default bot properties which will be passed to all API calls
bot = Bot(TOKEN, parse_mode=ParseMode.HTML) bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# Create aiohttp.web.Application instance # Create aiohttp.web.Application instance
app = web.Application() app = web.Application()

View file

@ -1,8 +1,11 @@
import asyncio import asyncio
import html import html
import logging import logging
from os import getenv
from aiogram import Bot, Dispatcher, types from aiogram import Bot, Dispatcher, types
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import ( from aiogram.filters import (
Command, Command,
CommandObject, CommandObject,
@ -11,7 +14,7 @@ from aiogram.filters import (
) )
from aiogram.types import ErrorEvent from aiogram.types import ErrorEvent
TOKEN = "42:TOKEN" TOKEN = getenv("BOT_TOKEN")
dp = Dispatcher() dp = Dispatcher()
@ -99,8 +102,8 @@ async def handle_set_name(message: types.Message, command: CommandObject) -> Non
async def main() -> None: async def main() -> None:
# Initialize Bot instance with a default parse mode which will be passed to all API calls # Initialize Bot instance with default bot properties which will be passed to all API calls
bot = Bot(TOKEN, parse_mode="HTML") bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# And the run events dispatching # And the run events dispatching
await dp.start_polling(bot) await dp.start_polling(bot)

View file

@ -5,6 +5,7 @@ from os import getenv
from typing import Any, Dict from typing import Any, Dict
from aiogram import Bot, Dispatcher, F, Router, html from aiogram import Bot, Dispatcher, F, Router, html
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode from aiogram.enums import ParseMode
from aiogram.filters import Command, CommandStart from aiogram.filters import Command, CommandStart
from aiogram.fsm.context import FSMContext 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(): 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 = Dispatcher()
dp.include_router(form_router) dp.include_router(form_router)
# Start event dispatching
await dp.start_polling(bot) await dp.start_polling(bot)

View file

@ -6,6 +6,7 @@ from handlers.echo import echo_router
from handlers.start import start_router from handlers.start import start_router
from aiogram import Bot, Dispatcher from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode from aiogram.enums import ParseMode
# Bot token can be obtained via https://t.me/BotFather # Bot token can be obtained via https://t.me/BotFather
@ -21,8 +22,9 @@ async def main() -> None:
echo_router, echo_router,
) )
# Initialize Bot instance with a default parse mode which will be passed to all API calls # Initialize Bot instance with default bot properties which will be passed to all API calls
bot = Bot(TOKEN, parse_mode=ParseMode.HTML) bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# And the run events dispatching # And the run events dispatching
await dp.start_polling(bot) await dp.start_polling(bot)

View file

@ -1,11 +1,11 @@
from aiogram import Router from aiogram import Router
from aiogram.filters import Command from aiogram.filters import CommandStart
from aiogram.types import Message from aiogram.types import Message
start_router = Router() start_router = Router()
@start_router.message(Command("start")) @start_router.message(CommandStart())
async def command_start_handler(message: Message) -> None: async def command_start_handler(message: Message) -> None:
""" """
This handler receives messages with `/start` command This handler receives messages with `/start` command

View file

@ -289,13 +289,13 @@ def create_dispatcher():
async def main(): async def main():
dispatcher = create_dispatcher() dp = create_dispatcher()
bot = Bot(TOKEN) bot = Bot(token=TOKEN)
await dispatcher.start_polling(bot) await dp.start_polling(bot)
if __name__ == "__main__": if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
# Alternatively, you can use aiogram-cli: # Alternatively, you can use aiogram-cli:
# `aiogram run polling quiz_scene:create_dispatcher --log-level info --token BOT_TOKEN` # `aiogram run polling quiz_scene:create_dispatcher --log-level info --token BOT_TOKEN`
logging.basicConfig(level=logging.INFO)
asyncio.run(main())

View file

@ -16,6 +16,8 @@ from aiogram.types import (
ReplyKeyboardRemove, ReplyKeyboardRemove,
) )
TOKEN = getenv("BOT_TOKEN")
BUTTON_CANCEL = KeyboardButton(text="❌ Cancel") BUTTON_CANCEL = KeyboardButton(text="❌ Cancel")
BUTTON_BACK = KeyboardButton(text="🔙 Back") BUTTON_BACK = KeyboardButton(text="🔙 Back")
@ -195,9 +197,13 @@ def create_dispatcher() -> Dispatcher:
return dispatcher return dispatcher
def main() -> None:
dp = create_dispatcher()
bot = Bot(token=TOKEN)
dp.run_polling(bot)
if __name__ == "__main__": if __name__ == "__main__":
# Recommended to use CLI instead of this snippet. # Recommended to use CLI instead of this snippet.
# `aiogram run polling scene_example:create_dispatcher --token BOT_TOKEN --log-level info` # `aiogram run polling scene_example:create_dispatcher --token BOT_TOKEN --log-level info`
dp = create_dispatcher() main()
bot = Bot(token=getenv("TELEGRAM_TOKEN"))
dp.run_polling()

View file

@ -4,6 +4,7 @@ import sys
from os import getenv from os import getenv
from aiogram import Bot, Dispatcher, Router from aiogram import Bot, Dispatcher, Router
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode from aiogram.enums import ParseMode
from aiogram.filters import LEAVE_TRANSITION, ChatMemberUpdatedFilter, CommandStart from aiogram.filters import LEAVE_TRANSITION, ChatMemberUpdatedFilter, CommandStart
from aiogram.types import ( from aiogram.types import (
@ -78,8 +79,8 @@ async def my_chat_member_change(chat_member: ChatMemberUpdated, bot: Bot) -> Non
async def main() -> None: async def main() -> None:
# Initialize Bot instance with a default parse mode which will be passed to all API calls # Initialize Bot instance with default bot properties which will be passed to all API calls
bot = Bot(TOKEN, parse_mode=ParseMode.HTML) bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher() dp = Dispatcher()

View file

@ -1,5 +1,5 @@
from aiogram import Bot, F, Router from aiogram import Bot, F, Router
from aiogram.filters import Command from aiogram.filters import Command, CommandStart
from aiogram.types import ( from aiogram.types import (
InlineKeyboardButton, InlineKeyboardButton,
InlineKeyboardMarkup, InlineKeyboardMarkup,
@ -11,7 +11,7 @@ from aiogram.types import (
my_router = Router() my_router = Router()
@my_router.message(Command("start")) @my_router.message(CommandStart())
async def command_start(message: Message, bot: Bot, base_url: str): async def command_start(message: Message, bot: Bot, base_url: str):
await bot.set_chat_menu_button( await bot.set_chat_menu_button(
chat_id=message.chat.id, chat_id=message.chat.id,

View file

@ -8,6 +8,8 @@ from handlers import my_router
from routes import check_data_handler, demo_handler, send_message_handler from routes import check_data_handler, demo_handler, send_message_handler
from aiogram import Bot, Dispatcher 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.types import MenuButtonWebApp, WebAppInfo
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
@ -24,7 +26,7 @@ async def on_startup(bot: Bot, base_url: str):
def main(): def main():
bot = Bot(token=TOKEN, parse_mode="HTML") bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dispatcher = Dispatcher() dispatcher = Dispatcher()
dispatcher["base_url"] = APP_BASE_URL dispatcher["base_url"] = APP_BASE_URL
dispatcher.startup.register(on_startup) dispatcher.startup.register(on_startup)