To receive incoming messages in a Telegram bot using the Telegram API with PHP in WordPress, follow these steps:
1. Create a Telegram Bot
- Find the
@BotFather
bot in Telegram. - Use the
/newbot
command to create a new bot. - Follow the instructions and get the access token for your bot.
2. Set Up Webhook for the Bot
Telegram sends messages to your bot through a Webhook. Set up a URL where updates will be sent:
- Write a PHP script to handle the Webhook:
<?php
// Get the incoming data
$content = file_get_contents("php://input");
$update = json_decode($content, true);
// Check if the data contains a message
if (isset($update['message'])) {
$chat_id = $update['message']['chat']['id'];
$text = $update['message']['text'];
// Example of responding to the user
$response = [
'chat_id' => $chat_id,
'text' => "You sent: " . $text
];
// Send the response via the Telegram API
file_get_contents("https://api.telegram.org/bot<TOKEN>/sendMessage?" . http_build_query($response));
}
?>
- Place this script on your WordPress server (e.g., in the
wp-content/uploads
folder). - Set up the Webhook via a request to the Telegram API: Replace
<YOUR_BOT_TOKEN>
and<YOUR_DOMAIN>
with the appropriate values.
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://<YOUR_DOMAIN>/path/to/your/script.php
3. Add Processing in WordPress
If you want to integrate message processing directly into WordPress, you can use hooks and create a REST API handler.
Example plugin for handling Telegram Webhook:
- Create a plugin file, for example,
telegram-webhook.php
:
<?php
/*
Plugin Name: Telegram Webhook Handler
Description: Handle incoming Telegram messages via Webhook
Version: 1.0
Author: Your Name
*/
add_action('rest_api_init', function () {
register_rest_route('telegram/v1', '/webhook', [
'methods' => 'POST',
'callback' => 'telegram_webhook_handler',
]);
});
function telegram_webhook_handler($request) {
$update = $request->get_json_params();
if (isset($update['message'])) {
$chat_id = $update['message']['chat']['id'];
$text = $update['message']['text'];
// Send a message back to the user
$response = [
'chat_id' => $chat_id,
'text' => "You sent: " . $text
];
$token = 'YOUR_TOKEN';
wp_remote_get("https://api.telegram.org/bot{$token}/sendMessage?" . http_build_query($response));
}
return rest_ensure_response(['status' => 'ok']);
}
- Activate the plugin in WordPress.
- Set the Webhook to the new URL:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://<YOUR_DOMAIN>/wp-json/telegram/v1/webhook
4. Testing
- Send a message to your bot on Telegram.
- Check if the bot responds correctly.
- If errors occur, check your server logs or use debugging tools (such as Postman).