dasturchiuz / telegram-bot
PHP Telegram bot
Requires
- php: ^5.5|^7.0
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- ext-pdo: *
- guzzlehttp/guzzle: ^6.3
- psr/log: ^1.1
Requires (Dev)
- dms/phpunit-arraysubset-asserts: ^0.1.0
- monolog/monolog: ^2.0
- phpunit/phpunit: ^8.4
- squizlabs/php_codesniffer: ^3.4
- dev-master
- 0.63.1
- 0.63.0
- 0.62.0
- 0.61.1
- 0.61.0
- 0.60.0
- 0.59.1
- 0.59.0
- 0.58.0
- 0.57.0
- 0.56.0
- 0.55.1
- 0.55.0
- 0.54.1
- 0.54.0
- 0.53.0
- 0.52.0
- 0.51.0
- 0.50.0
- 0.49.0
- 0.48.0
- 0.47.1
- 0.47.0
- 0.46.0
- 0.45.0
- 0.44.1
- 0.44.0
- 0.43.0
- 0.42.0
- 0.41.0
- 0.40.1
- 0.40.0
- 0.39.0
- 0.38.1
- 0.38.0
- 0.37.1
- 0.37.0
- 0.36
- 0.35
- 0.34
- 0.33
- 0.32
- 0.31
- 0.30
- 0.29
- 0.28.0
- 0.27.0
- 0.26.0
- 0.25.0
- 0.24.0
- 0.23.0
- 0.22.0
- 0.21.0
- 0.20.1
- 0.18.0
- 0.17.2
- 0.17.1
- 0.17.0
- 0.16.0
- 0.05
- 0.0.15
- 0.0.14
- 0.0.13
- 0.0.12
- 0.0.11
- 0.0.10
- 0.0.9
- 0.0.8
- 0.0.7
- 0.0.6
- 0.0.5.1
- 0.0.5
- 0.0.4
- 0.0.3.1
- 0.0.3
- 0.0.2
- 0.0.1
- dev-develop
- dev-feature/database-migrations
- dev-feature/refactor-app-design
This package is auto-updated.
Last update: 2024-09-08 18:56:22 UTC
README
PHP Telegram Bot
基于官方 Telegram Bot API 的 Telegram Bot
目录
简介
这是一个纯 PHP Telegram Bot,可以通过插件完全扩展。
Telegram 宣布了对 Bot API 的官方支持,允许各种集成商将自动化交互引入移动平台。此机器人旨在提供一个平台,只需几分钟即可编写机器人并进行交互。
机器人可以
- 使用 webhook 和 getUpdates 方法检索更新。
- 支持 Telegram Bot API 4.9(2020 年 6 月)的所有类型和方法。
- 支持超级群。
- 处理与其他机器人的聊天中的命令。
- 从机器人管理员界面管理频道。
- 完全支持 内联机器人。
- 内联键盘。
- 消息、内联查询和 ChosenInlineQuery 存储在数据库中。
- 会话功能。
此代码可在 GitHub 上找到。欢迎提出拉取请求。
说明
创建你的第一个机器人
-
向
@BotFather
发送以下文本:/newbot
如果你不知道如何通过用户名发送消息,请点击你的 Telegram 应用程序中的搜索字段,并输入
@BotFather
,你应该能够开始对话。请小心不要发送到错误联系人,因为有些用户与BotFather
有类似的用户名。 -
@BotFather
回复Alright, a new bot. How are we going to call it? Please choose a name for your bot.
-
输入你想为你的机器人输入的任何名称。
-
@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 个字符,并且必须以
bot
结尾。例如:telesample_bot
-
@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
-
记下上面提到的 'token'。
可选地设置机器人隐私
-
向
@BotFather
发送/setprivacy
。 -
@BotFather
回复Choose a bot to change group messages settings.
-
输入(或选择)
@telesample_bot
(将其更改为步骤 5 中设置的名称,但以@
开头) -
@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
-
输入(或选择)
Disable
以让您的机器人接收发送到群组的所有消息。 -
@BotFather
回复Success! The new status is: DISABLED. /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 更新
此机器人可以通过Webhook或getUpdates方法处理更新
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', 'port' => 3306, // optional '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
无数据库的 getUpdates
如果你选择/或必须在不使用数据库的情况下使用getUpdates
方法,你可以将上面的$telegram->useMySQL(...);
行替换为
$telegram->useGetUpdatesWithoutDatabase();
支持
类型
所有类型都是根据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
参数中
$result = Request::sendPhoto([ 'chat_id' => $chat_id, 'photo' => Request::encodeFile('/path/to/pic.jpg'), ]);
如果你知道已上传文件的file_id
,只需在数据数组中直接使用它即可
$result = Request::sendPhoto([ 'chat_id' => $chat_id, 'photo' => 'AAQCCBNtIhAoAAss4tLEZ3x6HzqVAAqC', ]);
为了发送远程照片,请使用直接URL
$result = Request::sendPhoto([ 'chat_id' => $chat_id, 'photo' => 'https://example.com/path/to/pic.jpg', ]);
sendAudio、sendDocument、sendAnimation、sendSticker、sendVideo、sendVoice和sendVideoNote都按相同的方式工作,只需查看API文档以了解确切用法。请参阅ImageCommand.php以获取完整示例。
发送聊天动作
Request::sendChatAction([ 'chat_id' => $chat_id, 'action' => Longman\TelegramBot\ChatAction::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, ] );
您还可以从与您的机器人的私密聊天中向用户广播消息。请参阅下面的管理命令。
过滤更新
可以通过定义自定义更新过滤器来允许或拒绝更新处理。假设我们只想允许ID为428的用户的消息,我们可以在处理请求之前做以下操作:
$telegram->setUpdateFilter(function (Update $update, Telegram $telegram, &$reason = 'Update denied by update_filter') { $user_id = $update->getMessage()->getFrom()->getId(); if ($user_id === 428) { return true; } $reason = "Invalid user with ID {$user_id}"; return false; });
拒绝更新的原因可以通过$reason
参数定义。此文本将被写入调试日志。
实用工具
MySQL 存储(推荐)
如果您想将消息/用户/聊天保存到数据库中,以供命令进一步使用,请创建一个新的数据库(utf8mb4_unicode_520_ci
),导入structure.sql,并在创建对象和handle()
方法之前启用MySQL支持。
$mysql_credentials = [ 'host' => 'localhost', 'port' => 3306, // optional '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)
频道支持
所有实现的方法都可以用来管理频道。通过管理命令,您可以直接通过您的机器人私聊来管理您的频道。
命令
预定义命令
机器人能够识别聊天中多个机器人下的命令(/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以获取更多信息和技术教程!欢迎改进!
资源
所有项目资产均可在assets存储库中找到。
示例机器人
我们正在忙于构建一个完整的A-Z示例机器人,以帮助您开始使用此库并展示如何使用所有功能。您可以查看example-bot存储库的进度)。
使用此库的项目
以下是一些使用此库的项目列表,欢迎您添加自己的项目!
- Inline Games (@inlinegamesbot)
- Super-Dice-Roll (@superdiceroll_bot)
- tg-mentioned-bot
- OSMdeWikiBot (@OSM_de)
故障排除
如果您喜欢走在前沿,请向PHP Telegram Bot问题页面报告您发现的任何错误。
贡献
有关更多信息,请参阅CONTRIBUTING。
安全
有关更多信息,请参阅SECURITY。
捐赠
我们利用业余时间投入了大量时间来编写这个机器人,旨在为您提供易于使用和扩展的Telegram Bot库。如果您喜欢使用此库并想表示感谢,捐赠是一种很好的支持方式。
捐赠将回馈到项目中 👍
感谢您让这个项目继续存在 🙏
Patreon.com/phptelegrambot
OpenCollective.com/php-telegram-bot
Ko-fi.com/phptelegrambot
Tidelift.com/longman/telegram-bot
Liberapay.com/PHP-Telegram-Bot
PayPal.me/noplanman(@noplanman的账户)
166NcyE7nDxkRPWidWtG1rqrNJoD5oYNiV
0x485855634fa212b0745375e593fAaf8321A81055
企业
作为Tidelift订阅的一部分提供。
PHP Telegram Bot
的维护者以及成千上万的其他包维护者正在与Tidelift合作,为构建应用程序时使用的开源依赖项提供商业支持和维护。节省时间,降低风险,提高代码质量,同时向使用确切依赖项的维护者支付费用。 了解更多。
许可证
请参阅此存储库中包含的LICENSE以获取MIT许可证的完整副本,该项目据此许可。
致谢
在CREDITS中列出信用。