Refactor and improve bot messages

Refactored bot code to use aiogram enumerations and enhanced chat messages with markdown beautifications for a more user-friendly display.

CommandStart() is now used instead of Command('start') for readability.

Furthermore, the bot's 'stop' command was improved, ensuring it executes appropriately during KeyboardInterrupt or SystemExit.

Additionally, the bot's logging was adjusted to output to sys.stdout for better logs' readability.
This commit is contained in:
latan 2023-08-10 11:46:22 +03:00
parent 68c0516f69
commit 518739724c
7 changed files with 63 additions and 45 deletions

View file

@ -1,10 +1,12 @@
import asyncio
import logging
import sys
from aiogram import Bot, Dispatcher, Router, types
from aiogram.enums import ParseMode
from aiogram.filters import Command
from aiogram.filters import CommandStart
from aiogram.types import Message
from aiogram.utils.markdown import hbold
# Bot token can be obtained via https://t.me/BotFather
TOKEN = "42:TOKEN"
@ -13,7 +15,7 @@ TOKEN = "42:TOKEN"
router = Router()
@router.message(Command("start"))
@router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
@ -23,7 +25,7 @@ async def command_start_handler(message: Message) -> None:
# 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>")
await message.answer(f"Hello, {hbold(message.from_user.full_name)}!")
@router.message()
@ -54,5 +56,8 @@ async def main() -> None:
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logging.info("Bot stopped!")

View file

@ -2,13 +2,15 @@
This example shows how to use webhook on behind of any reverse proxy (nginx, traefik, ingress etc.)
"""
import logging
import sys
from aiohttp import web
from aiogram import Bot, Dispatcher, Router, types
from aiogram.enums import ParseMode
from aiogram.filters import Command
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
# Bot token can be obtained via https://t.me/BotFather
@ -32,7 +34,7 @@ BASE_WEBHOOK_URL = "https://aiogram.dev/"
router = Router()
@router.message(Command(commands=["start"]))
@router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
@ -42,7 +44,7 @@ async def command_start_handler(message: Message) -> None:
# 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>")
await message.answer(f"Hello, {hbold(message.from_user.full_name)}!")
@router.message()
@ -100,5 +102,5 @@ def main() -> None:
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
main()

View file

@ -8,8 +8,9 @@ from aiohttp import web
from aiogram import Bot, Dispatcher, Router, types
from aiogram.enums import ParseMode
from aiogram.filters import Command
from aiogram.filters import CommandStart
from aiogram.types import FSInputFile, Message
from aiogram.utils.markdown import hbold
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
# Bot token can be obtained via https://t.me/BotFather
@ -37,7 +38,7 @@ WEBHOOK_SSL_PRIV = "/path/to/private.key"
router = Router()
@router.message(Command("start"))
@router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
@ -47,7 +48,7 @@ async def command_start_handler(message: Message) -> None:
# 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>")
await message.answer(f"Hello, {hbold(message.from_user.full_name)}!")
@router.message()

View file

@ -5,7 +5,8 @@ from os import getenv
from typing import Any, Dict
from aiogram import Bot, Dispatcher, F, Router, html
from aiogram.filters import Command
from aiogram.enums import ParseMode
from aiogram.filters import Command, CommandStart
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from aiogram.types import (
@ -24,7 +25,7 @@ class Form(StatesGroup):
language = State()
@form_router.message(Command("start"))
@form_router.message(CommandStart())
async def command_start(message: Message, state: FSMContext) -> None:
await state.set_state(Form.name)
await message.answer(
@ -91,7 +92,7 @@ async def process_like_write_bots(message: Message, state: FSMContext) -> None:
@form_router.message(Form.like_bots)
async def process_unknown_write_bots(message: Message, state: FSMContext) -> None:
async def process_unknown_write_bots(message: Message) -> None:
await message.reply("I don't understand you :(")
@ -99,12 +100,12 @@ async def process_unknown_write_bots(message: Message, state: FSMContext) -> Non
async def process_language(message: Message, state: FSMContext) -> None:
data = await state.update_data(language=message.text)
await state.clear()
text = (
"Thank for all! Python is in my hearth!\nSee you soon."
if message.text.casefold() == "python"
else "Thank for information!\nSee you soon."
)
await message.answer(text)
if message.text.casefold() == "python":
await message.reply(
"Python, you say? That's the language that makes my circuits light up! 😉"
)
await show_summary(message=message, data=data)
@ -121,7 +122,7 @@ async def show_summary(message: Message, data: Dict[str, Any], positive: bool =
async def main():
bot = Bot(token=getenv("TELEGRAM_TOKEN"), parse_mode="HTML")
bot = Bot(token=getenv("TELEGRAM_TOKEN"), parse_mode=ParseMode.HTML)
dp = Dispatcher()
dp.include_router(form_router)
@ -130,4 +131,7 @@ async def main():
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
asyncio.run(main())
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logging.info("Bot stopped!")

View file

@ -6,6 +6,7 @@ from finite_state_machine import form_router
from aiogram import Bot, Dispatcher, F, Router
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.enums import ParseMode
from aiogram.exceptions import TelegramUnauthorizedError
from aiogram.filters import Command, CommandObject
from aiogram.fsm.storage.redis import DefaultKeyBuilder, RedisStorage
@ -57,7 +58,7 @@ async def on_startup(dispatcher: Dispatcher, bot: Bot):
def main():
session = AiohttpSession()
bot_settings = {"session": session, "parse_mode": "HTML"}
bot_settings = {"session": session, "parse_mode": ParseMode.HTML}
bot = Bot(token=MAIN_BOT_TOKEN, **bot_settings)
storage = RedisStorage.from_url(REDIS_DSN, key_builder=DefaultKeyBuilder(with_bot_id=True))

View file

@ -1,8 +1,10 @@
import asyncio
import logging
import sys
from aiogram import Bot, Dispatcher, Router
from aiogram.filters import Command
from aiogram.enums import ParseMode
from aiogram.filters import LEAVE_TRANSITION, ChatMemberUpdatedFilter, CommandStart
from aiogram.types import (
CallbackQuery,
ChatMemberUpdated,
@ -10,8 +12,9 @@ from aiogram.types import (
InlineKeyboardMarkup,
Message,
)
from aiogram.utils.markdown import hbold, hcode
TOKEN = "6wo"
TOKEN = "42:TOKEN"
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
@ -19,14 +22,14 @@ logging.basicConfig(level=logging.INFO)
router = Router()
@router.message(Command("start"))
@router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
"""
await message.answer(
f"Hello, <b>{message.from_user.full_name}!</b>",
f"Hello, {hbold(message.from_user.full_name)}!",
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text="Tap me, bro", callback_data="*")]]
),
@ -37,7 +40,7 @@ async def command_start_handler(message: Message) -> None:
async def chat_member_update(chat_member: ChatMemberUpdated, bot: Bot) -> None:
await bot.send_message(
chat_member.chat.id,
"Member {chat_member.from_user.id} was changed "
f"Member {hcode(chat_member.from_user.id)} was changed "
+ f"from {chat_member.old_chat_member.status} to {chat_member.new_chat_member.status}",
)
@ -48,7 +51,7 @@ sub_router = Router()
@sub_router.callback_query()
async def callback_tap_me(callback_query: CallbackQuery) -> None:
await callback_query.answer("Yeah good, now i'm fine")
await callback_query.answer("Yeah good, now I'm fine")
# this router will use only edited_message updates
@ -57,38 +60,39 @@ sub_sub_router = Router()
@sub_sub_router.edited_message()
async def edited_message_handler(edited_message: Message) -> None:
await edited_message.reply("Message was edited, big brother watch you")
await edited_message.reply("Message was edited, Big Brother watches you")
# this router will use only my_chat_member updates
deep_dark_router = Router()
@deep_dark_router.my_chat_member()
@deep_dark_router.my_chat_member(~ChatMemberUpdatedFilter(~LEAVE_TRANSITION))
async def my_chat_member_change(chat_member: ChatMemberUpdated, bot: Bot) -> None:
await bot.send_message(
chat_member.chat.id,
"Member was changed from "
+ f"{chat_member.old_chat_member.status} to {chat_member.new_chat_member.status}",
"This Bot`s status was changed from "
+ f"{hbold(chat_member.old_chat_member.status)} to {hbold(chat_member.new_chat_member.status)}",
)
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")
bot = Bot(TOKEN, parse_mode=ParseMode.HTML)
dp = Dispatcher()
dp.include_router(router)
sub_router.include_router(deep_dark_router)
router.include_router(sub_router)
router.include_router(sub_sub_router)
router.include_routers(sub_router, sub_sub_router)
dp.include_router(router)
useful_updates = dp.resolve_used_update_types()
# And the run events dispatching
await dp.start_polling(bot, allowed_updates=useful_updates)
# Start event dispatching
await dp.start_polling(bot)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logger.info("Bot stopped!")

View file

@ -1,4 +1,5 @@
import logging
import sys
from os import getenv
from aiohttp.web import run_app
@ -45,5 +46,5 @@ def main():
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
main()