uzdevid / yii2-telegrambot
用于在 PHP 框架 Yii2 上与 Telegram 机器人交互的扩展
dev-main
2022-07-12 06:46 UTC
Requires
- yiisoft/yii2: ~2.0.0
This package is auto-updated.
Last update: 2024-09-05 14:56:39 UTC
README
为创建 Telegram 机器人而优化的扩展
安装
您可以通过 composer 安装此扩展。
composer require uzdevid/yii2-telegrambot "dev-main"
使用方法
输入配置参数。
$config = [ 'token' => '<token>', 'parse_mode' => 'markdown', 'webhook_url' => '<webhook url>' ];
如果您只想向一个聊天发送消息,可以向此数组中添加 chat_id。
创建 Bot 类。
$bot = new TelegramBot($config);
向聊天发送普通消息。
$bot->send(['chat_id' => 1234567, 'text' => 'Hello world']);
如果配置中指定了 chat_id 并且只提供文本进行发送,可以使用以下方式
$bot->send(['Hello world']);
修改消息
$bot->edit(['message_id' => 1020, 'text' => "Yangi matn"]);
创建按钮
创建按钮
$bot->createKeyboard([ [['text' => "Button 1"]], [['text' => "Button 2"]] ]); $bot->send(['chat_id' => 1234567, 'text' => 'Mesage with url buttons']);
在消息下方(inline)创建按钮
$bot->createInlineKeyboard([ [['text' => "Button 1", 'url' => "https://google.com"]], [['text' => "Button 2", 'url' => "https://devid.uz"]] ]); $bot->send(['chat_id' => 1234567, 'text' => 'Mesage with url buttons']);
创建回调按钮
$bot->createInlineKeyboard([ [['text' => "Callback Button 1", 'callback_data' => json_encode(['command' => '/btn-1'])]] ]); $bot->send(['chat_id' => 1234567, 'text' => 'Mesage with callback']);
您可以向 callback_data 参数添加除 command 之外的额外参数。例如:id
$bot->createInlineKeyboard([ [[ 'text' => "Callback Button 1", 'callback_data' => json_encode(['command' => '/btn-1', 'id' => 100]) ]] ]); $bot->send(['chat_id' => 1234567, 'text' => 'Mesage with callback button and id']);
安装和移除 Webhook
在安装和移除 Webhook 时,配置中必须指定 webhook_url。其他情况下不要求。
安装 Webhook
$bot->setWebHook();
移除 Webhook
$bot->deleteWebHook();
接收 Bot 用户提出的问题,并返回回答。
$bot->onMessage('/start', function ($bot) { $bot->send("Chat ID: {$bot->chat_id}"); });
通过回调按钮处理问题。
$bot->onCallBack('/btn-1', function ($bot, $callback_data){ $bot->send("Siz /btn-1 tugmasini bosdingiz. Tugma id-si: " . $callback_data['id']); });
如您所见,这两种方法中,如果您通过 send 发送消息时没有指定 chat_id,则不需要。无论哪个用户提出问题,回答都将返回给同一用户。