Hey there, fellow developer! Ready to dive into the world of Telegram bots? You're in for a treat. Telegram's API is a powerhouse for creating interactive and engaging bots, and with the telegram-bot-sdk/telegram-bot-sdk
package, we're going to make it a breeze in PHP. Let's get cracking!
Before we jump in, make sure you've got:
Got all that? Great! Let's move on.
First things first, let's get our package installed. Fire up your terminal and run:
composer require telegram-bot-sdk/telegram-bot-sdk
Easy peasy, right? Now we're cooking with gas!
Time to initialize our Telegram API client. In your PHP file, add:
use Telegram\Bot\Api; $telegram = new Api('YOUR_BOT_TOKEN_HERE');
Replace 'YOUR_BOT_TOKEN_HERE'
with your actual bot token. Don't share this token with anyone, it's like the secret sauce of your bot!
Let's make our bot respond to messages:
$update = $telegram->getWebhookUpdate(); $message = $update->getMessage(); $chat_id = $message->getChat()->getId(); $text = $message->getText(); if ($text === '/start') { $telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => 'Hello! Welcome to my awesome bot!' ]); }
Want to add some cool commands? Here's how:
$telegram->addCommands([ Telegram\Bot\Commands\HelpCommand::class, YourCustomCommand::class, ]);
Spice things up with inline keyboards:
$keyboard = [ ['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0'] ]; $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => true ]); $telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => 'Choose a number:', 'reply_markup' => $reply_markup ]);
For those interactive buttons:
$callbackQuery = $telegram->getWebhookUpdate()->getCallbackQuery(); if ($callbackQuery !== null) { $data = $callbackQuery->getData(); // Handle the callback data }
You've got two options for getting updates: webhooks or long polling. Webhooks are more efficient, so let's set one up:
$telegram->setWebhook(['url' => 'https://your-domain.com/bot.php']);
Remember to replace 'https://your-domain.com/bot.php'
with your actual webhook URL.
Always be prepared for the unexpected:
try { // Your bot logic here } catch (\Exception $e) { error_log('Telegram Bot Error: ' . $e->getMessage()); }
Testing is crucial. Mock API responses to test your bot's logic:
$mockTelegram = $this->createMock(Api::class); $mockTelegram->method('sendMessage')->willReturn(/* mocked response */);
When deploying your bot, consider:
And there you have it! You're now equipped to create your own Telegram bot using PHP. Remember, this is just the beginning - there's so much more you can do with the Telegram API. Keep exploring, keep coding, and most importantly, have fun with it!
For more in-depth info, check out the Telegram Bot API documentation and the telegram-bot-sdk GitHub repo.
Now go forth and bot on! 🚀