Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

misc: code consistency and bot instance creation #1482

Merged
merged 5 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/1482.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Enhanced code consistency and readability by refactoring imports, adjusting the base webhook URL, modifying bot instance initialization to utilize DefaultBotProperties, and updating router message handlers for improved consistency and readability.
JrooTJunior marked this conversation as resolved.
Show resolved Hide resolved
14 changes: 10 additions & 4 deletions examples/echo_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
from os import getenv

from aiogram import Bot, Dispatcher, html
from aiogram import Bot, Dispatcher, Router, html
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
Expand All @@ -13,10 +13,11 @@
TOKEN = getenv("BOT_TOKEN")

# All handlers should be attached to the Router (or Dispatcher)
dp = Dispatcher()

echo_router = Router()

@dp.message(CommandStart())

@echo_router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
Expand All @@ -29,7 +30,7 @@ async def command_start_handler(message: Message) -> None:
await message.answer(f"Hello, {html.bold(message.from_user.full_name)}!")


@dp.message()
@echo_router.message()
async def echo_handler(message: Message) -> None:
"""
Handler will forward receive a message back to the sender
Expand All @@ -47,6 +48,11 @@ 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))

dp = Dispatcher()

dp.include_router(echo_router)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need routers in this example, this example should still simple


# And the run events dispatching
await dp.start_polling(bot)

Expand Down
11 changes: 6 additions & 5 deletions examples/echo_bot_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

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
Expand All @@ -29,7 +30,7 @@
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()
Expand All @@ -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

Expand Down Expand Up @@ -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()
Expand Down
9 changes: 5 additions & 4 deletions examples/echo_bot_webhook_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down
9 changes: 6 additions & 3 deletions examples/error_handling.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -11,7 +14,7 @@
)
from aiogram.types import ErrorEvent

TOKEN = "42:TOKEN"
TOKEN = getenv("BOT_TOKEN")

dp = Dispatcher()

Expand Down Expand Up @@ -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)

Expand Down
7 changes: 6 additions & 1 deletion examples/finite_state_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
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
Expand Down Expand Up @@ -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)


Expand Down
6 changes: 4 additions & 2 deletions examples/multi_file_bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
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
Expand All @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions examples/multi_file_bot/handlers/start.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
10 changes: 5 additions & 5 deletions examples/quiz_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
12 changes: 9 additions & 3 deletions examples/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
ReplyKeyboardRemove,
)

TOKEN = getenv("BOT_TOKEN")

BUTTON_CANCEL = KeyboardButton(text="❌ Cancel")
BUTTON_BACK = KeyboardButton(text="🔙 Back")

Expand Down Expand Up @@ -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()
5 changes: 3 additions & 2 deletions examples/specify_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
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 (
Expand Down Expand Up @@ -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()

Expand Down
4 changes: 2 additions & 2 deletions examples/web_app/handlers.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -11,7 +11,7 @@
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,
Expand Down
4 changes: 3 additions & 1 deletion examples/web_app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
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

Expand All @@ -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)
Expand Down