You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用irazasyed SDK处理Telegram webhook及接收消息的方法

Webhook 管理

基于irazasyed Telegram SDK,你可以通过以下方法管理已配置的Webhook:

  • 查询当前Webhook配置
    可直接调用getWebhookInfo方法获取当前Webhook的状态、pending更新数、错误信息等内容,示例代码:
Route::any('/getWebhookInfo', function () {
    return response()->json(Telegram::getWebhookInfo());
});
  • 删除现有Webhook
    如果需要切换Webhook地址、或者改用长连接模式拉取更新,可以调用deleteWebhook方法删除现有配置,支持传参清空未处理的更新:
Route::any('/deleteWebhook', function () {
    $response = Telegram::deleteWebhook([
        'drop_pending_updates' => true // 可选,清空所有未处理的更新推送
    ]);
    dd($response);
});
  • 注意事项
    • Webhook地址必须为HTTPS协议,本地测试用ngrok符合要求,生产环境需替换为自己的正式域名
    • 路径中添加的随机字符串是用于防恶意请求的验证标识,不要对外泄露
    • ngrok生成的临时域名每次重启服务都会变更,每次重启后需要重新调用setWebhook更新地址
处理Telegram推送的更新消息

1. 配置Webhook接收路由

首先需要配置你在setWebhook中填写的接收地址对应的路由,注意Telegram的推送为POST请求,路由需返回200状态码避免重复推送:

use Telegram\Bot\Laravel\Facades\Telegram;

Route::post('/NdqvlJstHyIUhmNyTZhCYTnoYxdGzoPcLCzDiMiH/webhook', function () {
    $update = Telegram::getWebhookUpdate();
    $chatId = $update->getMessage()->getChat()->getId();
    $messageText = $update->getMessage()->getText();

    // 优先处理系统命令
    Telegram::commandsHandler(true);

    // 读取当前会话的用户数据(SDK自带会话存储,默认存在storage目录,可配置为数据库存储)
    $chatData = Telegram::getChatData($chatId);

    // 状态判断:等待用户输入姓名
    if (isset($chatData['status']) && $chatData['status'] === 'awaiting_name') {
        // 保存用户输入的姓名到会话
        Telegram::setChatData($chatId, [
            'status' => 'normal',
            'user_name' => $messageText
        ]);
        // 回复用户
        Telegram::sendMessage([
            'chat_id' => $chatId,
            'text' => "已成功记录你的姓名:{$messageText},后续对话我会直接调用哦。"
        ]);
        return response('ok', 200);
    }

    // 正常对话逻辑,直接调用已保存的用户名
    if (isset($chatData['user_name'])) {
        Telegram::sendMessage([
            'chat_id' => $chatId,
            'text' => "你好{$chatData['user_name']},你刚刚发送的内容是:{$messageText}"
        ]);
        return response('ok', 200);
    }

    // 首次交互,未存储用户名的情况
    Telegram::sendMessage([
        'chat_id' => $chatId,
        'text' => '您好,请先告诉我您的姓名:'
    ]);
    Telegram::setChatData($chatId, ['status' => 'awaiting_name']);

    return response('ok', 200);
});

2. 可选:自定义命令

如果你需要支持/start这类命令触发交互,可以生成命令类并注册:

  • 执行命令生成命令类:php artisan make:telegram:command StartCommand
  • 在config/telegram.php的commands数组中注册生成的命令类
  • 在命令类的handle方法中编写触发逻辑,和上述路由中的首次交互逻辑一致即可

内容的提问来源于stack exchange,提问作者Charg3r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:21:02