Telegram chat bot without libraries in PHP

Telegram chat bot without libraries in PHP

First, let’s write the main code that will determine the sending and receiving of requests from the telegram servers:

<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
if (empty($data['message']['chat']['id'])) {
        exit();
}
define('TOKEN', 'ТОКЕН_БОТА12123124134124234');
// Функция вызова методов API.
function sendTelegram($method, $response)
{
        $ch = curl_init('https://api.telegram.org/bot' . TOKEN . '/' . $method);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
}

And so, the whole structure of the bot will be in this function:

if (!empty($data['message']['text'])) {
        $text = $data['message']['text'];
}

And then, it’s a matter of our imagination: We accept what we wrote to the bot -> we process it -> we answer.

If we were sent a text:

if (mb_stripos($text, 'hello') !== false) {sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],'text' => 'Hello!!!')); exit();}

Accordingly, if you write “Hello” to the bot, he will answer “Hello!!!”.

If a file was sent to us:

if (!empty($data['message']['document'])) {
        $res = sendTelegram(
                'getFile',
                array(
                        'file_id' => $data['message']['document']['file_id']
                )
        );
        $res = json_decode($res, true);
        if ($res['ok']) {
                $src = 'https://api.telegram.org/file/bot' . TOKEN . '/' . $res['result']['file_path'];
                $dest = __DIR__ . '/' . time() . '-' . $data['message']['document']['file_name'];
                if (copy($src, $dest)) {
                        sendTelegram(
                                'sendMessage',
                                array(
                                        'chat_id' => $data['message']['chat']['id'],
                                        'text' => 'Файл сохранён'
                                )
                        );
                }
        }

Accordingly, if a file is sent to the bot, it will reply that the file has been saved and save it to the root.

If a photo was sent to us:

if (!empty($data['message']['photo'])) {
        $photo = array_pop($data['message']['photo']);
        $res = sendTelegram(
                'getFile',
                array(
                        'file_id' => $photo['file_id']
                )
        );
        $res = json_decode($res, true);
        if ($res['ok']) {
                $src = 'https://api.telegram.org/file/bot' . TOKEN . '/' . $res['result']['file_path'];
                $dest = __DIR__ . '/upload_photo/' . time() . '-' . basename($src);
                if (copy($src, $dest)) {
                        sendTelegram(
                                'sendMessage',
                                array(
                                        'chat_id' => $data['message']['chat']['id'],
                                        'text' => 'Thanks))'
                                )
                        );

                }
        }
        exit();
}

Accordingly, if a photo was sent to the bot, it will answer “Thanks))” and save the photo to the upload_photo root folder.

Okay, simple answers did not suit me, and I came up with this way to revive the bot:

if (mb_stripos($text, 'how are you') !== false) {
  $rand = array(0, 1);
  $rand_result = array_rand($rand, 1);
  if (1 == $rand_result) {
     sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],
     'text' => 'Hmm'));
     sleep(3);
  }
sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],
'text' => "I'm fine!)")); exit();}

This code creates the effect of a thinking bot. In this example, you write to the bot “How are you?”. The bot, with a probability of 50%, will send you the phrase “Hmm”, and then (after 3 seconds, because sleep(3) ) will already answer “I’m fine!)”. Or will answer right away, because it’s random!

Also, so that the bot does not respond in the same way, you can create a file with prepared responses and add a selective response function to the send, with which the bot will respond.

For example, the bot responds differently to “Yes\No” messages.

Accordingly, the example code:

if (mb_stripos($text, 'yes') !== false ||
mb_stripos($text, 'mg') !== false ||
mb_stripos($text, 'ok') !== false
) {
$txt = file('frazy/yes.txt');
$str = $txt[ array_rand($txt) ];
unset($txt);
$txts = file('frazy/smyles/smile.txt');
$smi = $txts[ array_rand($txts) ];
unset($txts);
sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],
'text' => "$str $smi")); exit();}

if (mb_stripos($text, 'no') !== false) {
$txt = file('frazy/no.txt');
$str = $txt[ array_rand($txt) ];
unset($txt);
$txts = file('frazy/smyles/smile.txt');
$smi = $txts[ array_rand($txts) ];
unset($txts);
sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],
'text' => "$str $smi")); exit();}

Right here,
frazy/no.txt – a file with phrases for replying to the “No” message.
frazy/yes.txt – file with phrases for replying to “Yes” message.
frazy/smyles/smile.txt – file with smiles.

I think you noticed that there are several “consensual” words in the function:

mb_stripos($text, 'yes') !== false ||
mb_stripos($text, 'mg') !== false ||
mb_stripos($text, 'ok') !== false

This is not to write a separate function for each word – just through || indicate the ones you need, it’s something like this: if you sent the word “yes” or “mg” or “ok”, then we send the phrase from the text.

Similarly, you can force the bot to send a file or picture.

File upload example:

if (mb_stripos($text, 'file') !== false) {
                sendTelegram(
                        'sendDocument',
                        array(
                                'chat_id' => $data['message']['chat']['id'],
                                'document' => curl_file_create(__DIR__ . '/photos/my.jpg')
                        )
                );
                exit();
        }

If you write “file” to the bot, it will send the /photos/my.jpg file.

An example of sending a picture:

if (mb_stripos($text, "send photo") !== false ||
mb_stripos($text, "send pic") !== false) {
                sendTelegram(
                        'sendPhoto',
                        array(
                                'chat_id' => $id_creator,
                                'photo' => curl_file_create(__DIR__ . '/photos/my.jpg')
                        )
                );
sleep(1);
sendTelegram('sendMessage',array('chat_id' => $id_creator,
'text' => "Here, take it)))"));
                exit();
        }

My bot’s name is Lina. And for example, I indicated that for the phrases “send a photo”, “throw a photo”, “send a photo” – he will send me a photo and a message “Here, take it))”.

In general, that’s all.

Oh, if you want to make the bot only talk to you, you need to add such a small check on the account ID.

$id_creator = 'Telegram account ID';
if ($data['message']['chat']['id'] != $id_creator) {
sendTelegram('sendMessage',array('chat_id' => $data['message']['chat']['id'],
'text' => "You do not have permission to use this bot."));
      exit();
}

Add this code after the main code and now, if someone else writes to the bot, the bot will answer him “You do not have permission to use this bot.”

If the bot is in a group divided into topics, add the code to the message sending block:

'message_thread_id' => $data['message']['message_thread_id']

Full example:

sendTelegram('sendMessage',array(
           'chat_id' => $data['message']['chat']['id'],
            'message_thread_id' => $data['message']['message_thread_id'],
            'text' => "Hello!)"));