egormanakin/telegram-bot-bundle

Telegram机器人包

安装: 1

依赖: 0

建议: 0

安全: 0

星标: 0

关注者: 0

分支: 23

类型:symfony-bundle

4.1.1 2020-10-24 07:42 UTC

README

Build Status

基于 telegram-bot/api 库的Telegram机器人包

示例

查看 示例项目

安装

Composer

$ composer require boshurik/telegram-bot-bundle

如果你使用 symfony/flex,只需设置 TELEGRAM_BOT_TOKEN 环境变量

注册包

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new BoShurik\TelegramBotBundle\BoShurikTelegramBotBundle,
    );
    // ...
}

添加webhook路由

BoShurikTelegramBotBundle:
    resource: "@BoShurikTelegramBotBundle/Resources/config/routing.yml"
    prefix: /_telegram/<some-secret>

配置

boshurik_telegram_bot:
    api:
        token: "%telegram_bot_api_token%"
        proxy: "socks5://127.0.0.1:8888"

使用

API

    $api = $this->container->get(TelegramBot\Api\BotApi::class);

更多信息请见 使用 部分在 telegram-bot/api

获取更新

bin/console telegram:updates

更多信息请见 官方文档

Webhook

设置
bin/console telegram:webhook:set <url> [<path-to-certificate>]
取消设置
bin/console telegram:webhook:unset

更多信息请见 官方文档

异步命令处理

为了提高性能,你可以利用 Messenger 通过Messenger传输稍后处理webhooks。

composer req symfony/messenger
# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: "%env(MESSENGER_TRANSPORT_DSN)%"

        routing:
            'BoShurik\TelegramBotBundle\Messenger\TelegramMessage': async

添加命令

命令必须实现 \BoShurik\TelegramBotBundle\Telegram\Command\CommandInterface

你可以从 \BoShurik\TelegramBotBundle\Telegram\Command\AbstractCommand 开始

要注册命令:在服务定义中添加标签 boshurik_telegram_bot.command

app.telegram.command:
    class: AppBundle\Telegram\Command\SomeCommand
    tags:
        - { name: boshurik_telegram_bot.command }

如果你使用 autoconfigure 标签将自动添加

存在预定义的 \BoShurik\TelegramBotBundle\Telegram\Command\HelpCommand。你需要注册它

app.telegram.command.help:
    class: BoShurik\TelegramBotBundle\Telegram\Command\HelpCommand
    arguments:
        - '@BoShurik\TelegramBotBundle\Telegram\Command\CommandRegistry'
    tags:
        - { name: boshurik_telegram_bot.command }

它显示实现 \BoShurik\TelegramBotBundle\Telegram\Command\PublicCommandInterface 的命令

事件

对于更复杂的应用(例如对话),你可以监听 BoShurik\TelegramBotBundle\Event\UpdateEvent 事件

/**
 * @param UpdateEvent $event
 */
public function onUpdate(UpdateEvent $event)
{
    $update = $event->getUpdate();
    $message = $update->getMessage();
}

使用Telegram登录

此包支持通过Telegram API进行登录

如果你想让你的机器人用户登录而无需重新注册,请遵循以下 说明