mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-11 18:01:04 +00:00
Added more aliases, refactor CallbackData factory, added base exceptions classification mechanism
This commit is contained in:
parent
9451a085d1
commit
f022b4441c
18 changed files with 364 additions and 664 deletions
|
|
@ -1,39 +1,46 @@
|
|||
import logging
|
||||
from typing import Any
|
||||
|
||||
from aiogram import Bot, Dispatcher, types
|
||||
from aiogram.dispatcher.handler import MessageHandler
|
||||
from aiogram.types import Message
|
||||
|
||||
TOKEN = "42:TOKEN"
|
||||
dp = Dispatcher()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dp.message(commands=["start"])
|
||||
class MyHandler(MessageHandler):
|
||||
|
||||
@dp.message(commands={"start"})
|
||||
async def command_start_handler(message: Message) -> None:
|
||||
"""
|
||||
This handler receive messages with `/start` command
|
||||
|
||||
Usage of Class-based handlers
|
||||
"""
|
||||
|
||||
async def handle(self) -> Any:
|
||||
await self.event.answer(f"<b>Hello, {self.from_user.full_name}!</b>")
|
||||
# Most of event objects has an aliases for API methods to be called in event context
|
||||
# For example if you want to answer to incoming message you can use `message.answer(...)` alias
|
||||
# and the target chat will be passed to :ref:`aiogram.methods.send_message.SendMessage` method automatically
|
||||
# or call API method directly via Bot instance: `bot.send_message(chat_id=message.chat.id, ...)`
|
||||
await message.answer(f"Hello, <b>{message.from_user.full_name}!</b>")
|
||||
|
||||
|
||||
@dp.message(content_types=[types.ContentType.ANY])
|
||||
async def echo_handler(message: types.Message, bot: Bot) -> Any:
|
||||
@dp.message()
|
||||
async def echo_handler(message: types.Message) -> Any:
|
||||
"""
|
||||
Handler will forward received message back to the sender
|
||||
|
||||
Usage of Function-based handlers
|
||||
By default message handler will handle all message types (like text, photo, sticker and etc.)
|
||||
"""
|
||||
|
||||
await bot.forward_message(
|
||||
from_chat_id=message.chat.id, chat_id=message.chat.id, message_id=message.message_id
|
||||
)
|
||||
try:
|
||||
# Send copy of the received message
|
||||
await message.send_copy(chat_id=message.chat.id)
|
||||
except TypeError:
|
||||
# But not all the types is supported to be copied so need to handle it
|
||||
await message.answer("Nice try!")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# Initialize Bot instance with an default parse mode which will be passed to all API calls
|
||||
bot = Bot(TOKEN, parse_mode="HTML")
|
||||
# And the run events dispatching
|
||||
dp.run_polling(bot)
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue