Tag Archives: telegram bot

Telegram bot to send message

This is a simple code for a telegram bot to send message to a person or to a group

function send_telegram($telegram_id, $message_text) {

        $secret_token='123456789:adfjalJNhahasdfHUsQ';

        // to get group telegram id (can be in negative value)
        // https://api.telegram.org/bot1228803793:AAEElKIr5OhBlnMpsvPVNLa_Gb4cjSriUsQ/getUpdates

        $url = "https://api.telegram.org/bot" . $secret_token . "/sendMessage?parse_mode=markdown&chat_id=" . $telegram_id;
        $url = $url . "&text=" . urlencode($message_text);
        $ch = curl_init();
        $optArray = array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true
        );
        curl_setopt_array($ch, $optArray);
        $result = curl_exec($ch);
        curl_close($ch);
    }

Some important notes

  1. You need to create a bot using @botFather (search this bot in telegram and just follow the steps to create your own bot)
  2. Once your bot successfully created, you need to capture the secret token given
  3. To get the telegram id for user – can ask the user to send a message to @userinfobot – the telegram id is in integer
  4. To get telegram id for a group, you need to add the bot to the group and go to this link to get the group id, group id start with – (dash/negative sign)
    https://api.telegram.org/bot<your bot secret token>/getUpdates
  5. (easier way) or add this bot @RawDataBot (Telegram Data Raw) to the group. Once added a message will be displayed. Get the chat id with negative number from the message
  6. In order for bot able to send message to the group, you must add bot to the group
  7. In order for bot able to send message to a person, the person must send a message to the bot first

source