Laravel中使用webhook开发Telegram机器人自定义指令

蒲德曜
2023-12-01

一、操作Telegram

1. 创建Telegram机器人

  1. 与@BotFather交谈,或者点击链接 : https://telegram.me/BotFather
  2. 点击Start
  3. 点击 /newbot
  4. 输入机器人名称 name,设置后可以修改
  5. 输入机器人用户名 username,必须以bot结尾,被@和搜索的名字,设置后无法修改
  6. 得到API Token

2. 创建command指令

  1. 点击/mybot
  2. 点击Edit Bot
  3. 点击Edit Commands
  4. 输入命令列表:
    command1 - 描述
    command2 - 描述
    例如:article - 查看或搜索文章

二、安装Telegram-Bot-SDK

1. 执行composer命令

composer require irazasyed/telegram-bot-sdk ^2.0

2. 修改config/app.php添加配置

'providers' => [
	Telegram\Bot\Laravel\TelegramServiceProvider::class
]
'aliases' => [
	'Telegram' => Telegram\Bot\Laravel\Facades\Telegram::class
]

3. 执行命令发布配置

php artisan vendor:publish --provider="Telegram\Bot\Laravel\TelegramServiceProvider"

4. 添加.env配置

TELEGRAM_BOT_TOKEN=API TOKEN
TELEGRAM_ASYNC_REQUESTS=false

三、使用Telegram-Bot-API

以Laravel-admin自定义行操作为例

<?php
namespace App\Admin\Actions\Article;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Telegram\Bot\Laravel\Facades\Telegram;

class SendToTGChannel extends RowAction
{
    public $name = '发送文章到TG频道';

    public $chat_id = '@xxxxx'; //@channelusername

    public function handle(Model $model)
    {
        $title = "<a href={https://domin/article/$model->id}>{$model->title}</a>";

        if ($model->cover) { //有封面 发图片
            $response = Telegram::sendPhoto([
                'chat_id' => $this->chat_id,
                'photo' => Storage::disk(config('admin.upload.disk'))->path($model->cover),
                'caption' => $title,
                'parse_model' => 'html', //支持html和markdown
            ]);
        } else {
            $response = Telegram::sendMessage([
                'chat_id' => $this->chat_id,
                'text' => $title,
                'parse_model' => 'html',
            ]);
        }

        $messageId = $response->getMessageId();
        if ($messageId) {
            return $this->response()->success('发送成功')->refresh();
        } else {
            return $this->response()->error('发送失败')->refresh();
        }
    }

    public function dialog()
    {
        $this->confirm('确定发送文章到TG频道?');
    }
}

四、设置Webhook

1. web应用添加路由

  1. 修改routes/web.php,添加Webhook URI到路由中,不能有需要授权的中间件
Route::post('/API TOKEN/webhook', function () {
    Telegram\Bot\Laravel\Facades\Telegram::commandsHandler(true);
});
  1. 修改app\Http\Middleware\VerifyCsrfToken.php,将webhook URI添加到$except数组
     protected $except = [
        '/API TOKEN/webhook',
    ];

2. API添加路由

  1. 修改routes/api.php
//dingo api
$api->post('v1/API TOKEN/webhook', function () {
	Telegram\Bot\Laravel\Facades\Telegram::commandsHandler(true);
});

3. 请求setWebhook接口,url参数必须支持https

curl https://api.telegram.org/botAPI TOKEN/setWebhook --data url=https://domain/API TOKEN/webhook

4. 通过getWebhookInfo接口查看Webhook信息

curl https://api.telegram.org/botAPI TOKEN/getWebhookInfo

五、自定义指令开发

1. 修改config/telegram.php添加指令

'commands' => [
    //Telegram\Bot\Commands\HelpCommand::class,
    App\Console\Telegram\Start::class,
    App\Console\Telegram\Help::class,
    App\Console\Telegram\Article::class,
],

2. 修改默认start指令

<?php

namespace App\Console\Telegram;

use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;

class Start extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'start';

    /**
     * @var string Command Description
     */
    protected $description = '开始';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        //回复消息
        $this->replyWithMessage(['text' => '你好!欢迎使用机器人,以下是我们可以用的指令:']);

        //切换到输入状态
        $this->replyWithChatAction(['action' => Actions::TYPING]);

        //触发帮助指令
        $this->triggerCommand('help');

        $this->replyWithMessage(['text' => '以下是热门文章:']);

        $this->replyWithChatAction(['action' => Actions::TYPING]);

        $this->triggerCommand('article');
    }
}

3. 修改默认help指令

<?php

namespace App\Console\Telegram;

use Telegram\Bot\Commands\Command;

class Help extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'help';

    /**
     * @var string Command Description
     */
    protected $description = '帮助';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        $commands = $this->telegram->getCommands();

        $text = '';
        foreach ($commands as $name => $handler) {
            $text .= sprintf('/%s - %s'.PHP_EOL, $name, $handler->getDescription());
        }

        $this->replyWithMessage(compact('text'));
    }
}

4. 添加自定义article指令

<?php

namespace App\Console\Telegram;

use App\Models\ArticleModel;
use Telegram\Bot\Commands\Command;

class Article extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'Article';

    /**
     * @var string Command Description
     */
    protected $description = '查看或搜索文章';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        if ($arguments) {//搜索 /article 新冠肺炎	回复标题包含“新冠肺炎”的10篇文章
            $article = ArticleModel::where('title', 'LIKE', "%{$arguments}%")->take(10)->get();
        } else {
            $article = ArticleModel::orderBy('created_at', 'DESC')->take(10)->get();
        }

        $return = [
            'text' => '',
            'parse_mode' => 'html' //支持html和markdown
        ];

        foreach ($article as $item) {
            $return['text'] .= "
<a href={https://domin/article/$item->id}>{$item->title}</a>
            ";
        }

        $this->replyWithMessage($return);
    }
}
 类似资料: