Skip to content

Latest commit

History

37 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TelegramPhp

GitHub licensePackagist DownloadsGitHub commit activityGitHub stars

👌 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

Requirements

  • PHP >= 7.0
    • cURL
    • JSON

Installation

composer require httd1/TelegramPhp

Usage:

<?phpinclude__DIR__.'/vendor/autoload.php';
use \TelegramPhp\TelegramPhp;
use \TelegramPhp\Methods;
use \TelegramPhp\Buttons;
// set bot token
\TelegramPhp\Config\Token::setToken ('110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw');
$tlg = newTelegramPhp;
$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'
]);
});

🔒 Secure

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);
}

Handling Commands

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');

Some methods available:

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.

Buttons:

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 ()
]);
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()
]);

Message reactions

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.

  • Reaction with ❤
    Reacting with ❤
Methods::setMessageReaction ([
'chat_id' => $bot->getChatId (),
'message_id' => $bot->getMessageId (),
'reaction' => Reaction::reactionType ([
Reaction::reactionTypeEmoji (''),
])
]);
  • Reacting with custom emojis5445284980978621387
    Reacting with custom emojis
Methods::setMessageReaction ([
'chat_id' => $bot->getChatId (),
'message_id' => $bot->getMessageId (),
'reaction' => Reaction::reactionType ([
Reaction::reactionTypeCustomEmoji ('5445284980978621387'),
])
]);

Send files:

  • 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'
]);

Download files

$file = Methods::getFile ([
'file_id' => 'CQACAgEAAxkBAAIBRGMFiJ_7zH2y9lJZxnn-XesvrBIhAALrAgACBcf5R68w-Z9ZMsgUKQQ'
]);
var_dump ($bot->saveFile ($file, __DIR__.'/music.mp3'));

Logs

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 requiredpublicfunctionlog ($telegramPhp, $action, $route, $data){
// process data
}
}
  • Setting class LogCommands on the \TelegramPhp\Config\Logs
\TelegramPhp\Config\Logs::catchLogs ([
LogCommands::class,
// LogStatistics::class
]);

Updates types

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

About

This is a PHP package designed to interact with the Telegram Bot API easily and efficiently.

Topics

Resources

Stars

11 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages