Laravel中使用webhook开发Telegram机器人自定义指令

一、操作Telegram

1. 创建Telegram机器人

  1. 与@BotFather交谈,或者点击链接 : https://telegram.me/BotFather
  2. 点击Start
  3. 点击 /newbot
  4. 输入机器人名称 name,设置后可以修改
  5. 输入机器人用户名 username,必须以bot结尾,被@和搜索的名字,设置后无法修改
  6. 得到API Token

2. 创建command指令

  1. 点击/mybot
  2. 点击Edit Bot
  3. 点击Edit Commands
  4. 输入命令列表:
    command1 - 描述
    command2 - 描述
    例如:article - 查看或搜索文章

二、安装Telegram-Bot-SDK

1. 执行composer命令

composer require irazasyed/telegram-bot-sdk ^2.0

2. 修改config/app.php添加配置

'providers' => [
	Telegram\Bot\Laravel\TelegramServiceProvider::class
]
'aliases' => [
	'Telegram' => Telegram\Bot\Laravel\Facades\Telegram::class
]

3. 执行命令发布配置

php artisan vendor:publish --provider="Telegram\Bot\Laravel\TelegramServiceProvider"

4. 添加.env配置

TELEGRAM_BOT_TOKEN=API TOKEN
TELEGRAM_ASYNC_REQUESTS=false

三、使用Telegram-Bot-API

以Laravel-admin自定义行操作为例

<?php
namespace App\Admin\Actions\Article;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Telegram\Bot\Laravel\Facades\Telegram;

class SendToTGChannel extends RowAction
{
    public $name = '发送文章到TG频道';

    public $chat_id = '@xxxxx'; //@channelusername

    public function handle(Model $model)
    {
        $title = "<a href={https://domin/article/$model->id}>{$model->title}</a>";

        if ($model->cover) { //有封面 发图片
            $response = Telegram::sendPhoto([
                'chat_id' => $this->chat_id,
                'photo' => Storage::disk(config('admin.upload.disk'))->path($model->cover),
                'caption' => $title,
                'parse_model' => 'html', //支持html和markdown
            ]);
        } else {
            $response = Telegram::sendMessage([
                'chat_id' => $this->chat_id,
                'text' => $title,
                'parse_model' => 'html',
            ]);
        }

        $messageId = $response->getMessageId();
        if ($messageId) {
            return $this->response()->success('发送成功')->refresh();
        } else {
            return $this->response()->error('发送失败')->refresh();
        }
    }

    public function dialog()
    {
        $this->confirm('确定发送文章到TG频道?');
    }
}

四、设置Webhook

1. web应用添加路由

  1. 修改routes/web.php,添加Webhook URI到路由中,不能有需要授权的中间件
Route::post('/API TOKEN/webhook', function () {
    Telegram\Bot\Laravel\Facades\Telegram::commandsHandler(true);
});
  1. 修改app\Http\Middleware\VerifyCsrfToken.php,将webhook URI添加到$except数组
     protected $except = [
        '/API TOKEN/webhook',
    ];

2. API添加路由

  1. 修改routes/api.php
//dingo api
$api->post('v1/API TOKEN/webhook', function () {
	Telegram\Bot\Laravel\Facades\Telegram::commandsHandler(true);
});

3. 请求setWebhook接口,url参数必须支持https

curl https://api.telegram.org/botAPI TOKEN/setWebhook --data url=https://domain/API TOKEN/webhook

4. 通过getWebhookInfo接口查看Webhook信息

curl https://api.telegram.org/botAPI TOKEN/getWebhookInfo

五、自定义指令开发

1. 修改config/telegram.php添加指令

'commands' => [
    //Telegram\Bot\Commands\HelpCommand::class,
    App\Console\Telegram\Start::class,
    App\Console\Telegram\Help::class,
    App\Console\Telegram\Article::class,
],

2. 修改默认start指令

<?php

namespace App\Console\Telegram;

use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;

class Start extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'start';

    /**
     * @var string Command Description
     */
    protected $description = '开始';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        //回复消息
        $this->replyWithMessage(['text' => '你好!欢迎使用机器人,以下是我们可以用的指令:']);

        //切换到输入状态
        $this->replyWithChatAction(['action' => Actions::TYPING]);

        //触发帮助指令
        $this->triggerCommand('help');

        $this->replyWithMessage(['text' => '以下是热门文章:']);

        $this->replyWithChatAction(['action' => Actions::TYPING]);

        $this->triggerCommand('article');
    }
}

3. 修改默认help指令

<?php

namespace App\Console\Telegram;

use Telegram\Bot\Commands\Command;

class Help extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'help';

    /**
     * @var string Command Description
     */
    protected $description = '帮助';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        $commands = $this->telegram->getCommands();

        $text = '';
        foreach ($commands as $name => $handler) {
            $text .= sprintf('/%s - %s'.PHP_EOL, $name, $handler->getDescription());
        }

        $this->replyWithMessage(compact('text'));
    }
}

4. 添加自定义article指令

<?php

namespace App\Console\Telegram;

use App\Models\ArticleModel;
use Telegram\Bot\Commands\Command;

class Article extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = 'Article';

    /**
     * @var string Command Description
     */
    protected $description = '查看或搜索文章';

    /**
     * {@inheritdoc}
     */
    public function handle($arguments)
    {
        if ($arguments) {//搜索 /article 新冠肺炎	回复标题包含“新冠肺炎”的10篇文章
            $article = ArticleModel::where('title', 'LIKE', "%{$arguments}%")->take(10)->get();
        } else {
            $article = ArticleModel::orderBy('created_at', 'DESC')->take(10)->get();
        }

        $return = [
            'text' => '',
            'parse_mode' => 'html' //支持html和markdown
        ];

        foreach ($article as $item) {
            $return['text'] .= "
<a href={https://domin/article/$item->id}>{$item->title}</a>
            ";
        }

        $this->replyWithMessage($return);
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Spring Boot注册Telegram机器人,你需要遵循以下步骤: 1. 首先,你需要创建一个Telegram Bot账号,可以通过联系BotFather创建。 2. 在Spring Boot应用程序,你需要添加Telegram Bot库。可以使用TelegramBots库来实现这一点。 3. 在你的应用程序添加Telegram Bot的配置,包括Bot的token和Webhook URL。可以使用@BotConfiguration注释来实现这一点。 4. 创建一个WebhookController类并添加一个@PostMapping方法。该方法应该处理来自Telegram的所有请求。 5. 在你的应用程序,启动Webhook并将其链接到Telegram Bot API。可以使用TelegramBots库WebhookUtils类来实现这一点。 6. 最后,你需要启动你的Spring Boot应用程序。 下面是一个简单的示例代码,演示如何在Spring Boot注册Telegram机器人: ``` @BotConfiguration public class TelegramBotConfig { @Value("${telegram.bot.token}") private String botToken; @Value("${telegram.bot.webhook-url}") private String webhookUrl; @Bean public TelegramBot telegramBot() { TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); try { TelegramBot telegramBot = new MyTelegramBot(botToken); telegramBotsApi.registerBot(telegramBot); telegramBot.setWebhook(webhookUrl); return telegramBot; } catch (TelegramApiException e) { e.printStackTrace(); return null; } } } @RestController public class WebhookController { @PostMapping("${telegram.bot.webhook-url}") public ResponseEntity<Object> handleUpdate(@RequestBody Update update) { // 处理来自Telegram的请求 return ResponseEntity.ok().build(); } } @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在这个例子,我们创建了一个名为MyTelegramBot的TelegramBot类,并将它注册到Telegram Bot API。我们还创建了一个名为WebhookController的类,用于处理来自Telegram的请求。最后,我们在Spring Boot应用程序启动Webhook,并将它链接到Telegram Bot API
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值