Skip to content

How to send message to channel user without user interaction

justanotheranonymoususer edited this page Mar 30, 2024 · 3 revisions

Based on discussion in this thread: https://github.com/akalongman/php-telegram-bot/issues/71#issuecomment-183177739

To send message to user/channel without initiating message from user (usually, for broadcasting message), you can use the following snippet:

<?php
/**
 * Usage on CLI: $ php broadcast.php [telegram-chat-id] [message]
 */

require __DIR__ . '/vendor/autoload.php';

use Longman\TelegramBot\Request;
use Longman\TelegramBot\Telegram;

$API_KEY  = '--botfather-api-key--';
$BOT_NAME = '--botfather-bot-name--';

$telegram = new Telegram($API_KEY, $BOT_NAME);

// Get the chat id and message text from the CLI parameters.
$chat_id = isset($argv[1]) ? $argv[1] : '';
$message = isset($argv[2]) ? $argv[2] : '';

if ($chat_id !== '' && $message !== '') {
    $data = [
        'chat_id' => $chat_id,
        'text'    => $message,
    ];

    $result = Request::sendMessage($data);

    if ($result->isOk()) {
        echo 'Message sent successfully to: ' . $chat_id;
    } else {
        echo 'Sorry message not sent to: ' . $chat_id;
    }
}