lex19 / telegram
telegram机器人SDK
2.1.0
2022-08-12 14:36 UTC
Requires
- php: ^8.0
- laravel/framework: ^9
- spatie/laravel-package-tools: ^1.9.2
This package is auto-updated.
Last update: 2024-09-09 03:23:54 UTC
README
您可以通过composer安装此包
composer require lex19/telegram
然后您需要发布配置并创建主接收器,该接收器将接收并处理来自telegram钩子的请求
php artisan telegram:install
如果您想通过telegram钩子接收消息,您需要为此创建一个路由
// routes/web.php use lex19\Telegram\Facades\Telegram; use App\Telegram\Receptions\MainReception; Route::any('hook', function(){ return Telegram::hook(MainReception::class); });
要安装钩子(setWebHook),您只需从这个机器人运行的域向该路由发送GET请求。
注意
127.0.0.1或localhost不适用。对于本地开发,您可以使用ngrok,并通过对该地址发起GET请求来安装钩子:https://sample-address-from-ngrok.ngrok.io/hook
用法
如果您只想通过telegram_id发送消息,您可以这样做
// AnyClass.php use lex19\Telegram\Facades\Telegram; Telegram::send([ "chat_id" => 123456, "text" => "hello stranger!" ]);
要回复来自机器人的消息,您需要创建一个命令
php artisan telegram:command CommandName
这将创建命令App\Telegram\Commands\CommandName
// app/Telegram/Commands/CommandName.php namespace App\Telegram\Commands; use lex19\Telegram\Command; class CommandName extends Command { public function handle() { return $this->telegram->send('hello'); } }
然后您可以在接收器中定义此命令的commands属性
// app/Telegram/Receptions/MainReception.php namespace App\Telegram\Receptions; use lex19\Telegram\BaseReception; class MainReception extends BaseReception { protected $commands = [ 'say hello' => \App\Telegram\Commands\CommandName::class ]; }
您可以通过不同的方式将命令绑定到请求上
// app/Telegram/Receptions/MainReception.php namespace App\Telegram\Receptions; use lex19\Telegram\BaseReception; use App\Telegram\Commands\CommandName; class MainReception extends BaseReception { protected $commands = [ 'say hello' => CommandName::class, 'say hello myFunc' => [CommandName::class, 'myFunc'], // you use not just 'handle' method ]; public function init() { $this->add('dynamic hello', [CommandName::class, 'dynamicHello']); $this->add([ 'dynamic hello 1' => [CommandName::class, 'dynamicHello1'], 'dynamic hello 2' => [CommandName::class, 'dynamicHello2'], ]); $command = new CommandName; $this->add('dynamic hello 3', [$command, 'dynamicHello3']); } }
如果您想执行以下消息的特定命令,而不考虑其内容,您可以在当前命令内定义它
// app/Telegram/Commands/CommandName.php namespace App\Telegram\Commands; use lex19\Telegram\Command; class CommandName extends Command { public function handle() { $this->setNext([CommandName::class, 'next']); // any next message will trigger this command return $this->telegram->send('hello'); } public function next() { $text = $this->telegram->text; return $this->telegram->send("I don't care what you wrote there, but here it is: $text"); } }