๐ Read this documentation in Portuguese here
This is a package for the Telegram Bots API.
This package was made exclusively for use with Webhook.
Before using this package, please read the entire Telegram Bot API documentation: 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 provides ways to verify if a request actually comes from its servers (read more here).
You can set a secret_token in your webhook, and Telegram will include this token in the X-Telegram-Bot-Api-Secret-Token header.
This package allows you to validate your 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);
}Use the methods command (), commandMatch () or commandDefault to catch and handle commands sent to your bot. Each method receives a callback or class method.
command ()- Use for standard Telegram commands like /comando or simple inputs that you consider a command, such as '๐'. You can use{{param}}to define expected parameters.
$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 ()- For some kind of commands, you can build you own pattern using regular expression such as telegram urls for example!
// 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 ()- Fallback handler when no command matches.
// ...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 () - User full name; getLanguageCode () - List of languages ID; getMessageId (), getChatId (), getMediaType () - Media type, photo, animation, audio, document, sticker, story, video, video_note, voice, contact, dice, game, poll, venue, location, invoice; getCallbackQueryId (), getChatType () - Chat type, private, group, supergroup, channel; saveFile () - Download a file, receive with paramether a return of getFile () and the file destination; setSecretToken () - Set a token used in Webhook(secret_token) updates; checkSecretToken () - Checks the secret_token set on the the webhook.
Use the static Buttons class to create inline or reply keyboards.
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 (), inlineKeyBoardCopyText, inlineKeyBoardSwitchInlineQueryChosenChat
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 ()
]);forceReply ()- Force a reply to the message, documentation
Methods::sendMessage([
'chat_id' => $bot->getChatId(),
'text' => 'Message with force reply',
'reply_markup' => Buttons::forceReply()
]);replyKeyboardRemove ()- Removes the Telegram keyboard buttons and displays the device keyboard, documentation
Methods::sendMessage([
'chat_id' => $bot->getChatId(),
'text' => 'Keyboard removed',
'reply_markup' => Buttons::replyKeyboardRemove()
]);Telegram Bots can react to messages using simple emojis such as ๐, ๐, ๐ฅ, ๐... or custom emojis.
You can see the all available reaction emoji here
We have Reaction, an static class for reacting to messages.
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'),
])
]);- Send audio
Methods::sendAudio ([
'chat_id' => $bot->getChatId (),
'audio' => curl_file_create (__DIR__.'/music.mp3'),
'caption' => 'Description music'
]);- Send photo
Methods::sendPhoto ([
'chat_id' => $bot->getChatId (),
'photo' => curl_file_create (__DIR__.'/photo.jpg'),
'caption' => 'Description photo'
]);- Send video
Methods::sendVideo ([
'chat_id' => $bot->getChatId (),
'video' => curl_file_create (__DIR__.'/video.mp4'),
'caption' => 'Description video'
]);- Send file
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'));You can capture bot logs using \TelegramPhp\Config\Logs, symple set one or more classes to catch all user logs.
- Class to catch and process all user logs.
class LogCommands {
// method log is required
public function log ($telegramPhp, $action, $route, $data){
// process data
}
}- Setting class
LogCommandson the\TelegramPhp\Config\Logs
\TelegramPhp\Config\Logs::catchLogs ([
LogCommands::class,
// LogStatistics::class
]);It's possible to execute a callback for a specific type of Updates sent by the Telegram API, for example, executing a callback to 'my_chat_member' or 'chat_member'.
- Handling 'my_chat_member' updates
$tlg->on ('my_chat_member', function ($bot){
// code here
});
// $tlg->on (['message_reaction', 'message'], function ($bot){
// code here
// });- Handling 'chat_member' updates
$tlg->on ('chat_member', 'TelegramBot:myChatMember');๐ฅ Share your project made with this class, your project could be featured here!
โข J.M
- @scdownbot (+50K Users)
- @twitterdlrobot (+20K Users)
- Off @rastreiorobot (+14K Users)
- @btn_bot (+200 Users)
- @mailtemprobot (+5k Users)





