PHP+Telegram: 5 easy ways to send a message

PHP+Telegram: 5 easy ways to send a message

# php# telegram# symfony# laravel

Tuesday, August 22, 2023


In the world of online communication, Telegram stands out as a popular messaging platform. It might be useful to know how to easily send a message to Telegram from the code. This article shows 5 easy ways to do this using PHP:


Preconditions

  • PHP installed and curl extension enabled
  • Public Telegram channel created
  • Telegram bot created with BotFather
  • Bot added to channel administrators

Telegram API

Telegram provides a variety of API endpoints and methods, which can be found in the documentation.

Today we are going to focus on the sendMessage endpoint. It sends some text {TEXT} to the particular channel {CHANNEL_ID} by the bot {BOT_API_TOKEN}

https://api.telegram.org/bot{BOT_API_TOKEN}/sendMessage?chat_id={CHANNEL_ID}&text={TEXT}

There are many ways to call this endpoint and send a message to the channel within a PHP project. We will cover 5 of them.


HTTP request with cURL

Functional style

<?php

$botApiToken = 'your bot api token';
$channelId ='your channel id';
$text = 'Hello, I am from PHP!';

$query = http_build_query([
    'chat_id' => $channelId,
    'text' => $text,
]);
$url = "https://api.telegram.org/bot{$botApiToken}/sendMessage?{$query}";

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'GET',
));
curl_exec($curl);
curl_close($curl);

OOP style

Installation

composer require curl/curl

Usage

<?php

require 'vendor/autoload.php';

$botApiToken = 'your bot api token';
$channelId ='your channel id';
$text = 'Hello, I am from PHP!';

$query = http_build_query([
    'chat_id' => $channelId,
    'text' => $text,
]);
$url = "https://api.telegram.org/bot{$botApiToken}/sendMessage?{$query}";

$curl = new \Curl\Curl();
$curl->get($url);

One line magic with file_get_contents

<?php

$botApiToken = 'your bot api token';
$channelId = 'your channel id';
$text = 'Hello, I am from PHP file_get_contents!';
$query = http_build_query([
    'chat_id' => $channelId,
    'text' => $text,
]);
$url = "https://api.telegram.org/bot{$botApiToken}/sendMessage?{$query}";
file_get_contents($url);

Symfony HTTP client

Symfony is one of the most popular PHP frameworks. It provides a lot of different components out of the box, and one of them is HTTP Client. It allows you to make HTTP requests easily.

Installation

composer require symfony/http-client

Standalone

<?php

require 'vendor/autoload.php';

use Symfony\Component\HttpClient\HttpClient;

$botApiToken = 'your bot api token';
$channelId ='your channel id';
$text = 'Hello, I am from Symfony HTTP Client!';

$client = HttpClient::create([
    'base_uri' => 'https://api.telegram.org',
]);

$client->request('GET', "/bot{$botApiToken}/sendMessage", [
    'query' => [
        'chat_id' => $channelId,
        'text' => $text,
    ],
]);

Inside Symfony app

Prepare a scoped client in config/packages/framework.yaml:

framework:
    http_client:
        scoped_clients:
            telegram.client:
                base_uri: 'https://api.telegram.org'

And use it inside your service:

<?php

namespace App;

use Symfony\Contracts\HttpClient\HttpClientInterface;

class YourService
{
    public function __construct(
        private readonly HttpClientInterface $telegramClient,
    )
    {
    }

    public function sendMessage(string $text): void
    {
        $botApiToken = 'your bot api token';
        $channelId ='your channel id';

        $this->telegramClient->request('GET', "/bot{$botApiToken}/sendMessage", [
            'query' => [
                'chat_id' => $channelId,
                'text' => $text,
            ],
        ]);
    }
}

Symfony Telegram Notifier

Another Symfony component that can send a message to the Telegram channel is Telegram Notifier.

Installation

composer require symfony/telegram-notifier

Standalone

<?php

require 'vendor/autoload.php';

use Symfony\Component\Notifier\Bridge\Telegram\TelegramTransport;
use Symfony\Component\Notifier\Chatter;
use Symfony\Component\Notifier\Message\ChatMessage;

$botApiToken = 'your bot api token';
$channelId ='your channel id';

$text = 'Hello, I am from Symfony Telegram Notifier!';

$telegramTransport = new TelegramTransport($botApiToken, $channelId);
$chatter = new Chatter($telegramTransport);
$chatMessage = new ChatMessage($text);
$chatter->send($chatMessage);

Inside Symfony app

Configure a notifier chatter transport in config/packages/framework.yaml:

parameters:
  env(TELEGRAM_DSN): 'telegram://BOT_API_TOKEN@default?channel=CHANNEL_ID'

framework:
    notifier:
        chatter_transports:
            telegram: '%env(TELEGRAM_DSN)%'

And use it inside your service:

<?php

namespace App;

use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\Message\ChatMessage;

class YourService
{
    public function __construct(
        private readonly ChatterInterface $telegramChatter
    )
    {
    }

    public function sendMessage(string $text): void
    {
        $this->telegramChatter->send(new ChatMessage($text));
    }
}

Telegram Bot SDK

With the Telegram Bot SDK you can easily develop Telegram Bots in PHP. It supports the Laravel framework and comes with add-ons to enhance your bot development experience.

Installation

composer require irazasyed/telegram-bot-sdk

Standalone

<?php

require 'vendor/autoload.php';

use Telegram\Bot\Api;

$botApiToken = 'your bot api token';
$channelId ='your channel id';

$telegram = new Api($botApiToken);
$telegram->sendMessage([
    'chat_id' => $channelId,
    'text' => $text,
]);

Inside Laravel app

php artisan vendor:publish --tag="telegram-config"
<?php

namespace App;

use Telegram\Bot\Api;

class YourService
{
    public function __construct(private readonly Api $telegram)
    {
    }

    public function sendMessage(string $channelId, string $text): void
    {
        $this->telegram->sendMessage([
            'chat_id' => $channelId,
            'text' => $text,
        ]);
    }
}

Summary

There are many ways to achieve the same goal. With so many options available, there's no definitive "right" way to send a Telegram message using PHP. The choice you make depends on your needs and the technologies you're working with. This article shows five easy ways to send messages to Telegram using PHP, it's up to you which one to use.