I’m working on a Telegram bot in PHP and I need to include additional custom parameters when sending messages through webhook. Can I add extra variables along with the standard sendMessage method?
For instance, I want to pass a custom action parameter like this:
function handleIncomingMessage($data) {
// handle the received message
$msg_id = $data['message_id'];
$action = $data['task'];
$chat_id = $data['chat']['id'];
$first_name = isset($data['chat']['first_name']) ? $data['chat']['first_name'] : "";
$last_name = isset($data['chat']['last_name']) ? $data['chat']['last_name'] : "";
if (isset($data['text'])) {
$text = $data['text'];
if (strpos($text, "/begin") === 0) {
sendApiRequest("sendMessage", array(
'chat_id' => $chat_id,
"text" => 'Hello '.$first_name.' '.$last_name.' welcome to my bot, what would you like to do ['.$action.']?',
'task' => "do something",
'reply_markup' => array(
'keyboard' => array(array('/check', '/help')),
'one_time_keyboard' => true,
'resize_keyboard' => true
)
));
}
}
}
Is this approach correct for passing custom parameters through the webhook?
You can’t send custom parameters through the API call - Telegram just discards unknown fields. I’ve encountered this issue before. The best solution is to manage state on your server. I typically create a simple database table or use Redis to store user context with chat_id as the key. When a user triggers an action, I save their current state (such as your ‘task’ parameter) to the database and retrieve it when processing their next message. This method is much more reliable than trying to have Telegram store your custom data, and it gives you complete control over the user’s session throughout the conversation.
No, that approach won’t work. Telegram’s Bot API only accepts predefined parameters for each method, so custom ones like ‘task’ will be ignored. When you call sendMessage, only the official parameters (chat_id, text, reply_markup, etc.) are processed. If you need to keep track of state or pass custom data between webhook calls, consider storing it in a database or session. You can save the task parameter in a table associated with the user’s chat_id and retrieve it during subsequent messages. Alternatively, for inline keyboards, you can encode custom data in the callback_data, but be aware of the size limit, as Telegram’s responses will only include the standard structure without your custom fields.
nope, Telegram API doesn’t support custom params like that. I just use $_SESSION or a txt file to track user states. When someone hits /begin, I save their chat_id + current action to the file, then check it when they send the next message. works great for small bots - no database needed.