How to Make a Telegram Bot: A Complete Dev Guide

Diagram showing the interaction between a user, Telegram, and a bot server

Telegram bots are powerful tools that can automate tasks, provide services, and enhance user experiences within the Telegram messaging platform. In this detailed guide, we’ll walk you through the process of creating your own Telegram bot using various programming languages, with a focus on Go (Golang), Python, PHP, JavaScript, and Ruby.

Understanding Telegram Bots

Telegram bots are special accounts that don’t require a phone number to set up. They can perform a wide range of functions, from sending notifications to integrating with other services.

Key Features of Telegram Bots:

Setting Up Your Development Environment

Before we start coding our bot, let’s set up our development environment.

1. Choose Your Programming Language

We’ll provide examples in Go, Python, PHP, JavaScript, and Ruby. Choose the language you’re most comfortable with.

2. Install Dependencies

Depending on your chosen language, install the necessary dependencies:

3. Choose an IDE

We recommend using Visual Studio Code with the appropriate language extensions for the best development experience.

Creating Your Telegram Bot

Now that we have our environment set up, let’s create our bot.

1. Get a Bot Token

  1. Open Telegram and search for the BotFather.
  2. Start a chat and send the command /newbot.
  3. Follow the prompts to choose a name and username for your bot.
  4. Save the API token provided by BotFather.
Screenshot of BotFather chat in Telegram, showing the process of creating a new bot

2. Write the Bot Code

Here are examples of a basic echo bot in different languages:

Go (using github.com/bakatz/telegram-bot-api)

package main

import (
	"log"
	"os"

	tgbotapi "github.com/bakatz/telegram-bot-api/v5"
)

func main() {
	bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil {
			continue
		}

		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
		msg.ReplyToMessageID = update.Message.MessageID

		bot.Send(msg)
	}
}

Python

import os
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

def echo(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)

def main():
    updater = Updater(token=os.environ['TELEGRAM_APITOKEN'], use_context=True)
    dispatcher = updater.dispatcher

    echo_handler = MessageHandler(Filters.text & ~Filters.command, echo)
    dispatcher.add_handler(echo_handler)

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

PHP

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Telegram\Bot\Api;

$telegram = new Api(getenv('TELEGRAM_APITOKEN'));

$response = $telegram->getUpdates();

foreach ($response as $update) {
    $message = $update->getMessage();
    $chatId = $message->getChat()->getId();
    $text = $message->getText();

    $telegram->sendMessage([
        'chat_id' => $chatId,
        'text' => $text
    ]);
}

JavaScript (Node.js)

const TelegramBot = require('node-telegram-bot-api');

const token = process.env.TELEGRAM_APITOKEN;
const bot = new TelegramBot(token, {polling: true});

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, msg.text);
});

Ruby

require 'telegram/bot'

token = ENV['TELEGRAM_APITOKEN']

Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    bot.api.send_message(chat_id: message.chat.id, text: message.text)
  end
end

3. Run Your Bot

Set your bot token as an environment variable and run the bot using the appropriate command for your chosen language.

Adding Features to Your Bot

Now that we have a basic bot running, let’s add some features, specifically focusing on handling commands. We’ll provide examples in all the languages we’ve covered.

Handling Commands

Here are examples of how to handle commands in different languages:

Go (using github.com/bakatz/telegram-bot-api)

package main

import (
	"log"
	"os"

	tgbotapi "github.com/bakatz/telegram-bot-api"
)

func main() {
	bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil {
			continue
		}

		if update.Message.IsCommand() {
			msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
			switch update.Message.Command() {
			case "start":
				msg.Text = "Welcome! I'm your new Telegram bot."
			case "help":
				msg.Text = "I can help you with various tasks. Use /commands to see what I can do."
			case "commands":
				msg.Text = "Available commands:\n/start - Start the bot\n/help - Get help\n/commands - Show available commands"
			default:
				msg.Text = "Unknown command. Use /help to see available commands."
			}
			bot.Send(msg)
		} else {
			// Echo the message (as before)
			msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
			msg.ReplyToMessageID = update.Message.MessageID
			bot.Send(msg)
		}
	}
}

Python

import os
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Welcome! I\'m your new Telegram bot.')

def help_command(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('I can help you with various tasks. Use /commands to see what I can do.')

def commands(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Available commands:\n/start - Start the bot\n/help - Get help\n/commands - Show available commands')

def echo(update: Update, context: CallbackContext) -> None:
    update.message.reply_text(update.message.text)

def main() -> None:
    updater = Updater(token=os.environ['TELEGRAM_APITOKEN'])

    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))
    dispatcher.add_handler(CommandHandler("commands", commands))

    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

PHP

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Telegram\Bot\Api;

$telegram = new Api(getenv('TELEGRAM_APITOKEN'));

$telegram->commandsHandler(true);

$telegram->addCommand(Telegram\Bot\Commands\HelpCommand::class);

$telegram->addCommand(
    Telegram\Bot\Commands\Command::class,
    'start',
    'Welcome! I\'m your new Telegram bot.'
);

$telegram->addCommand(
    Telegram\Bot\Commands\Command::class,
    'commands',
    "Available commands:\n/start - Start the bot\n/help - Get help\n/commands - Show available commands"
);

$response = $telegram->getUpdates();

foreach ($response as $update) {
    $message = $update->getMessage();
    $chatId = $message->getChat()->getId();
    $text = $message->getText();

    if ($message->isCommand()) {
        $telegram->triggerCommand($text, $update);
    } else {
        $telegram->sendMessage([
            'chat_id' => $chatId,
            'text' => $text
        ]);
    }
}

JavaScript (Node.js)

const TelegramBot = require('node-telegram-bot-api');

const token = process.env.TELEGRAM_APITOKEN;
const bot = new TelegramBot(token, {polling: true});

bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'Welcome! I\'m your new Telegram bot.');
});

bot.onText(/\/help/, (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'I can help you with various tasks. Use /commands to see what I can do.');
});

bot.onText(/\/commands/, (msg) => {
  const chatId = msg.chat.id;
  bot.sendMessage(chatId, 'Available commands:\n/start - Start the bot\n/help - Get help\n/commands - Show available commands');
});

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  if (!msg.text.startsWith('/')) {
    bot.sendMessage(chatId, msg.text);
  }
});

Ruby

require 'telegram/bot'

token = ENV['TELEGRAM_APITOKEN']

Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    case message.text
    when '/start'
      bot.api.send_message(chat_id: message.chat.id, text: "Welcome! I'm your new Telegram bot.")
    when '/help'
      bot.api.send_message(chat_id: message.chat.id, text: "I can help you with various tasks. Use /commands to see what I can do.")
    when '/commands'
      bot.api.send_message(chat_id: message.chat.id, text: "Available commands:\n/start - Start the bot\n/help - Get help\n/commands - Show available commands")
    else
      bot.api.send_message(chat_id: message.chat.id, text: message.text)
    end
  end
end

These examples demonstrate how to handle basic commands (/start, /help, /commands) and echo back non-command messages in each language. You can extend these examples to add more complex functionality to your bot.

Screenshot showing a Telegram chat with the bot, demonstrating command responses in different programming languages

Deploying Your Bot

To keep your bot running 24/7, you’ll need to deploy it to a server.

1. Choose a Hosting Provider

Popular hosting platforms offer a variety of services, pricing, and ease of use. Here’s a brief overview of the most popular ones:

2. Set Up Version Control

Using version control like Git is crucial for managing code, especially for deployment purposes:

3. Configure Environment Variables

Environment variables allow you to keep sensitive information (e.g., API keys, database URIs) outside of your codebase. Most hosting providers offer simple ways to manage environment variables.

4. Deploy Your Code

Each hosting provider has its own deployment process. Here’s a basic rundown for each:

Each platform has robust documentation to help guide you through deployment, including error troubleshooting and scaling options. It’s also a good idea to automate your deployment process with CI/CD tools like GitHub Actions, GitLab CI, or CircleCI.

Best Practices for Telegram Bot Development

  1. Security: Never hardcode your bot token in your source code.
  2. Error Handling: Implement robust error handling to prevent crashes.
  3. Rate Limiting: Respect Telegram’s rate limits to avoid being blocked.
  4. User Experience: Design clear and intuitive command structures.
  5. Privacy: Only collect and store necessary user data, and be transparent about it.

Enhancing Your Bot with AI-Powered Moderation

As your Telegram bot gains popularity, managing user interactions becomes increasingly important. This is where AI-powered moderation tools like Watchdog come into play. Watchdog is an AI chat moderator specifically designed for Telegram, offering advanced features to keep your users’ conversations safe and on-topic.

Benefits of Using Watchdog:

  1. Automated Content Moderation: Watchdog uses advanced AI algorithms to automatically detect and filter out inappropriate content, spam, and offensive language.

  2. Customizable Rules: Tailor the moderation rules to fit your bot’s specific needs and community guidelines.

  3. Real-time Monitoring: Get instant alerts and take immediate action on potential issues in your bot’s conversations.

  4. Multi-language Support: Effectively moderate conversations in multiple languages, expanding your bot’s global reach.

  5. Integration with Existing Bots: Easily integrate Watchdog alongside your current Telegram bot setup for seamless moderation.

By incorporating Watchdog into your Telegram bot, you can focus on developing innovative features while ensuring a safe and enjoyable experience for your users. This AI-powered moderation can significantly reduce the manual effort required to manage large-scale bot interactions, allowing your bot to scale efficiently.

Screenshot of Watchdog dashboard showing moderation statistics and settings

Conclusion

Creating a Telegram bot can be an exciting and rewarding project. With this guide, you’ve learned the basics of setting up, coding, and deploying your own bot using various programming languages. As you continue to develop your bot, remember to explore the Telegram Bot API documentation for more advanced features and possibilities.

To ensure the long-term success and scalability of your bot, consider implementing AI-powered moderation tools like Watchdog. These tools can help maintain a positive user experience, protect your community, and allow you to focus on creating innovative features for your bot.

Happy coding, and may your bot bring value and joy to its users!