php-telegram-bot / core

PHP Telegram Bot based on the official Telegram Bot API
MIT License
3.79k stars 949 forks source link

Commands not processed by default #1410

Closed iyamk closed 10 months ago

iyamk commented 10 months ago

🐞 Bug Report

Required Information

? !
Operating system Arch last
PHP Telegram Bot version 0.81.0
PHP version 8.2.9
MySQL version none
Update Method Webhook
Self-signed certificate no
RAW update (if available) {...}

Summary

I made a simple bot and it doesn't work. I need to process any commands in GenericCommand.php file

Current behaviour

Commands don't work! the request comes to the server without problems

How to reproduce

My Code

hook.php:

<?php

// Set the ranges of valid Telegram IPs.
// https://core.telegram.org/bots/webhooks#the-short-version
$telegram_ip_ranges = [
    ['lower' => '149.154.160.0', 'upper' => '149.154.175.255'], // literally 149.154.160.0/20
    ['lower' => '91.108.4.0', 'upper' => '91.108.7.255'],       // literally 91.108.4.0/22
];

$ip_dec = (float) sprintf("%u", ip2long($_SERVER['REMOTE_ADDR']));
$ok     = false;

foreach ($telegram_ip_ranges as $telegram_ip_range) {
    // Make sure the IP is valid.
    $lower_dec = (float) sprintf("%u", ip2long($telegram_ip_range['lower']));
    $upper_dec = (float) sprintf("%u", ip2long($telegram_ip_range['upper']));
    if ($ip_dec >= $lower_dec && $upper_dec >= $ip_dec) {
        $ok = true;
        break;
    }
}

if (!$ok) {
    echo "Hmm, I don't trust you...";
    file_put_contents('error.log', 'block access'."\n", FILE_APPEND);
    exit;
}

// Load composer
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = <API_KEY>;
$bot_username = <USER_ID>;

try {
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

    $telegram->handle();
}
catch (Longman\TelegramBot\Exception\TelegramException $e)
{
    file_put_contents('error.log', $e->getMessage()."\n", FILE_APPEND);
}
catch (Exception $e)
{
    file_put_contents('error.log', $e->getMessage()."\n", FILE_APPEND);
}

File Commands/GenericCommand.php:

<?php

/**
 * This file is part of the PHP Telegram Bot example-bot package.
 * https://github.com/php-telegram-bot/example-bot/
 *
 * (c) PHP Telegram Bot Team
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;

/**
 * Generic command
 *
 * Gets executed for generic commands, when no other appropriate one is found.
 */
class GenericCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'generic';

    /**
     * @var string
     */
    protected $description = 'Handles generic commands or is executed by default when a command is not found';

    /**
     * @var string
     */
    protected $version = '1.1.0';

    /**
     * Main command execution
     *
     * @return ServerResponse
     * @throws TelegramException
     */
    public function execute(): ServerResponse
    {
        $message = $this->getMessage();
        $user_id = $message->getFrom()->getId();
        $command = $message->getCommand();

        // To enable proper use of the /whois command.
        // If the user is an admin and the command is in the format "/whoisXYZ", call the /whois command
        if (stripos($command, 'whois') === 0 && $this->telegram->isAdmin($user_id)) {
            return $this->telegram->executeCommand('whois');
        }

        return $this->replyToChat("Command /{$command} not found.. :(");
    }
}

File Commands/Message/GenericmessageCommand.php:

<?php

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;

class GenericmessageCommand extends SystemCommand
{
    protected $name = 'genericmessage';
    protected $description = 'Handle generic message';
    protected $version = '1.0.0';

    public function execute(): ServerResponse
    {
        $message = $this->getMessage();

        $message_text = $message->getText(true);
        $result = Request::sendMessage([
            'chat_id' => $message->getFromId(),
            'text'    => $message_text
        ]);

        return Request::emptyResponse();
    }
}

composer.json:

{
    "name": "php/bot",
    "type": "project",
    "require": {
        "php": ">=7.3",
        "longman/telegram-bot": "0.81.0"
    }
}

Expected behaviour

This should work as an echo bot and also throw an error on unknown commands!

noplanman commented 10 months ago

Do you have any other GenericmessageCommand.php files anywhere within your custom commands folder?

There can only be one, as otherwise they will be overriding each other.

iyamk commented 10 months ago

Do you have any other GenericmessageCommand.php files anywhere within your custom commands folder?

There can only be one, as otherwise they will be overriding each other.

I have already figured out to add a folder in the path

    $telegram->addCommandsPaths([
        __DIR__.'/Commands'
    ]);

Other working bot examples help me and the documentation is very poor