首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在laravel项目的php-电报-bot中未识别的命令

在laravel项目的php-电报-bot中未识别的命令
EN

Stack Overflow用户
提问于 2018-01-22 16:11:30
回答 1查看 2.2K关注 0票数 0

我正在用php-电报-bot/corelarvel 5.5中制作电报机器人。

我跟踪了所有的安装并添加了描述为这里的自定义命令。

首先,我在web.php路由文件中添加了以下内容:

代码语言:javascript
运行
复制
Route::get('/setwebhook', 'BotController@setWebhook');
Route::post('/webhook', ['as' => 'webhook', 'uses' => 'BotController@Webhook']);

这是BotController结构:

代码语言:javascript
运行
复制
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Longman\TelegramBot\Request;

class BotController extends Controller
{
    public $bot_api_key;
    public $bot_username;
    public $hook_url;
    public $commands_paths;

    function __construct ()
    {
        $this->bot_api_key    = 'my_api_key';
        $this->bot_username   = 'my_username';
        $this->hook_url       = 'https://e18ed4a5.ngrok.io/webhook';
        $this->commands_paths = [
            __DIR__ . '\app\Commands',
        ];
    }

    public function setWebhook ()
    {
        try {
            // Create Telegram API object
            $telegram = new \Longman\TelegramBot\Telegram($this->bot_api_key, $this->bot_username);
            // Set webhook
            $result = $telegram->setWebhook($this->hook_url);

            if ($result->isOk()) {
                echo $result->getDescription();
            }
        } catch (\Longman\TelegramBot\Exception\TelegramException $e) {
            // log telegram errors
            echo $e->getMessage();
        }
    }

    public function Webhook ()
    {
        try {
            // Create Telegram API object
            $telegram = new \Longman\TelegramBot\Telegram($this->bot_api_key, $this->bot_username);

            $telegram->addCommandsPaths($this->commands_paths);

            Request::setClient(new \GuzzleHttp\Client([
                'base_uri' => 'https://api.telegram.org',
                'verify'   => false
            ]));

            // Handle telegram webhook request
            $telegram->handle();
        } catch (\Longman\TelegramBot\Exception\TelegramException $e) {
            // Silence is golden!
            // log telegram errors
            echo $e->getMessage();
        }

    }
}

这是StartCommand

代码语言:javascript
运行
复制
namespace Longman\TelegramBot\Commands\UserCommands;

use Illuminate\Support\Facades\Log;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

class StartCommand extends UserCommand
{
    protected $name = 'start';

    protected $description = 'Start command';

    protected $usage = '/start';

    protected $version = '1.1.0';

    public function execute ()
    {

        Log::info('how are you');
        $message = $this->getMessage();

        $chat_id = $message->getChat()->getId();
        $text    = 'Welcome to my first bot';

        $data = [
            'chat_id' => $chat_id,
            'text'    => $text,
        ];

        return Request::sendMessage($data);
    }
}

如您所见,我完成了运行一个简单的机器人的所有要求。但是每次我向我的机器人发送\start命令时,我都不会收到任何响应。似乎新更新的电报发送给我的主机,但我的脚本无法识别。

我不知道问题到底是什么

EN

回答 1

Stack Overflow用户

发布于 2018-02-04 14:55:27

我已经使用服务提供商完成了它,它工作得很好。我的应用程序的结构中有一部分:

代码语言:javascript
运行
复制
app/Commands/{StartCommand.php, HelpCommand.php, ...}
app/Http/Controllers/TelegramController.php
app/Model/ExtendedTelegram.php
config/telegram.php

TelegramController.php

代码语言:javascript
运行
复制
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\ExtendedTelegram;

class TelegramController extends Controller
{
    public function run(Request $request, ExtendedTelegram $telegram)
        {
            if (config('telegram.webhook') === 'true') {
            $response = $telegram->getTelegram()->handle();
        } else {
            $response = $telegram->getTelegram()->handleGetUpdates();
        }

        return response()->json(['status' => 'success']);
   }

    public function setWebhook(Request $request, ExtendedTelegram $telegram)
    {
        $webhookUrl = config('app.hook_url') . '/run?token=' .     config('telegram.hook_token');
        $result = $telegram->getTelegram()->setWebhook($webhookUrl);

        return response()->json([
            'status' => $result->isOk() ? 'success' : 'error',
            'message' => $result->getDescription()
        ]);
    }

    public function unsetWebhook(Request $request, ExtendedTelegram $telegram)
    {
        $result = $telegram->getTelegram()->deleteWebhook();

        return response()->json([
            'status' => $result->isOk() ? 'success' : 'error',
            'message' => $result->getDescription()
        ]);
    }
}

app/Model/ExtendedTelegram.php .app

代码语言:javascript
运行
复制
<?php

namespace App\Model;

use Longman\TelegramBot\Telegram;

class ExtendedTelegram
{
    private $telegram = null;

    public function __construct()
    {
        $this->telegram = new Telegram(
            config('telegram.bot_api_key'),
            config('telegram.bot_username')
        );

        $commandsPaths = [
            realpath(app_path('Commands/'))
        ];
        $this->telegram->addCommandsPaths($commandsPaths);

        $this->telegram->enableAdmin(config('telegram.dev_id'));

        // Enable MySQL
        $mysqlConfig = config('database.connections.mysql');
        $this->telegram->enableMySql([
            'host' => $mysqlConfig['host'],
            'user' => $mysqlConfig['username'],
            'password' => $mysqlConfig['password'],
            'database' => $mysqlConfig['database'],
        ]);
    }

    /**
     * @return Telegram|null
     */
    public function getTelegram()
    {
        return $this->telegram;
    }
}

config/电报.

代码语言:javascript
运行
复制
<?php

return [
    'bot_api_key' => env('BOT_API_KEY', ''),
    'bot_username' => env('BOT_USERNAME', ''),
    'hook_url' => env('HOST', ''),
    'hook_token' => env('HOOK_TOKEN', ''),
    'webhook' => env('WEBHOOK', true),
    'dev_id' => env('DEV_ID', ''),
    'telegram_url' => env('TELEGRAM_URL', 'https://t.me/')
];

路由/api.php

代码语言:javascript
运行
复制
...
Route::any('/run', 'TelegramController@run');
Route::get('/set-webhook', 'TelegramController@setWebhook');
Route::get('/unset-webhook', 'TelegramController@unsetWebhook');
...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48385842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档