httd1 / telegramphp
这是一个用于使用Telegram Bot API的PHP包
Requires
- php: >=7.0
- ext-curl: *
Requires (Dev)
- phpunit/phpunit: ^9.5
README
这是一个PHP包,用于使用Telegram Bot API。
该包专为Webhook使用而设计,使用前请在此处阅读Telegram完整文档:https://core.telegram.org/bots/api
要求
- PHP>=7.0
- cURL
- JSON
安装
composer require httd1/TelegramPhp
使用
<?php include __DIR__.'/vendor/autoload.php'; use \TelegramPhp\TelegramPhp; use \TelegramPhp\Methods; use \TelegramPhp\Buttons; // set bot token \TelegramPhp\Config\Token::setToken ('110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw'); $tlg = new TelegramPhp; $tlg->command ('/start', function ($bot){ // send message Methods::sendMessage ([ 'chat_id' => $bot->getChatId (), 'text' => 'Hello 👋' ]); }); // Passing parameters to a command with {{info}} $tlg->command ('/get {{info}}', function ($bot, $data){ switch ($data ['info']){ case 'id': $user_info = $bot->getUserId (); break; case 'username': $user_info = $bot->getUsername (); break; case 'name': $user_info = $bot->getFullName (); break; default: $user_info = "Use <code>/get id or username or name</code>"; } Methods::sendMessage ([ 'chat_id' => $bot->getChatId (), 'text' => "User Info: <b>{$user_info}</b>", 'parse_mode' => 'html', 'reply_markup' => Buttons::inlineKeyBoard ([ [Buttons::inlineKeyBoardUrl ("Link My Profile", "tg://user?id=".$bot->getUserId ())], [Buttons::inlineKeyBoardCallbackData ("Ok, Thanks 👍", "/ok")] ]) ]); }); // match pattern $tlg->commandMatch ('/^\/ok$/', function ($bot){ Methods::answerCallbackQuery ([ 'callback_query_id' => $bot->getCallbackQueryId (), 'text' => '💪 Bro' ]); }); // commandDefault aways in the end of code! $tlg->commandDefault (function ($bot){ Methods::sendMessage ([ 'chat_id' => $bot->getChatId (), 'text' => 'Chose a command /start, /info with id, name or username' ]); });
🔒 安全
Telegram提供了一些方法来验证接收到的请求确实来自其服务器(更多信息),您可以在Webhook中设置一个secret_token,所有请求都将包含一个名为X-Telegram-Bot-Api-Secret-Token的header中的秘密token。使用此包,您还可以验证您的secret_token。
$secret_token = 'wubbalubbadub_dub'; // set secret_token in webhook // Methods::setWebhook ([ // 'url' => 'https://url.com/mybot/', // 'secret_token' => $secret_token // ]); // my secret token $tlg->setSecretToken ($secret_token); if ($tlg->checkSecretToken () == false){ http_response_code (401); }
响应命令
使用command ()、commandMatch ()或commandDefault方法来捕获发送到机器人的命令,将为该命令执行一个回调函数或一个类的方法。
command ()- 用于标准命令/comando或任何简单的字符串,您认为它是命令,例如“👍”!使用{{param}},您可以命名期望在命令中接收的参数。
$tlg->command ('👍', function ($bot){ // process command... }); $tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', function ($bot, $data){ // $data ['color_1']... // process command... }); // run the colors method of ClassBot class // $tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', 'ClassBot:methodColors'); // for namespace use '\MyNamespace\ClassBot:colors' // $tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', '\MyNamespace\ClassBot:colors');
commandMatch ()- 用于遵循不同模式的命令,与特定正则表达式匹配的命令,例如Telegram URL!
// telegram urls https://t.me/botfather, https://t.me/TelegramBR $tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', function ($bot, $data){ // $data [0] // process command... }); // run the executeLinks method of TelegramBot class // $tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', 'TelegramBot:executeLinks'); // for namespace use '\MyNamespace\ClassBot:colors' // $tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', '\MyNamespace\TelegramBot:executeLinks');
commandDefault ()- 当没有与command或commandMatch匹配时执行的默认命令。
// ...command // ...commandMatch // in the end of code! $tlg->commandDefault (function ($bot){ // send default message }); // $tlg->commandDefault ('ControllerBot:default');
一些可用的方法
getText ()、getUpdateType ()、getContent ()、getUserId ()、getUsername ()、getFirstName ()、getLastName ()、getFullName () - 用户的全名;getLanguageCode () - 用户的语言ID;getMessageId ()、getChatId ()、getMediaType () - 媒体类型,例如photo, animation, audio, document, sticker, story, video, video_note, voice, contact, dice, game, poll, venue, location, invoice;getCallbackQueryId ()、getChatType () - 聊天类型,例如private, group, supergroup, channel;saveFile () - 下载文件,接收getFile ()方法的返回值和文件目标;setSecretToken () - 定义用于Webhook请求的安全token(secret_token);checkSecretToken () - 验证与请求中定义的secret token一致的secret_token。
方法和按钮
如上例所示 ☝ 在静态类Methods中提供了Telegram API的所有方法,完整的方法列表在此,我们还有一个静态类Buttons用于创建内联按钮和键盘按钮。
Methods::sendMessage ([ 'chat_id' => $bot->getUserId (), 'text' => '(☞゚ヮ゚)☞', 'reply_markup' => Buttons::inlineKeyBoard ([ [Buttons::inlineKeyBoardCallbackData ('Hello', '/hello')], // [Buttons::inlineKeyBoardUrl ('Open Link', 'https://google.com')] ]) ]);
inlineKeyBoardUrl ()、inlineKeyBoardCallbackData ()、inlineKeyBoardWebApp ()、inlineKeyBoardLoginUrl ()、inlineKeyBoardSwitchInlineQuery ()、inlineKeyBoardSwitchInlineQueryCurrentChat ()、inlineKeyBoardPay ()
Methods::sendMessage ([ 'chat_id' => $bot->getUserId (), 'text' => 'Hello 👋', 'reply_markup' => Buttons::replyKeyBoardMarkup ([ [Buttons::keyBoardButtonText ('Hello')], // [Buttons::keyBoardButtonRequestContact ('share your contact')] ]) ]);
keyBoardButtonText ()、keyBoardButtonRequestContact ()、keyBoardButtonRequestLocation ()、keyBoardButtonRequestPoll ()、keyBoardButtonWebApp ()
Methods::sendMessage ([ 'chat_id' => $bot->getChatId (), 'text' => '😍🤔👌🔥🤦', 'reply_markup' => Buttons::forceReply () ]);
消息反应
机器人可以通过自定义表情符号或简单的表情符号(如👍, 👌, 🔥, 😍...)来对消息进行反应。
您可以在这里查看所有可用的反应列表
我们有一个静态类 Reaction 用于对消息进行反应。
Methods::setMessageReaction ([ 'chat_id' => $bot->getChatId (), 'message_id' => $bot->getMessageId (), 'reaction' => Reaction::reactionType ([ Reaction::reactionTypeEmoji ('❤'), ]) ]);
Methods::setMessageReaction ([ 'chat_id' => $bot->getChatId (), 'message_id' => $bot->getMessageId (), 'reaction' => Reaction::reactionType ([ Reaction::reactionTypeCustomEmoji ('5445284980978621387'), ]) ]);
发送文件
- 发送音频
Methods::sendAudio ([ 'chat_id' => $bot->getChatId (), 'audio' => curl_file_create (__DIR__.'/music.mp3'), 'caption' => 'Description music' ]);
- 发送图片
Methods::sendPhoto ([ 'chat_id' => $bot->getChatId (), 'photo' => curl_file_create (__DIR__.'/photo.jpg'), 'caption' => 'Description photo' ]);
- 发送视频
Methods::sendVideo ([ 'chat_id' => $bot->getChatId (), 'video' => curl_file_create (__DIR__.'/video.mp4'), 'caption' => 'Description video' ]);
- 发送文件
Methods::sendDocument ([ 'chat_id' => $bot->getChatId (), 'document' => curl_file_create (__DIR__.'/application.apk'), 'caption' => 'Description file' ]);
文件下载
$file = Methods::getFile ([ 'file_id' => 'CQACAgEAAxkBAAIBRGMFiJ_7zH2y9lJZxnn-XesvrBIhAALrAgACBcf5R68w-Z9ZMsgUKQQ' ]); var_dump ($bot->saveFile ($file, __DIR__.'/music.mp3'));
日志
您可以通过静态类 \TelegramPhp\Config\Logs 获取与机器人的交互日志,通过它,您可以定义一个或多个类来接收和处理用户交互数据。
- 负责处理日志的类。
class LogCommands { // method log is required public function log ($telegramPhp, $action, $route, $data){ // process data } }
- 定义将处理日志的类。
\TelegramPhp\Config\Logs::catchLogs ([ LogCommands::class, // LogStatistics::class ]);
更新类型
可以为特定类型的 Update 执行函数/方法,例如,您可以执行一个响应类型为 'my_chat_member' 或 'chat_member' 的函数。
- 处理 'my_chat_member' 更新
$tlg->on ('my_chat_member', function ($bot){ // code here }); // $tlg->on (['message_reaction', 'message'], function ($bot){ // code here // });
- 处理 'chat_member' 更新
$tlg->on ('chat_member', 'TelegramBot:myChatMember');
🔥 发送使用此包制作的机器人,它可能在此列出!
• J.M
- @scdownbot (+18K 用户)
- @twitterdlrobot (+11K 用户)
- @rastreiorobot (+14K 用户)
- @btn_bot (+200 用户)