### Initialize Telegram Bot
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Initializes a new Telegram bot client using the provided API key and starts the bot's event loop. Includes basic error handling for API exceptions.
```php
try
{
$bot = new \TelegramBot\Api\Client(API_KEY);
// Tell the bot what to do like waiting for callbacks or defining some commands
$bot->run();
}
catch (\TelegramBot\Api\Exception $e)
{
$e->getMessage();
}
```
--------------------------------
### Install Telegram Bot API Wrapper
Source: https://github.com/telegrambot/api/blob/master/README.md
Installs the Telegram Bot API wrapper using Composer. This is the primary method for adding the library to your PHP project.
```bash
$ composer require telegram-bot/api
```
--------------------------------
### Debug and Get Variables
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Provides a method for debugging by allowing access to the raw body of the response received from the Telegram API. This is helpful for understanding the data exchanged and troubleshooting issues.
```php
# This snippet is intended for debugging purposes to inspect raw API responses.
```
--------------------------------
### Create and Send Inline Keyboard
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Creates an inline keyboard with multiple options, including emojis, and sends it with a message. The callback data associated with each button is used to identify user interactions.
```php
$question = 'How can I help you?';
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup([
[
['text' => html_entity_decode("💙") . " Option 1", 'callback_data' => 'option1'],
['text' => html_entity_decode("💚") . " Option 2", 'callback_data' => 'option2'],
['text' => html_entity_decode("💛") . " Option 3", 'callback_data' => 'option3']
]
]);
$bot->sendMessage($message->getChat()->getId(), $question, null, false, null, $keyboard);
```
--------------------------------
### Define Bot Commands
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Defines a command handler for a specific command (e.g., 'telegram'). This function is executed when a user sends the defined command to the bot.
```php
$bot->command('telegram', function ($message) use ($bot) {
// Tell me what I should do here like sending a message or a photo
});
```
--------------------------------
### Dump Telegram Message Object
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
This example demonstrates how to dump the contents of a Telegram message object received via a callback query. It uses `var_dump` to inspect the object's properties and sends the resulting string back to the user.
```php
$bot->callbackQuery(function ($message) use ($bot) {
ob_start();
var_dump($message);
$result = ob_get_contents();
ob_flush();
$bot->sendMessage(
$message->getFrom()->getId(),
$result
);
})
```
--------------------------------
### Edit Message Content
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Demonstrates how to send a message and then edit its content. This involves first sending a temporary message to get its details, then deleting it.
```php
$temp_message = $bot->sendMessage(
$message->getFrom()->getId(),
"Asking my database, one moment ... 🎲",
"HTML"
);
$bot->deleteMessage(
$temp_message->getChat()->getId(),
$temp_message->getMessageId()
);
```
--------------------------------
### Handle Callback Queries
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Processes callback queries received when a user interacts with an inline keyboard button. It can send popup messages (answerCallbackQuery) and respond with new messages based on the button clicked.
```php
# This function is called if someone clicks on an inline button
$bot->callbackQuery(function ($message) use ($bot) {
if ($message->getData() == "option1")
{
// If you want you can send some kind of popup message after the user clicked one of the buttons
$bot->answerCallbackQuery($message->getId(), "You clicked on option1. Loading...");
$bot->sendMessage(
$message->getFrom()->getId(),
"Hi " . $message->getFrom()->getUsername() . ", you've choosen Option 1",
"HTML"
);
}
elseif ($message->getData() == "option2")
{
// If you want you can send some kind of popup message after the user clicked one of the buttons
$bot->answerCallbackQuery($message->getId(), "You clicked on option2. Loading...");
$bot->sendMessage(
$message->getFrom()->getId(),
"Hi " . $message->getFrom()->getUsername() . ", you've choosen Option 2",
"HTML"
);
}
elseif ($message->getData() == "option3")
{
// If you want you can send some kind of popup message after the user clicked one of the buttons
$bot->answerCallbackQuery($message->getId(), "You clicked on option3. Loading...");
$bot->sendMessage(
$message->getFrom()->getId(),
"Hi " . $message->getFrom()->getUsername() . ", you've choosen Option 3",
"HTML"
);
}
});
```
--------------------------------
### Running Tests with PHPUnit
Source: https://github.com/telegrambot/api/blob/master/CONTRIBUTING.md
This snippet shows the command to execute tests using PHPUnit, a popular unit testing framework for PHP. Ensure PHPUnit is installed and configured in your project.
```bash
phpunit
```
--------------------------------
### Send Photo
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Sends a photo to a specified chat ID. Allows for a caption with HTML formatting and specifies the file path or URL of the photo.
```php
$bot->sendPhoto(
$message->getChat()->getId(),
"https://telegram.org/file/464001876/2/61q3quSkA-o.229990/0448e8588e48b3942c",
"Some bold caption for the photo",
null,
null,
null,
"HTML"
);
```
--------------------------------
### Delete Message
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Shows how to send a message and then delete it. This is useful for cleaning up temporary messages or correcting previous bot responses.
```php
$temp_message = $bot->sendMessage(
$message->getFrom()->getId(),
"Asking my database, one moment ... 🎲",
"HTML"
);
$bot->deleteMessage(
$temp_message->getChat()->getId(),
$temp_message->getMessageId(),
);
```
--------------------------------
### Handle Telegram Callback Query
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
This snippet shows how to process a callback query received from an inline button click. It retrieves the raw request body and sends it back as a message to the user who initiated the query.
```php
$bot->callbackQuery(function ($message) use ($bot) {
$rawBody = $bot->getRawBody();
$bot->sendMessage(
$message->getFrom()->getId(),
$rawBody
);
}
```
--------------------------------
### Send Chat Action (Typing)
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Sends a 'typing' chat action to indicate that the bot is currently processing a request or preparing a response. This improves the user experience by providing visual feedback.
```php
$bot->command('letmetype', function ($message) use ($bot) {
# Send "Typing..."
$bot->sendChatAction(
$message->getChat()->getId(),
'typing'
);
});
```
--------------------------------
### Send Text Message
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
Sends a text message to a specified chat ID. Supports HTML formatting for rich text content.
```php
$bot->sendMessage(
$message->getChat()->getId(),
"",
"HTML"
);
```
--------------------------------
### Var Dump Output of Telegram Callback Query Object
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
This text output shows the result of using `var_dump` on a Telegram callback query object, detailing its properties and their values, including nested objects like User and Message.
```text
object(TelegramBot\Api\Types\CallbackQuery)#56 (7) {
"id":protected=>
string(18) "987654321098765432"
"from":protected=>
object(TelegramBot\Api\Types\User)#57 (6) {
"id":protected=>
int(45645645)
"firstName":protected=>
string(9) "ME"
"lastName":protected=>
NULL
"username":protected=>
string(9) "me"
"languageCode":protected=>
string(2) "de"
"isBot":protected=>
bool(false)
}
"message":protected=>
object(TelegramBot\Api\Types\Message)#58 (45) {
"messageId":protected=>
int(924)
"from":protected=>
object(TelegramBot\Api\Types\User)#59 (6) {
"id":protected=>
int(1231231231)
"firstName":protected=>
string(13) "someones"
"lastName":protected=>
NULL
"username":protected=>
string(17) "someones_bot"
"languageCode":protected=>
NULL
"isBot":protected=>
bool(true)
}
"date":protected=>
int(1594544189)
"chat":protected=>
object(TelegramBot\Api\Types\Chat)#60 (13) {
"id":protected=>
int(45645645)
"type":protected=>
string(7) "private"
"title":protected=>
NULL
"username":protected=>
string(9) "me"
"firstName":protected=>
string(9) "ME"
"lastName":protected=>
NULL
"allMembersAreAdministrators":protected=>
NULL
"photo":protected=>
NULL
"description":protected=>
NULL
"inviteLink":protected=>
NULL
"pinnedMessage":protected=>
NULL
"stickerSetName":protected=>
NULL
"canSetStickerSet":protected=>
NULL
}
"forwardFrom":protected=>
NULL
"forwardFromChat":protected=>
NULL
"forwardFromMessageId":protected=>
NULL
"forwardSignature":protected=>
NULL
"forwardSenderName":protected=>
NULL
"forwardDate":protected=>
NULL
"replyToMessage":protected=>
NULL
"editDate":protected=>
NULL
"mediaGroupId":protected=>
NULL
"authorSignature":protected=>
NULL
"text":protected=>
string(22) "How can I help you?"
"entities":protected=>
NULL
"captionEntities":protected=>
NULL
"audio":protected=>
NULL
"document":protected=>
NULL
"animation":protected=>
NULL
"photo":protected=>
NULL
"sticker":protected=>
NULL
"video":protected=>
NULL
"voice":protected=>
NULL
"caption":protected=>
NULL
"contact":protected=>
NULL
"location":protected=>
NULL
"venue":protected=>
NULL
"poll":protected=>
NULL
"dice":protected=>
NULL
"newChatMembers":protected=>
NULL
"leftChatMember":protected=>
NULL
"newChatTitle":protected=>
NULL
"newChatPhoto":protected=>
NULL
"deleteChatPhoto":protected=>
NULL
"groupChatCreated":protected=>
NULL
"supergroupChatCreated":protected=>
NULL
"channelChatCreated":protected=>
NULL
"migrateToChatId":protected=>
NULL
"migrateFromChatId":protected=>
NULL
"pinnedMessage":protected=>
NULL
"invoice":protected=>
NULL
"successfulPayment":protected=>
NULL
"connectedWebsite":protected=>
NULL
"replyMarkup":protected=>
NULL
}
"inlineMessageId":protected=>
NULL
"chatInstance":protected=>
string(20) "-1234567890123456789"
"data":protected=>
string(11) "option1"
"gameShortName":protected=>
NULL
}
```
--------------------------------
### Telegram Callback Query Response Structure
Source: https://github.com/telegrambot/api/wiki/Some-basic-examples
This JSON structure represents a typical callback query response from the Telegram Bot API, including details about the update, the callback query itself, and the associated message.
```json
{"update_id":27417224,
"callback_query":{"id":"987654321098765432","from":{"id":45645645,"is_bot":false,"first_name":"ME","username":"me","language_code":"de"},"message":{"message_id":924,"from":{"id":1231231231,"is_bot":true,"first_name":"someones","username":"someones_bot"},"chat":{"id":45645645,"first_name":"ME","username":"me","type":"private"},"date":1594544189,"text":"How can I help you?","reply_markup":{"inline_keyboard":[[{"text":"Option 1","callback_data":"option1"},{"text":"Option 2","callback_data":"option2"},{"text":"Option 3","callback_data":"option3"}]]}}},"chat_instance":"-1234567890123456789","data":"option1"}
```
--------------------------------
### Telegram Bot Client Usage
Source: https://github.com/telegrambot/api/blob/master/README.md
Provides a comprehensive example of using the Telegram Bot client to handle commands and text messages. It includes setting up command listeners and general message handlers.
```php
require_once "vendor/autoload.php";
try {
$bot = new \TelegramBot\Api\Client('YOUR_BOT_API_TOKEN');
//Handle /ping command
$bot->command('ping', function ($message) use ($bot) {
$bot->sendMessage($message->getChat()->getId(), 'pong!');
});
//Handle text messages
$bot->on(function (\TelegramBot\Api\Types\Update $update) use ($bot) {
$message = $update->getMessage();
$id = $message->getChat()->getId();
$bot->sendMessage($id, 'Your message: ' . $message->getText());
}, function () {
return true;
});
$bot->run();
} catch (\TelegramBot\Api\Exception $e) {
$e->getMessage();
}
```
--------------------------------
### Local Bot API Server Configuration
Source: https://github.com/telegrambot/api/blob/master/README.md
Configures the Telegram Bot client to use a custom local Bot API server. This is useful for testing or development environments.
```php
use TelegramBot\Api\Client;
$token = 'YOUR_BOT_API_TOKEN';
$bot = new Client($token, null, null, 'http://localhost:8081');
```
--------------------------------
### Send a Message with Telegram Bot API
Source: https://github.com/telegrambot/api/blob/master/README.md
Demonstrates how to send a simple text message to a chat using the Telegram Bot API wrapper. Requires a bot token and chat ID.
```php
$bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
$bot->sendMessage($chatId, $messageText);
```
--------------------------------
### Send Message with Reply Keyboard
Source: https://github.com/telegrambot/api/blob/master/README.md
Illustrates sending a message with a custom reply keyboard, allowing users to select predefined options. The keyboard can be set as one-time.
```php
$bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
$keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup(array(array("one", "two", "three")), true); // true for one-time keyboard
$bot->sendMessage($chatId, $messageText, null, false, null, $keyboard);
```
--------------------------------
### Send a Document with Telegram Bot API
Source: https://github.com/telegrambot/api/blob/master/README.md
Shows how to send a document file to a chat using the Telegram Bot API wrapper. It utilizes CURLFile for file uploads.
```php
$bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
$document = new \CURLFile('document.txt');
$bot->sendDocument($chatId, $document);
```
--------------------------------
### Send Message with Inline Keyboard
Source: https://github.com/telegrambot/api/blob/master/README.md
Demonstrates sending a message with an inline keyboard, which includes clickable buttons with URLs or callback data. Useful for interactive elements.
```php
$bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
[
[
['text' => 'link', 'url' => 'https://core.telegram.org']
]
]
);
$bot->sendMessage($chatId, $messageText, null, false, null, $keyboard);
```
--------------------------------
### Third-party HTTP Client Integration
Source: https://github.com/telegrambot/api/blob/master/README.md
Integrates a third-party HTTP client, such as Symfony's HttpClient, with the Telegram Bot API wrapper. This allows for more advanced network configurations.
```php
use Symfony\Component\HttpClient\HttpClient;
use TelegramBot\Api\BotApi;
use TelegramBot\Api\Http\SymfonyHttpClient;
$token = 'YOUR_BOT_API_TOKEN';
$bot = new Client($token, null, new SymfonyHttpClient(HttpClient::create()));
```
--------------------------------
### Send Media Group
Source: https://github.com/telegrambot/api/blob/master/README.md
Shows how to send a group of media items (photos or videos) in a single message using the Telegram Bot API. Requires creating an InputMedia array.
```php
$bot = new \TelegramBot\Api\BotApi('YOUR_BOT_API_TOKEN');
$media = new \TelegramBot\Api\Types\InputMedia\ArrayOfInputMedia();
$media->addItem(new TelegramBot\Api\Types\InputMedia\InputMediaPhoto('https://avatars3.githubusercontent.com/u/9335727'));
$media->addItem(new TelegramBot\Api\Types\InputMedia\InputMediaPhoto('https://avatars3.githubusercontent.com/u/9335727'));
// Same for video
// $media->addItem(new TelegramBot\Api\Types\InputMedia\InputMediaVideo('http://clips.vorwaerts-gmbh.de/VfE_html5.mp4'));
$bot->sendMediaGroup($chatId, $media);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.