I’m working on a Telegram bot and need help with adding clickable links. For example I want to show two options:
- My website
- My blog
When a user taps these they should open specific web pages in their browser. How can I set this up using PHP?
Here’s a bit of my code so far:
$linkList = '';
foreach($sites as $site) {
$linkList .= '<a href=\"' . $site['url'] . '\">' . $site['name'] . '</a>';
}
$message = $linkList;
$apiEndpoint = 'https://api.telegram.org/bot' . $botToken . '/sendMessage';
$params = [
'chat_id' => $chatId,
'text' => $message,
'reply_markup' => json_encode($keyboard)
];
file_get_contents($apiEndpoint . '?' . http_build_query($params));
Any tips on how to make the links work properly in Telegram? Thanks!
I’ve implemented clickable URLs in my Telegram bot using a slightly different approach that works well. Instead of HTML parsing, I used Telegram’s built-in InlineKeyboardMarkup.
Here’s a snippet of my PHP code:
$keyboard = [
'inline_keyboard' => [
[
['text' => 'My Website', 'url' => 'https://mywebsite.com'],
['text' => 'My Blog', 'url' => 'https://myblog.com']
]
]
];
$params = [
'chat_id' => $chatId,
'text' => 'Check out these links:',
'reply_markup' => json_encode($keyboard)
];
file_get_contents($apiEndpoint . '?' . http_build_query($params));
This creates buttons that users can tap directly in the chat. It’s more intuitive and looks cleaner than text links. Plus, you don’t need to worry about HTML parsing or escaping. Give it a try and see if it suits your needs better!
Hey MiaDragon42, have u tried using Markdown instead? it’s way easier imo. just set ‘parse_mode’ to ‘MarkdownV2’ and use this format:
My Website
My Blog
works like a charm and looks neat too! lmk if u need more help
To create clickable URLs in your Telegram bot, you’ll need to use the parse_mode parameter and set it to HTML. This allows Telegram to interpret HTML tags in your message.
Here’s how you can modify your code:
$apiEndpoint = 'https://api.telegram.org/bot' . $botToken . '/sendMessage';
$params = [
'chat_id' => $chatId,
'text' => $message,
'parse_mode' => 'HTML',
'reply_markup' => json_encode($keyboard)
];
file_get_contents($apiEndpoint . '?' . http_build_query($params));
By adding ‘parse_mode’ => ‘HTML’, Telegram will recognize the tags in your message and render them as clickable links. Make sure your $message variable contains properly formatted HTML links.
Also, consider using inline keyboards for a better user experience. They allow you to create buttons directly in the chat interface, which can be more user-friendly than plain text links.