【问题标题】:Commands not recognised in php-telegram-bot on a laravel Projectlaravel 项目的 php-telegram-bot 中无法识别的命令
【发布时间】:2018-07-01 08:03:22
【问题描述】:

我在 larvel 5.5 中使用php-telegram-bot/core 来制作电报机器人。

我遵循了所有安装并添加了here 中描述的自定义命令。

首先在web.php 路由文件中我添加了这个:

Route::get('/setwebhook', 'BotController@setWebhook');
Route::post('/webhook', ['as' => 'webhook', 'uses' => 'BotController@Webhook']);

这是BotController 结构:

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

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 命令时,我都没有收到任何响应。似乎从电报发送到我的主机的新更新,但我的脚本无法识别。

我不知道真的是什么问题

【问题讨论】:

    标签: php laravel telegram laravel-5.5 telegram-bot


    【解决方案1】:

    我已经使用服务提供商完成了它,它工作正常。 我的应用有一部分结构:

    app/Commands/{StartCommand.php, HelpCommand.php, ...}
    app/Http/Controllers/TelegramController.php
    app/Model/ExtendedTelegram.php
    config/telegram.php
    

    TelegramController.php

    <?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

    <?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/telegram.php

    <?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

    ...
    Route::any('/run', 'TelegramController@run');
    Route::get('/set-webhook', 'TelegramController@setWebhook');
    Route::get('/unset-webhook', 'TelegramController@unsetWebhook');
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 2018-08-15
      • 2022-07-12
      • 2023-01-22
      • 2021-11-10
      • 1970-01-01
      • 2020-08-15
      • 2021-08-21
      • 2015-04-22
      相关资源
      最近更新 更多