首页 > 解决方案 > Laravel 处理 Telegram 网络钩子

问题描述

我对 Laravel 还很陌生,最近我尝试创建一个可以管理传入消息并相应回复的 Telegram 机器人。最初,我计划在下次机器人回复时询问用户的姓名并使用他的姓名。

那么如何管理我已经设法设置的机器人的 webhook。

Route::any('/setWebhook', function () {
    $response = Telegram::setWebhook([
        'url' => 'https://57f7-2806-104e-c-5c3b-3dc7-3284-7383-e130.ngrok.io/NdqvlJstHyIUhmNyTZhCYTnoYxdGzoPcLCzDiMiH/webhook'
    ]);
    dd($response);
});

如何管理机器人的传入更新?我目前正在使用 irazasyed sdk。

标签: phplaraveltelegram

解决方案


  1. 您需要使用数据库,这需要模型和迁移
  2. Telegram Bot API 将向您的 webhook 发送 POST 请求
  3. 您应该添加->middleware('api'),因为您将收到数据
  4. 用于file_get_contents('php://input')获取更新,或使用库。

对我来说,我使用SimpleBotAPI 库

SimpleBotAPI 中的简单代码:

// Handle updates here
class BotHandler extends UpdatesHandler
{
    public function MessageHandler($message) : bool
    {
        // Do whatever:
        $this->Bot->SendMessage(['chat_id' => $message->chat->id, 'text' => 'new Message!']);
        return true;
    }
}

Route::post('/bot_webhook', function () {
    $Bot = new TelegramBot(env('BOT_TOKEN'), new BotHandler());
    $Bot->OnWebhookUpdate();
})->middleware('api');

推荐阅读