alexsisukin/php-telegram-bot-core

0.53 2018-01-30 12:26 UTC

This package is auto-updated.

Last update: 2024-09-29 04:36:54 UTC


README

Join the bot support group on Telegram Donate

Build Status Code Coverage Code Quality Latest Stable Version Total Downloads Downloads Month Minimum PHP Version License

一个基于官方 Telegram Bot API 的 Telegram Bot

目录

介绍

这是一个纯 PHP Telegram Bot,完全可以通过插件扩展。Telegram 最近宣布了对 Bot API 的官方支持,允许各种集成商将自动化交互带到移动平台。此机器人旨在提供一个平台,用户可以轻松编写插件,并在几分钟内完成交互。

此机器人可以

  • 通过 Webhook 和 getUpdates 方法检索更新。
  • 支持根据 Telegram API(2016 年 5 月 25 日)的所有类型和方法。
  • 支持超级群组。
  • 处理与其他机器人的聊天中的命令。
  • 从机器人管理员界面管理频道。
  • 完全支持 内联机器人
  • 内联键盘。
  • 消息、InlineQuery 和 ChosenInlineQuery 存储在数据库中。
  • Botan.io 集成和数据库缓存系统。(新功能!
  • 会话功能

此代码可在 Github 上找到。欢迎提交拉取请求。

说明

创建您的第一个机器人

  1. 向 @botfather 发送消息 https://telegram.me/botfather,内容如下: /newbot 如果您不知道如何通过用户名发送消息,请点击 Telegram 应用中的搜索字段并输入 @botfather,您应该能够开始对话。请注意不要发送给错误联系人,因为一些用户与 botfather 有相似的昵称。

    botfather initial conversation

  2. @botfather 回复: Alright, a new bot. How are we going to call it? Please choose a name for your bot.

  3. 输入您想要的机器人名称。

  4. @botfather 回复: Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

  5. 输入您想要的机器人用户名,至少 5 个字符,且必须以 bot 结尾。例如: telesample_bot

  6. @botfather 回复:

    Done! Congratulations on your new bot. You will find it at
    telegram.me/telesample_bot. You can now add a description, about
    section and profile picture for your bot, see /help for a list of
    commands.
    
    Use this token to access the HTTP API:
    123456789:AAG90e14-0f8-40183D-18491dDE
    
    For a description of the Bot API, see this page:
    https://core.telegram.org/bots/api
    
  7. 记下上面的 'token'。

  8. 向 @botfather 输入 /setprivacy

    botfather later conversation

  9. @botfather 回复: Choose a bot to change group messages settings.

  10. 输入(或选择) @telesample_bot(将其更改为步骤 5 上设置的名称,但以 @ 开头)

  11. @botfather 回复:

    'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
    'Disable' - your bot will receive all messages that people send to groups.
    Current status is: ENABLED
    
  12. 选择(或选择)禁用以让您的机器人接收发送到群组的所有消息。这一步由您决定。

  13. @botfather回复成功!新状态为:禁用。/help

使用 Composer 安装此包

通过Composer安装此软件包。编辑您项目的composer.json文件,以要求longman/telegram-bot

创建composer.json文件

{
    "name": "yourproject/yourproject",
    "type": "project",
    "require": {
        "php": ">=5.5",
        "longman/telegram-bot": "*"
    }
}

然后运行composer update

或者

在您的命令行中运行此命令

composer require longman/telegram-bot

选择如何获取 Telegram 更新

机器人可以通过WebhookgetUpdates方法处理更新

Webhook 安装

注意:对于更详细的说明,请访问example-bot存储库并遵循那里的说明。

要设置Webhook,您需要一个支持HTTPS和Composer的服务器。(对于自签名证书,您需要添加一些额外的代码)

创建包含以下内容的set.php

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

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';
$hook_url = 'https://your-domain/path/to/hook.php';

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

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

通过浏览器打开您的set.php以将Webhook注册到Telegram。您应该看到Webhook已设置

现在,创建包含以下内容的hook.php

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

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';

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

    // Handle telegram webhook request
    $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Silence is golden!
    // log telegram errors
    // echo $e->getMessage();
}

自签名证书

要上传证书,请将证书路径作为参数添加到set.php

$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);

取消 Webhook

使用您的机器人凭据编辑unset.php并执行它。

getUpdates 安装

MySQL数据库必须启用getUpdates方法!

创建包含以下内容的getUpdatesCLI.php

#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';
$mysql_credentials = [
   'host'     => 'localhost',
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];

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

    // Enable MySQL
    $telegram->enableMySql($mysql_credentials);

    // Handle telegram getUpdates request
    $telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // log telegram errors
    // echo $e->getMessage();
}

然后,给文件设置执行权限

$ chmod +x getUpdatesCLI.php

最后,运行它!

$ ./getUpdatesCLI.php

支持

类型

所有类型都是根据Telegram API(2016年1月20日)实现的。

内联查询

根据Telegram API(2016年1月20日)完全支持内联查询。

方法

所有方法都是根据Telegram API(2016年1月20日)实现的。

发送消息

超过4096个字符的消息将拆分为多个消息。

$result = Request::sendMessage(['chat_id' => $chat_id, 'text' => 'Your utf8 text 😜 ...']);

发送照片

要发送本地照片,请使用文件路径将其正确添加到$data参数中

$data = [
    'chat_id' => $chat_id,
    'photo'   => Request::encodeFile('/path/to/pic.jpg'),
];
$result = Request::sendPhoto($data);

如果您知道之前上传的文件的file_id,只需将其直接用于数据数组中

$data = [
    'chat_id' => $chat_id,
    'photo'   => $file_id,
];
$result = Request::sendPhoto($data);

要发送远程照片,请使用直接URL

$data = [
    'chat_id' => $chat_id,
    'photo'   => 'https://example.com/path/to/pic.jpg',
];
$result = Request::sendPhoto($data);

sendAudiosendDocumentsendStickersendVideosendVoicesendVideoNote都以相同的方式工作,只需查看API文档以获取确切用法。请参阅ImageCommand.php以获取完整示例。

发送聊天操作

Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']);

getUserProfilePhoto

检索用户照片,请参阅WhoamiCommand.php以获取完整示例。

getFile和downloadFile

获取文件路径并下载它,请参阅WhoamiCommand.php以获取完整示例。

向所有活跃聊天发送消息

为此,您必须启用MySQL连接。以下是一个示例用法(检查DB::selectChats()以检查参数用法)

$results = Request::sendToActiveChats(
    'sendMessage', // Callback function to execute (see Request.php methods)
    ['text' => 'Hey! Check out the new features!!'], // Param to evaluate the request
    [
        'groups'      => true,
        'supergroups' => true,
        'channels'    => false,
        'users'       => true,
    ]
);

您还可以从与您的机器人进行的私人聊天中向用户广播消息。请参阅下面的管理命令

实用工具

MySQL 存储(推荐)

如果您想要在命令中使用消息/用户/聊天,请创建一个新的数据库(utf8mb4_unicode_520_ci),导入structure.sql并在创建对象后、在handle()方法之前启用MySQL支持。

$mysql_credentials = [
   'host'     => 'localhost',
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];

$telegram->enableMySql($mysql_credentials);

在启用MySQL的同时,您可以为所有表设置一个自定义的前缀。

$telegram->enableMySql($mysql_credentials, $bot_username . '_');

您还可以将内联查询和所选内联查询数据存储在数据库中。

外部数据库连接

您可以向库提供外部MySQL PDO连接。以下是配置方法:

$telegram->enableExternalMySql($external_pdo_connection)
//$telegram->enableExternalMySql($external_pdo_connection, $table_prefix)

频道支持

所有实现的方法都可以用来管理频道。通过管理命令,您可以通过与机器人私聊直接管理您的频道。

Botan.io 集成(可选)

您可以使用以下行在您的hook.php中启用集成:

$telegram->enableBotan('your_token');

your_token替换为您的Botan.io令牌,查看此页面了解如何获取一个。

以下操作将被跟踪:

  • 命令(在统计中显示为Command (/command_name)
  • 内联查询、所选内联结果和回调查询
  • 发送给机器人的消息(或群组中的回复)

为了使用URL缩短器,您必须包含类use Longman\TelegramBot\Botan;并按如下方式调用它:

Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id);

如果启用了MySQL存储,缩短的URL将缓存在数据库中。

命令

预定义命令

机器人能够识别具有多个机器人的聊天中的命令(/command@mybot)。

它可以执行由聊天事件触发的命令。

以下是列表:

  • StartCommand.php(新用户开始使用机器人。)

  • NewChatMembersCommand.php(新成员加入群组,有关他们的信息。)

  • LeftChatMemberCommand.php(成员被移除出群组,有关他们的信息。)

  • NewChatTitleCommand.php(聊天标题更改为此值。)

  • NewChatPhotoCommand.php(聊天图片更改为此值。)

  • DeleteChatPhotoCommand.php(服务消息:聊天图片已被删除。)

  • GroupChatCreatedCommand.php(服务消息:已创建群组。)

  • SupergroupChatCreatedCommand.php(服务消息:已创建超级群组。)

  • ChannelChatCreatedCommand.php(服务消息:已创建频道。)

  • MigrateToChatIdCommand.php(群组已迁移到具有指定标识符的超级群组。)

  • MigrateFromChatIdCommand.php(超级群组已从具有指定标识符的群组迁移。)

  • PinnedMessageCommand.php(指定的消息被固定。)

  • GenericmessageCommand.php(处理任何类型的消息。)

  • GenericCommand.php(处理不存在的命令或用作变量的命令。)

    • 最喜欢的颜色?/black, /red
    • 最喜欢的数字?/1, /134

自定义命令

也许您想要开发自己的命令。这里有一份指南帮助您创建自己的命令

此外,请务必查看示例命令,以了解更多关于自定义命令及其工作方式的信息。

命令配置

使用此方法,您可以设置一些特定于命令的参数,例如

// Google geocode/timezone API key for /date command
$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']);

// OpenWeatherMap API key for /weather command
$telegram->setCommandConfig('weather', ['owm_api_key' => 'your_owm_api_key_here']);

管理员命令

启用此功能后,机器人管理员可以执行一些超级用户命令,如

  • 列出以机器人启动的所有聊天 /chats
  • 清理旧数据库条目 /cleanup
  • 显示机器人的调试信息 /debug
  • 向所有聊天发送消息 /sendtoall
  • 将任何内容发布到您的频道 /sendtochannel
  • 使用/whois检查用户或聊天

查看存储在src/Commands/AdminCommands/文件夹中的所有默认管理命令。

设置管理员

您可以使用此选项指定一个或多个管理员。

// Single admin
$telegram->enableAdmin(your_telegram_user_id);

// Multiple admins
$telegram->enableAdmins([your_telegram_user_id, other_telegram_user_id]);

使用/whoami命令可以获取Telegram用户ID。

频道管理

要启用此功能,请按照以下步骤操作

  • 将您的机器人添加为频道管理员,这可以通过任何Telegram客户端完成。
  • 如上所述管理员部分中所述,为您的用户启用管理员界面。
  • 将您的频道名称作为/sendtochannel命令的参数输入
$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel']]);
  • 如果您想管理更多频道
$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel', '@type_here_another_channel', '@and_so_on']]);
  • 享受吧!

上传和下载目录路径

要使用上传和下载功能,您需要使用以下方式设置路径

$telegram->setDownloadPath('/your/path/Download');
$telegram->setUploadPath('/your/path/Upload');

文档

请查看Wiki以获取更多信息和相关教程!请随意改进!

示例机器人

我们正在忙于构建一个完整的A-Z示例机器人,以帮助您开始使用此库,并展示如何使用所有功能。您可以查看示例机器人仓库的进度)。

使用此库的项目

以下是一些使用此库的项目列表,请随意添加您的项目!

故障排除

如果您喜欢前沿的技术,请将您在PHP Telegram Bot issues页面上发现的任何错误报告。

贡献

有关更多信息,请参阅CONTRIBUTING

捐赠

我们对这个机器人的所有工作都是在我们的业余时间用数小时代码完成的,以提供一个易于使用和扩展的Telegram Bot库。如果您喜欢使用这个库并且想表示感谢,捐款是表达您支持的一种很好的方式。

捐款会重新投入到项目中👍

许可证

请参阅此仓库中包含的LICENSE,以获取MIT许可证的完整副本,本项目据此许可。

致谢

CREDITS中列出信用清单。