noplanman/telegram-bot-manager

此软件包已被废弃且不再维护。作者建议使用 php-telegram-bot/telegram-bot-manager 软件包。

PHP 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"
}

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

执行操作

如果无法执行任何操作,此库有何用途?!

有一些参数可供您开始操作

参数 描述
s secret:这是一个在主 manager.php 文件中定义的特殊密钥值。
此参数是调用脚本的浏览器所必需的。
a action:要执行的实际操作。 (handle(默认),webhookinfo,cron,set,unset,reset)
handle 执行 getUpdates 方法; webhookinfo 获取 getWebhookInfo 的结果; cron 执行 cron 命令; set / unset / reset webhook。
l loop:脚本循环的秒数(用于 getUpdates 方法)。
这主要用于 CLI,以在一定时间内持续获取更新。
i interval:在 getUpdates 请求之间的等待秒数(用于 getUpdates 方法,默认为 2)。
这主要用于 CLI,以每隔 i 秒持续获取更新。
g group:cron 的命令组(仅与 cron 操作一起使用,默认组为 default)。
定义要执行哪个命令组的命令。可以是多个组的逗号分隔列表。

通过浏览器

只需将您的浏览器指向具有必要 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_secret (handle 动作是默认)

处理更新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.php (handle 动作是默认)

处理更新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

创建manager 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 Bot库。如果您喜欢使用这个库并且想表示感谢,捐赠是表达您支持的一种很好的方式。

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

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

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