Creating a Telegram bot to interact with

Steven Grant

I'm writing this for my future self because I always seem to forget the steps needed.

The steps are as follows:

  1. Start chat with BotFather on desktop Telegram

  2. create a new bot using /newbot

  3. give the bot a name eg. Steven's Demo Bot

  4. give the bot a username eg. StevensDemoBot

  5. take note of the Telegram token

  6. start a conversation with Steven's Demo Bot

  7. hit the Telegram API getUpdates endpoint with your token eg https://api.telegram.org/bot000000000:AAFjSq4AMkx1JkQS4woTlyKlXeftv6mgu-I/getUpdates

  8. if there's no update, add a message to the conversation again

  9. visit the API again and take a note of the chat id

  10. send an http request to https://api.telegram.org/bot000000000:AAFjSq4AMkx1JkQS4woTlyKlXeftv6mgu-I/sendMessage?chat_id=000000000&text=Feed%20Me to send a message

Mainly I'm doing this in the context of a PHP Laravel application but it could totally be language agnostic.

Here's the simple Telegram service I use

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TelegramService
{
    public function __construct(
        private string $botToken = '',
        private string $chatId = ''
    ) {
        $this->botToken = $this->botToken ?: config('services.telegram.token');
        $this->chatId = $this->chatId ?: config('services.telegram.chat_id');
    }

    public function sendMessage($message): bool
    {
        $response = Http::post("https://api.telegram.org/bot{$this->botToken}/sendMessage", [
            'chat_id' => $this->chatId,
            'text' => $message,
        ]);

        if ($response->successful()) {
            Log::info("Telegram message sent successfully");
            return true;
        } else {
            Log::error("Failed to send Telegram message: " . $response->body());
            return false;
        }
    }
}