php-telegram-bot/telegram-bot-manager

2.1.0 2023-05-27 17:17 UTC

README

Join the bot support group on Telegram Donate

Scrutinizer Code Quality Codecov Tests Status

Latest Stable Version Dependencies Total Downloads License

此项目基于 PHP Telegram Bot,因此依赖于它!

此微型库的主要目的是简化您的 web 服务器与 Telegram 之间的交互。我强烈建议您首先阅读 PHP Telegram Bot 的 说明,以了解此库的确切功能。

安装和使用相当简单

使用 Composer 需要此包

composer require php-telegram-bot/telegram-bot-manager:^2.1

注意: 这将自动将 PHP Telegram Bot 安装到您的项目中(如果尚未安装)。

高级: 由于核心库尚未是稳定版本,因此此项目部分锁定到核心版本,以确保可靠运行。

然而,可以覆盖此库要求的核心版本

"require": {
    "php-telegram-bot/telegram-bot-manager": "^2.1",
    "longman/telegram-bot": "dev-master as 0.81"
}

此示例将拉取核心库的主版本,使其看起来是版本 0.81,然后满足要求。

执行操作

如果无法执行任何操作,这个库有什么用?!

有一些参数可用于启动操作

通过浏览器

只需将您的浏览器指向具有必要 GET 参数的 manager.php 文件

  • http://example.com/manager.php?s=<secret>&a=<action>&l=<loop>&i=<interval>

Webhook

设置、清除和重置 webhook

  • http://example.com/manager.php?s=super_secret&a=set
  • http://example.com/manager.php?s=super_secret&a=unset
  • http://example.com/manager.php?s=super_secret&a=reset(清除 & 设置组合)

getUpdates

处理更新一次

  • http://example.com/manager.php?s=super_secret&a=handle 或简单地
  • http://example.com/manager.php?s=super_secrethandle 操作是默认操作)

处理 30 秒钟的更新,每 5 秒获取一次

  • http://example.com/manager.php?s=super_secret&l=30&i=5

cron

通过 cron 执行命令

  • http://example.com/manager.php?s=super_secret&a=cron&g=maintenance 或多个组
  • http://example.com/manager.php?s=super_secret&a=cron&g=maintenance,cleanup

通过 CLI

当使用 CLI 时,不需要密钥(因为它可以从文件本身读取)。

直接使用 php 调用 manager.php 文件并传递参数

  • $ php manager.php a=<action> l=<loop> i=<interval>

Webhook

设置、清除和重置 webhook

  • $ php manager.php a=set
  • $ php manager.php a=unset
  • $ php manager.php a=reset(清除 & 设置组合)

getUpdates

处理更新一次

  • $ php manager.php a=handle 或简单地
  • $ php manager.phphandle 操作是默认操作)

处理 30 秒钟的更新,每 5 秒获取一次

  • $ php manager.php l=30 i=5

cron

通过 cron 执行命令

  • $ php manager.php a=cron g=maintenance 或多个组
  • $ php manager.php a=cron g=maintenance,cleanup

创建管理 PHP 文件

你可以随意命名这个文件,只要它在你的PHP项目中某个地方(最好是根目录,这样会更方便)。(假设我们的文件叫做 manager.php

让我们从一个使用webhook方法的简单示例开始

<?php

use TelegramBot\TelegramBotManager\BotManager;

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

try {
    $bot = new BotManager([
        // Vitals!
        'api_key'      => '12345:my_api_key',

        // Extras.
        'bot_username' => 'my_own_bot',
        'secret'       => 'super_secret',
        'webhook'      => [
            'url' => 'https://example.com/manager.php',
        ]
    ]);
    $bot->run();
} catch (\Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}

设置重要的机器人参数

唯一的重要参数是API密钥

$bot = new BotManager([
    // (string) Bot API key provided by @BotFather.
    'api_key' => '12345:my_api_key',
    ...
]);

设置额外的机器人参数

除了必要的API密钥外,机器人可以通过额外的参数轻松配置。

设置webhook?启用管理员?添加自定义命令路径?

都没有问题!

secret 是一个用户自定义的密钥,用于通过webhook执行库的任何功能。最好让它很长、随机且非常独特!

对于84个随机字符

  • 如果你安装了 pwgen,只需执行 pwgen 84 1 并复制输出。
  • 如果你安装了 openssl,请使用 openssl rand -hex 84
  • 或者直接去 这里,并将所有输出放在一行中。

(你猜猜为什么84是个好数字?😉)

以下是所有可用额外参数的完整列表。

$bot = new BotManager([
    ...
    // (string) Bot username that was defined when creating the bot.
    'bot_username'     => 'my_own_bot',

    // (string) A secret password required to authorise access to the webhook.
    'secret'           => 'super_secret',

    // (array) All options that have to do with the webhook.
    'webhook'          => [
        // (string) URL to the manager PHP file used for setting up the webhook.
        'url'             => 'https://example.com/manager.php',
        // (string) Path to a self-signed certificate (if necessary).
        'certificate'     => __DIR__ . '/server.crt',
        // (int) Maximum allowed simultaneous HTTPS connections to the webhook.
        'max_connections' => 20,
        // (array) List the types of updates you want your bot to receive.
        'allowed_updates' => ['message', 'edited_channel_post', 'callback_query'],
        // (string) Secret token to validate webhook requests.
        'secret_token'    => 'super_secret_token',
    ],

    // (bool) Only allow webhook access from valid Telegram API IPs.
    'validate_request' => true,
    // (array) When using `validate_request`, also allow these IPs.
    'valid_ips'        => [
        '1.2.3.4',         // single
        '192.168.1.0/24',  // CIDR
        '10/8',            // CIDR (short)
        '5.6.*',           // wildcard
        '1.1.1.1-2.2.2.2', // range
    ],

    // (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,
        ],
    ],

    // (array) An array of user ids that have admin access to your bot (must be integers).
    'admins'           => [12345],

    // (array) Mysql credentials to connect a database (necessary for [`getUpdates`](#using-getupdates-method) method!).
    'mysql'            => [
        'host'         => '127.0.0.1',
        'port'         => 3306,           // optional
        'user'         => 'root',
        'password'     => 'root',
        'database'     => 'telegram_bot',
        'table_prefix' => 'tbl_prfx_',    // optional
        'encoding'     => 'utf8mb4',      // optional
    ],

    // (array) List of configurable paths.
    'paths'            => [
        // (string) Custom download path.
        'download' => __DIR__ . '/Download',
        // (string) Custom upload path.
        'upload'   => __DIR__ . '/Upload',
    ],

    // (array) All options that have to do with commands.
    'commands'         => [
        // (array) A list of custom commands paths.
        'paths'   => [
            __DIR__ . '/CustomCommands',
        ],
        // (array) A list of all custom command configs.
        'configs' => [
            'sendtochannel' => ['your_channel' => '@my_channel'],
            'weather'       => ['owm_api_key' => 'owm_api_key_12345'],
        ],
    ],

    // (array) All options that have to do with cron.
    'cron'             => [
        // (array) List of groups that contain the commands to execute.
        'groups' => [
            // Each group has a name and array of commands.
            // When no group is defined, the default group gets executed.
            'default'     => [
                '/default_cron_command',
            ],
            'maintenance' => [
                '/db_cleanup',
                '/db_repair',
                '/message_admins Maintenance completed',
            ],
        ],
    ],

    // (string) Override the custom input of your bot (mostly for testing purposes!).
    'custom_input'     => '{"some":"raw", "json":"update"}',
]);

使用getUpdates方法

使用 getUpdates 方法时必须设置 webhook 参数,并需要MySQL数据库连接

$bot = new BotManager([
    ...
    // Extras.
    'mysql' => [
        'host'         => '127.0.0.1',
        'port'         => 3306,           // optional
        'user'         => 'root',
        'password'     => 'root',
        'database'     => 'telegram_bot',
        'table_prefix' => 'tbl_prfx_',    // optional
        'encoding'     => 'utf8mb4',      // optional
    ],
]);

现在,可以通过 浏览器通过CLI 来处理更新。

自定义getUpdates输出

可以定义一个回调,以覆盖通过getUpdates处理更新时的默认输出。

默认输出的示例

...
2017-07-10 14:59:25 - Updates processed: 1
123456: <text>
2017-07-10 14:59:27 - Updates processed: 0
2017-07-10 14:59:30 - Updates processed: 0
2017-07-10 14:59:32 - Updates processed: 0
2017-07-10 14:59:34 - Updates processed: 1
123456: <photo>
2017-07-10 14:59:36 - Updates processed: 0
...

使用必须返回字符串的自定义回调

// In manager.php after $bot has been defined:
$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));
});

输出

...
There are 0 update(s)
There are 0 update(s)
There are 2 update(s)
There are 1 update(s)
...

开发

在分叉上运行实时机器人测试时,你必须将以下环境变量输入到你的 仓库设置

API_KEY="12345:your_api_key"
BOT_USERNAME="username_of_your_bot"

也许创建一个新的虚拟机器人会更合理。

安全

有关更多信息,请参阅 SECURITY

捐赠

我们对这个机器人的所有工作都是在我们的空闲时间里花费了许多小时编写的,以提供给您一个易于使用和扩展的Telegram机器人库。如果您喜欢使用这个库,并想表示感谢,捐赠是表达您支持的一种很好的方式。

捐赠将重新投资到项目中 👍

感谢您让这个项目保持活力 🙏

通过Tidelift订阅为该包获取专业支持
Tidelift帮助使开源对维护者可持续,同时为公司
提供关于其依赖项的安全性、维护和许可的保证。