Первая версия класса для отправки сообщений через Telegram Bot API без сторонних библиотек — только cURL. Подходит для уведомлений с сайта: новая заявка, ошибка, результат крон-задачи.

Класс принимает токен бота и список получателей, вычищает из текста HTML-теги, которых нет в списке поддерживаемых Telegram, и отправляет сообщение каждому получателю. Если отправка не удалась, выводит ответ API.

§Код

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
<?php
class TelegramMessage
{
	private $recipients;

	private $token;

	private $parseMode;

	public function __construct($parse_mode = 'HTML')
	{
		$this->parseMode = $parse_mode;
		$this->token = '';
		$this->recipients = array();
	}

	public function setToken($token)
	{
		$this->token = $token;
	}

	public function setRecipients($list = array())
	{
		$this->recipients = $list;
	}

	public function send($message)
	{
		if (!count($this->recipients)) {
			exit ('Список получателей пуст');
		}

		if (!strlen($this->token)) {
			exit ('Токен не задан');
		}

		preg_match_all('/<.+?[\s]*\/?[\s]*>/si', $message, $tags);

		$tags = array_unique($tags[0]);

		$allowed_tags = array(
			'<a\s.*?>',
			'<\/a>',
			'<b>',
			'<b\s.*?>',
			'<\/b>',
			'<i>',
			'<i\s.*?>',
			'<\/i>',
			'<code>',
			'<code\s.*?>',
			'<\/code>',
			'<pre>',
			'<pre\s.*?>',
			'<\/pre>',
		);

		foreach ($tags as $key => $tag) {
			$find_tag = false;

			foreach ($allowed_tags as $allowed_tag) {
				if (preg_match('/' . $allowed_tag . '/', $tag)) {
					$find_tag = true;
					break;
				}
			}

			if ($find_tag)
				continue;

			$message = preg_replace('/' . addcslashes($tag, '/[]().+?') . '/', '', $message);
		}

		$message = urlencode($message);

		$token = $this->token;
		$parse_mode = $this->parseMode;

		foreach ($this->recipients as $id) {
			$url = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$id}&parse_mode={$parse_mode}&text={$message}";

			$ch = curl_init();

			curl_setopt_array($ch, array(
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true
			));

			$response = curl_exec($ch);

			$response = json_decode($response);

			if (!$response->{'ok'}) {
				echo(
					json_encode(
						array(
							'target_id' => $id,
							'response' => $response,
							'message' => urldecode($message),
						)
					)
				);
			}

			curl_close($ch);
		}
	}
}

§Пример использования

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

require_once(__DIR__ . '/TelegramMessage.php');

$telegram = new TelegramMessage();

$telegram->setToken('YOUR_TELEGRAM_TOKEN');

$recipients = [
	// chat_id
	'1234567890',

	// channel
	'@webclownchannel'
];

$telegram->setRecipients($recipients);

$message = 'Провер<i>_очка</i>! <code>Lorem ipsum dolor sit amet.</code>';

$telegram->send($message);

Есть обновлённая версия класса для PHP 8 с inline-кнопками.