Commands not recognised in php-telegram-bot on a laravel Project

孤者浪人 提交于 2019-12-13 03:50:48

问题


I'm using php-telegram-bot/core in larvel 5.5 to make a telegram bot.

I followed all installation and add custom commands described here.

First in the web.php route file I added this :

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

and this is BotController structure :

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();
        }

    }
}

And this is 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);
    }
}

As you can see I done all requirements to run a simple bot. but each time I send \start command to my bot I do not receive any response. seems that new updated sent from telegram to my host but my scripts can not recognize that.

I do not know what is problem is really


回答1:


I have done it using service provider and it works fine. There is a part of the structure of my app:

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/')
];

routes/api.php

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


来源:https://stackoverflow.com/questions/48385842/commands-not-recognised-in-php-telegram-bot-on-a-laravel-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!