How can you send a Telegram channel message in PHP? Let's send a post with and without an image through a bot using PHP.
Create a bot
In Telegram, this takes only a few minutes. The official verified bot for creating and configuring bots is @BotFather. Open it in Telegram and send this command:
/newbot Choose a name and username for your bot. Everything happens directly in the Telegram chat.
Once the bot has been created and configured, BotFather sends you its token. You need this token to make API requests. Telegram documents all available API methods here: Telegram Bot API. That completes the bot setup.
PHP example for sending a Telegram message
For our purposes, you do not need to read all the documentation. Two methods are enough: sendPhoto and sendMessage.
To send a Telegram channel message with a photo:
static public function photoMessage(string $title, string $desc, string $img, string $url): array
{
$bot_token = 'xxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$chat_id = '@chat_id';
$text = "*{$title}* **{$desc}** [Подробнее]({$url})";
$request = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage';
// параметры, которые отправятся api телеграмм
$params = array(
'chat_id' => $chat_id, // id получателя сообщения
'caption' => $text, // текст сообщения
'parse_mode' => 'markdown', // режим отображения сообщения, не обязательный параметр
'disable_web_page_preview' => true,
'photo' => $img,
);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $request);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $params);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$result = curl_exec($c);
if ($result === false) {
$result = curl_error($c);
}
curl_close($c);
return $result;
}To send a Telegram channel message without a photo:
static public function sendMessage(string $title, string $desc, string $url): array
{
$bot_token = 'xxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$chat_id = '@chat_id';
$text = "*{$title}* **{$desc}** [Подробнее]({$url})";
$request = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage';
// параметры, которые отправятся api телеграмм
$params = array(
'chat_id' => $chat_id, // id получателя сообщения
'text' => $text, // текст сообщения
'parse_mode' => 'markdown', // режим отображения сообщения, не обязательный параметр
'disable_web_page_preview' => true,
);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $request);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $params);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$result = curl_exec($c);
if ($result === false) {
$result = curl_error($c);
}
curl_close($c);
return $result;
}