php - 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。
解决方案
- 您需要使用数据库,这需要模型和迁移
- Telegram Bot API 将向您的 webhook 发送 POST 请求
- 您应该添加
->middleware('api')
,因为您将收到数据 - 用于
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');
推荐阅读
- java - 当我使用事件输入切换意图时,用户存储变得清晰
- sparql - Jena 似乎缓存了 BIND(RAND()) 查询
- generics - 将泛型从 Java 转换为 Kotlin
- angularjs - AngularJS服务功能在while循环完成后没有返回完整的承诺
- svelte - 如何像 Vue 一样在 Svelte 中制作无标签插槽模板
- vue.js - 如何向 v-data-table 添加点击事件?
- c# - 旋转 UILabel 的拉伸宽度
- python - 根据 MultiIndex DataFrame 中的第一级列删除重复项
- buildkite - 如何在 buildkite 中为存储库/管道级别添加访问控制?
- java - 错误:SqlExceptionHelper:HOUR_OF_DAY:2 -> 3