mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-14 02:52:12 +00:00
Add context manager support for bot client (#1468)
* Add context manager support for bot client The bot client now supports the context manager protocol, providing automatic resource management. This enhancement helps to automatically close the session when leaving the context, which cleans up resources better. The documentation and tests have been updated accordingly to illustrate this new feature. Moreover, an example of usage without a dispatcher has been provided to clarify its use in simple cases. * Added changelog
This commit is contained in:
parent
9756dac877
commit
4729978c60
5 changed files with 84 additions and 0 deletions
36
examples/without_dispatcher.py
Normal file
36
examples/without_dispatcher.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import asyncio
|
||||
from argparse import ArgumentParser
|
||||
|
||||
from aiogram import Bot
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
|
||||
|
||||
def create_parser() -> ArgumentParser:
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("--token", help="Telegram Bot API Token")
|
||||
parser.add_argument("--chat-id", type=int, help="Target chat id")
|
||||
parser.add_argument("--message", "-m", help="Message text to sent", default="Hello, World!")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
async def main():
|
||||
parser = create_parser()
|
||||
ns = parser.parse_args()
|
||||
|
||||
token = ns.token
|
||||
chat_id = ns.chat_id
|
||||
message = ns.message
|
||||
|
||||
async with Bot(
|
||||
token=token,
|
||||
default=DefaultBotProperties(
|
||||
parse_mode=ParseMode.HTML,
|
||||
),
|
||||
) as bot:
|
||||
await bot.send_message(chat_id=chat_id, text=message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue