php-telegram-bot / core

PHP Telegram Bot based on the official Telegram Bot API
MIT License
3.81k stars 951 forks source link

My BOT doesn't work - It does nothing #1471

Open gubi opened 1 week ago

gubi commented 1 week ago

Hi, I run my BOT on a VPS which has everything configured as well. I installed and carefully configured all but no response from the bot and it does not save anything in the database. If called from the chat the BOT does not reply and stay silent. Note that xxxx values are right setted but censored in this chat...

My configurations

config.php:

// Add you bot's API key and name
    'api_key'      => 'xxxx',
    'bot_username' => 'xxxx', // Without "@"

    // [Manager Only] Secret key required to access the webhook
    'secret'       => 'xxxx',

    // When using the getUpdates method, this can be commented out
    'webhook'      => [
        'url' => 'xxxx',
        // Use self-signed certificate
        'certificate'     => __DIR__ . '/certs/cert.pem',
        // Limit maximum number of connections
        // 'max_connections' => 5,
        // (array) List the types of updates you want your bot to receive.
        // 'allowed_updates' => ['message', 'edited_channel_post', 'callback_query'],
    ],

    // (bool) Only allow webhook access from valid Telegram API IPs.
    // 'validate_request' => true,
    // (array) When using `validate_request`, also allow these IPs.
    // 'valid_ips'        => [],

    // (array) All options that have to do with the limiter.
    'limiter'          => [
        // (bool) Enable or disable the limiter functionality.
        'enabled' => true,
        // (array) Any extra options to pass to the limiter.
        'options' => [
            // (float) Interval between request handles.
            'interval' => 0.5,
        ],
    ],

    // Define all IDs of admin users
    // 'admins'       => [xxxx],

    // All command related configs go here
    'commands'     => [
        'paths'   => [
            // __DIR__ . '/Commands/Message',
            // __DIR__ . '/Commands/Other',
            // __DIR__ . '/Commands/Payments',
        ],
        // Here you can set any command-specific parameters
        'configs' => [
            // - Google geocode/timezone API key for /date command (see DateCommand.php)
            // 'date'    => ['google_api_key' => 'your_google_api_key_here'],
            // - OpenWeatherMap.org API key for /weather command (see WeatherCommand.php)
            // 'weather' => ['owm_api_key' => 'your_owm_api_key_here'],
            // - Payment Provider Token for /payment command (see Payments/PaymentCommand.php)
            // 'payment' => ['payment_provider_token' => 'your_payment_provider_token_here'],
        ],
    ],

    // Enter your MySQL database credentials
    'mysql'        => [
        'host'     => 'localhost',
        'user'     => 'xxxx',
        'password' => 'xxxx',
        'database' => 'xxxx',
    ],

    // Logging (Debug, Error and Raw Updates)
    'logging'  => [
        'debug'  => __DIR__ . '/php-telegram-bot-debug.log',
        'error'  => __DIR__ . '/php-telegram-bot-error.log',
        'update' => __DIR__ . '/php-telegram-bot-update.log',
    ],

    // Set custom Upload and Download paths
    'paths'        => [
        'download' => __DIR__ . '/Download',
        'upload'   => __DIR__ . '/Upload',
    ]

cron.php:

$commands = [
    '/whoami',
    "/echo I'm a bot!",
];

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

// Load all configuration options
/** @var array $config */
$config = require __DIR__ . '/config.php';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']);

    /**
     * Check `hook.php` for configuration code to be added here.
     */

    // Run user selected commands
    $telegram->runCommands($commands);

} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Log telegram errors
    Longman\TelegramBot\TelegramLog::error($e);

    // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!)
    // echo $e;
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
    // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!)
    // echo $e;
}

hook.php

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

// For all update types currently implemented in this library:
$getUpdateTypes = Update::getUpdateTypes();

// Define the list of allowed Update types manually:
// $allowed_updates = [
//     Update::TYPE_MESSAGE,
//     Update::TYPE_CHANNEL_POST,
//     // etc.
// ];

$config = require __DIR__ . '/config.php';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']);

    // Enable admin users
    $telegram->enableAdmins($config['admins']);

    // Add commands paths containing your custom commands
    $telegram->addCommandsPaths($config['commands']['paths']);

    // Logging
    // $telegram->setLogRequests(true);
    // $telegram->setLogPath($BOT_NAME . '.log');
    // $telegram->setLogVerbosity(3);

    // Enable MySQL if required
    $telegram->enableMySql($config['mysql']);

    // Logging (Error, Debug and Raw Updates)
    // https://github.com/php-telegram-bot/core/blob/master/doc/01-utils.md#logging
    //
    // (this example requires Monolog: composer require monolog/monolog)
    // \Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . '/' . $BOT_NAME . '_update.log');
    // \Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . '/' . $BOT_NAME . '_debug.log');
    // \Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . '/' . $BOT_NAME . '_error.log');

    Longman\TelegramBot\TelegramLog::initialize(
       new Monolog\Logger('telegram_bot', [
           (new Monolog\Handler\StreamHandler($config['logging']['debug'], Monolog\Logger::DEBUG))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)),
           (new Monolog\Handler\StreamHandler($config['logging']['error'], Monolog\Logger::ERROR))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true)),
       ]),
       new Monolog\Logger('telegram_bot_updates', [
           (new Monolog\Handler\StreamHandler($config['logging']['update'], Monolog\Logger::INFO))->setFormatter(new Monolog\Formatter\LineFormatter('%message%' . PHP_EOL)),
       ])
    );

    // Set custom Download and Upload paths
    $telegram->setDownloadPath($config['paths']['download']);
    $telegram->setUploadPath($config['paths']['upload']);

    // Load all command-specific configurations
    foreach ($config['commands']['configs'] as $command_name => $command_config) {
        $telegram->setCommandConfig($command_name, $command_config);
    }
    // $telegram->setWebhook($config["webhook"]["url"], [
    //     'certificate' => $config["webhook"]["certificate"],
    //     'allowed_updates' => $getUpdateTypes
    // ]);

    $telegram->handleGetUpdates(['allowed_updates' => $getUpdateTypes]);

    // Requests Limiter (tries to prevent reaching Telegram API limits)
    $telegram->enableLimiter($config['limiter']);

    // Handle telegram getUpdate request
    // $ServerResponse = $telegram->handleGetUpdates();
    // Handle telegram webhook request
    $ServerResponse = $telegram->handle();
    if ($ServerResponse->isOk()) {
        $n_update = count($ServerResponse->getResult());
        print(date('Y-m-d H:i:s', time()) . ' - Processed ' . $n_update . ' updates' . "\n");
    } else {
        print(date('Y-m-d H:i:s', time()) . ' - Failed to fetch updates' . "\n");
        echo $ServerResponse->printError() . "\n";
    }
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Log telegram errors
    Longman\TelegramBot\TelegramLog::error($e);

    // Uncomment this to output any errors (ONLY FOR DEVELOPMENT!)
    // echo $e;
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
    // Uncomment this to output log initialisation errors (ONLY FOR DEVELOPMENT!)
    // echo $e;
}

manager.php:

use TelegramBot\TelegramBotManager\BotManager;

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

// Load all configuration options
/** @var array $config */
$config = require __DIR__ . '/config.php';

try {
    // $bot = new TelegramBot\TelegramBotManager\BotManager($config);
    $bot = new BotManager([
        // Add you bot's API key and name
        'api_key'      => $config['api_key'],
        'bot_username' => $config['bot_username'],

        // Secret key required to access the webhook
        'secret'       => $config['secret'],

        'webhook'      => [
            // When using webhook, this needs to be uncommented and defined
            'url' => 'xxxx',
            // Use self-signed certificate
            'certificate' => $config["webhook"]["certificate"],
            // Limit maximum number of connections
            'max_connections' => 20,
        ],
        'validate_request' => false,
        'commands'     => [
            // Define all paths for your custom commands
            'paths'   => $config["commands"]["paths"],
            // Here you can set some command specific parameters
            'configs' => $config["commands"]["configs"],
        ],

        // Define all IDs of admin users
        'admins'       => $config["admins"],

        // Enter your MySQL database credentials
        'mysql'        => $config["mysql"],

        // Logging (Error, Debug and Raw Updates)
        'logging'      => $config["logging"],

        // Set custom Upload and Download paths
        'paths'        => $config["paths"],

        // Requests Limiter (tries to prevent reaching Telegram API limits)
        'limiter'      => $config["limiter"],
    ]);

    $bot->setCustomGetUpdatesCallback(function (ServerResponse $get_updates_response) {
        $results = array_filter((array) $get_updates_response->getResult());

        return sprintf('There are %d update(s)' . PHP_EOL, count($results));
    });

    // Run the bot!
    $bot->run();

} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Log telegram errors
    Longman\TelegramBot\TelegramLog::error($e);

    // Uncomment this to catch log initialisation errors
    //echo $e;
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
    // Uncomment this to catch log initialisation errors
    //echo $e;
}

set.php:

require_once __DIR__ . '/vendor/autoload.php';

// Load all configuration options
/** @var array $config */
$config = require __DIR__ . '/config.php';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']);

    /**
     * REMEMBER to define the URL to your hook.php file in:
     * config.php: ['webhook']['url'] => 'https://your-domain/path/to/hook.php'
     */

    // Set the webhook
    $result = $telegram->setWebhook($config['webhook']['url']);
    // To use a self-signed certificate, use this line instead
    // $result = $telegram->setWebhook(
    //     $config['webhook']['url'],
    //     ['certificate' => $config['webhook']['certificate']]
    // );

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

unset.php:

require_once __DIR__ . '/vendor/autoload.php';

// Load all configuration options
/** @var array $config */
$config = require __DIR__ . '/config.php';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($config['api_key'], $config['bot_username']);

    // Unset / delete the webhook
    $result = $telegram->deleteWebhook();

    echo $result->getDescription();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    echo $e->getMessage();
}

The file certs/cert.pem is the same cert file file of the domain https connection, it's wrong?

Many thanks in advance

Hitmare commented 1 week ago

hey.

could you try and install the example bot on your VPS ?

https://github.com/php-telegram-bot/example-bot

upload those files to a new folder and use composer to install the core into it

gubi commented 1 week ago

Just a question before: in the file config.php, the section webhook/certificate must contain a custom .pem file, or the https public certificate of the Server?

Hitmare commented 1 week ago

It must have the certificate of the webserver, but only if its a self-signed one. if you use a "official" one like from letsencrypt, you dont need to do this

see https://core.telegram.org/bots/self-signed