AIogram:基于Python飞机Telegram Bot API全异步架构

正文概述 云码哥   2024-05-3   457

AIogram:基于Python飞机Telegram Bot API全异步架构

aiogram是Github上一个现代且完全异步的 Telegram Bot API 框架,使用 asyncio 和 aiohttp 以 Python 3.8 编写,让您的飞机Telegram机器人更快、更强大!

主要特点

  • 异步(asyncio 文档,492)
  • 具有类型提示 (484) 并且可以与 mypy 一起使用
  • 支持PyPy
  • 支持 Telegram Bot API 7.2 并快速更新到最新版本的 Bot API
  • Telegram Bot API 集成代码是自动生成的,并且可以在 API 更新时轻松重新生成
  • 更新路由器(蓝图)
  • 具有有限状态机
  • 使用强大的Magic filters
  • 中间件(传入更新和 API 调用)
  • Webhook 提供回复
  • 与 GNU Gettext(或 Fluent)集成的 I18n/L10n 支持

简单用法示例

import asyncio
import logging
import sys
from os import getenv

from aiogram import Bot, Dispatcher, html
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message

# Bot token can be obtained via https://t.me/BotFather
TOKEN = getenv("BOT_TOKEN")

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


@dp.message(CommandStart())
async def command_start_handler(message: Message) -> None:
    """
    This handler receives messages with `/start` command
    """
    # Most event objects have aliases for API methods that can be called in events' 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, {html.bold(message.from_user.full_name)}!")


@dp.message()
async def echo_handler(message: Message) -> None:
    """
    Handler will forward receive a message back to the sender

    By default, message handler will handle all message types (like a text, photo, sticker etc.)
    """
    try:
        # Send a 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!")


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))
    # And the run events dispatching
    await dp.start_polling(bot)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    asyncio.run(main())

无dispacher用法示例

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())

 

下载地址

Github       |        百度网盘

视频教程

基于Python和Aiogram飞机Telegram机器人开发视频教程

开发文档

https://docs.aiogram.dev/en/latest/

本站大部分资源收集于网络以及网友投稿,本不保证资源的完整性以及安全性,请下载后自行测试。
本站资源仅供下载者学习技术,版权归资源原作者所有,请在下载后24小时之内自觉删除。
本站资源仅供下载者学习IT编程开发技术,请遵守国家法律法规,严禁用于非法用途。
若作商业用途,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
如您是版权方,本站源码有侵犯到您的权益,请邮件联系331752841@qq.com 删除,我们将及时处理!