Telegram bot开发,机器人第一次拉进群组会报错

机器人第一次拉入群组的时候会报错,显示获取不到用户发的信息

$path = "https://api.telegram.org/botMytoken";
$update = json_decode(file_get_contents("php://input"), TRUE);
$id = $update["update_id"];
$chatId = $update["message"]["chat"]["id"];
$username = $update["message"]["from"]["username"];
$message = $update["message"]["text"]; 

会显示获取不到 message 或者 text ,我用的 webhook,然后等pending_update_count为0,就可以正常用了,这是什么原因?
而且现在用 webhook 有个弊端,如果有报错,就会一直卡着,必须等推送完报错才能用机器人

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 1

我前一陣子也接入過 telegram bot

用的是 botman 套件 botman.io/

我在前端做一個 Enable Notification 的按鈕來把 Bot 加入 Telegram Channel

你可以試一下,這個套件整合的挺好的

// Frontend...
async function enableTelegramNotification()
{
    // https://core.telegram.org/bots#deep-linking

    // 我在 DB 中有一個 settings 的表 用來儲存 telegram_chat_id 和 telegram_notification_verification_key 
    const { data } = await axios.post('/api/settings/generate-enable-telegram-notifications-key')

    const url = `https://t.me/[your-bot-name]?startgroup=${data.key}`

    window.open(url, '_blank')
}

後端生成 Verification Key 來驗証

public function generateEnableTelegramNotificationsKey()
{
    $key = Str::random();

    Setting::updateOrCreate(
        ['key' => 'telegram_notification_verification_key'],
        ['value' => $key],
    );

    return response()->json(['key' => $key], 200);
}

驗証成功就把 chat_id 儲存起來

// TelegramBotmanController.php

// use...

class TelegramBotmanController extends Controller
{
    public function __invoke()
    {
        DriverManager::loadDriver(TelegramDriver::class);

        $botman = BotManFactory::create([
            'telegram' => config('botman.telegram')
        ], new LaravelCache());

        $botman->hears('/start.*', function (BotMan $bot) {
            $text = $bot->getMessage()->getText();

            $key = get_setting('telegram_notification_verification_key');

            if (Str::of($text)->contains($key)) {
                Setting::updateOrCreate(
                    ['key' => 'telegram_notification_verification_key'],
                    ['value' => null],
                );
                Setting::updateOrCreate(
                    ['key' => 'telegram_notification_chat_id'],
                    ['value' => request('message.chat.id')],
                );

                $bot->reply('Enable notification successfully!');
            } else {
                $bot->reply('Verification error, please try again.');
            }
        });

        $botman->listen();
    }
}

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!