Product
Solutions
Resources

How to Build Your First Telegram Bot: A Guide for Absolute Beginners

I’ve been obsessed with science fiction since I was a young teen, so coding has always appealed to me. I was fascinated by the idea that it is possible to write a program that behaves randomly — to me, that was already deep in the realms of sci-fi!

That obsession fueled my first forays into code, and resulted in a ton of fun bots. For example, this one that describes scary-sounding places by combining words at random, and this one that paints PNGs in block colors.

It’s nothing fancy. I’m hardly a master programmer, and you don’t have to be either. With a basic grasp of coding and APIs, you can create genuinely useful software for fun and profit. In this tutorial, we’ll look at creating a Telegram bot from scratch.

A Telegram bot could be used with the Intercom API to provide a way for support agents to reach their customers that use Telegram. It could also include automation that combines helpful resources with live chat, like in the example below from orat.io:

Telegram is a great home for customer-facing bots, with over 200,000,000 active monthly users and an annual growth rate of 50%. It’s a platform that your audience might already use, which reduces friction and encourages adoption. Plus, making bots for Telegram is super easy — the easiest bot creation experience I’ve had so far.

That’s why I decided to write this tutorial — it could be a good entry point for aspiring coders to looking something instantly rewarding (and potentially valuable) by leveraging a popular and functional platform.

The first bot I made for Telegram used RSS to find Hacker News submissions that match a search query:

Have a play around with the bot — it’s live here!

With the knowledge from this guide and a little further reading, you could make a support chatbot for your company, an RSS feed reader, a control panel for your smart home, or a bot that replies using only Shakespeare quotes. Little programming projects like this are great fun and infinitely extensible. The more you read around and dream up features, the further you can push your bot.

In this guide, you’ll learn:

  • How to write a Telegram bot from scratch
  • How to add new commands to the bot’s vocabulary
  • Basic terminal commands for creating files and navigating through folders
  • A little bit of the Ruby programming language
  • How to expand Ruby with gems
  • How to make your bot return random responses from a list
  • A few easy git commands to help you manage and transfer your code files
  • How to deploy the bot to a server and run it 24/7

Before starting, you’ll need:

  • A bash terminal. This comes packaged with macOS and Linux, but not most installs of Windows. If you’re following this tutorial on a Windows machine that doesn’t have Windows 10’s Anniversary Update, you can use an emulator or emulate Linux in a virtual machine.
  • Ruby. Refer to Ruby’s official documentation for OS-specific guides. I personally use Homebrew on macOS, but Windows users can install it with this tool.
  • Bundler. Bundler helps manage Ruby gems, which add extra functionality to your apps. You’ll need it to add an interface to the Telegram API to your bot. Simply run gem install bundler in your terminal to install it.
  • A text editor. You could theoretically use Notepad or TextEdit, but most would recommend a purpose-built editor like Atom, which highlights syntax and helps makes code mistakes more obvious.

With that in place, let’s get going.

Step 1: Download the Telegram app for desktop

Download Telegram for desktop

Telegram is predominantly a mobile app, but for development purposes you’re going to want to have it installed on the same machine you’re using for writing code. This way, you can quickly test it without unlocking your phone every time. And, you’ll be able to copy and paste your Telegram bot’s API key straight into your text editor.

Time to grab that API key!

Step 2: Chat with the BotFather to get your API key

Telegram bot creation is a novel process because much of it is centered around your own interactions with a Telegram bot. That bot is the BotFather. Inside your Telegram desktop app, you need to search his username and start a conversation with him.

Give the start command to BotFather by typing /start.

You’ll see a list of commands that help you create, edit, and manage your bots. Since it’s your first time, you’ll want /newbot.

Compared to the process for building a Twitter bot, a Mastodon bot, or any other kind of bot I’ve experimented with, Telegram makes the initial setup super easy. I guess that proves what a great tool Telegram bots can be!

After giving the /newbot command, you get to pick a name and username for your bot. The name is what your users will see the bot as in their contacts list, and the username is how they’ll find it. Think of the username like a Twitter handle; it has to be unique, and it’s best if it’s short and memorable.

With that done, you’ll be given your bot’s API key. The API key is how Telegram knows the code you write is associated with this particular bot. Every bot has its own API key, and you shouldn’t share it with anyone or they could hijack your bot and have it carry out their evil deeds.

That concludes our chat with BotFather for now — onto the code!

Step 3: Setting up the bot’s gems and directory

Open terminal, and do mkdir telegram-bot. This creates a new directory for your bot’s files. It’s best to keep them confined to one folder so it’s easy to manage. Navigate to the directory with cd telegram-bot and then do the following:

touch Gemfile
touch bot.rb
atom .

This creates two blank files, one for specifying the gems you’ll need and one where the bot’s code will live. The last command opens both of these files in Atom.

Click the Gemfile in Atom’s sidebar, and paste the following in:

source 'https://rubygems.org'
gem 'telegram_bot'

This tells Bundler to grab the Ruby interface to the Telegram API from rubygems.org.

To complete the gem setup, go back to your terminal and type bundle. Here’s what you should see:

That’s it for the gem setup, now we’re finally getting onto the code.

Coding your first Telegram bot

The actual code that is going to be running constantly on the server is inside bot.rb. It’s empty right now, but here we’re going to link in the Telegram gem we just bundled and create a bot.

It’s not much code to write. By the time you’re done, this is what you’ll have:

In Telegram, this is what the code above does:

Let’s look at what each part of the code does and write it as we go.

require 'telegram_bot'
token = 'TOKEN'
bot = TelegramBot.new(token: token)

(Replace the TOKEN with the API token you copied from BotFather)

Ruby makes it quite easy to guess what code will do. The three lines above add the Telegram bot functionality to your file and then create a new bot object from the TelegramBot class, authenticated with your token so the program knows where to send the data.

The next part is one big loop. It looks confusing at first, but it’s easy to pick apart.

bot.get_updates(fail_silently: true) do |message|
  puts "@#{message.from.username}: #{message.text}"
  command = message.get_command_for(bot)

  message.reply do |reply|
    case command
    when /start/i
      reply.text = "All I can do is say hello. Try the /greet command."
    when /greet/i
      reply.text = "Hello, #{message.from.first_name}.  "
    else
      reply.text = "I have no idea what #{command.inspect} means."
    end
    puts "sending #{reply.text.inspect} to @#{message.from.username}"
    reply.send_with(bot)
  end
end

The first line tells the bot to keep listening for commands. And, when it receives a command to pass it to the message variable. The puts line logs the command to your terminal so you can see what’s going on while the bot runs.

The bot’s response actions are stored in a case statement. The case statement’s input is fed through from the message variable after it’s been cleaned up by the gem’s get_command_for method. The bot’s reply text is set depending on the command stored and then finally sent with send_with before the loop restarts.

With this setup, you can now find your bot on Telegram and send the /start and /greet commands, and watch it in action.

To do this, save the changes in Atom and run ruby bot.rb in the terminal. As long as that terminal is open and running, your bot will send responses!

Customizing your shiny new bot

The bot you just made is fine, but it’s not very interesting. The basic bits are there, which means you can swap them out and extend them easily.

The parts to pay attention to when customizing are the when /command/i lines, and the text between the quotes on the reply.txt lines. These are the inputs your bot accepts, and the messages it sends back as responses.

So, if you wanted to say something different as a response to the /greet command, you’d change the value of reply.text underneath the greet command line (when /greet/i). Here’s a variation you could try:

when /greet/i
      greetings = ['bonjour', 'hola', 'hallo', 'sveiki', 'namaste', 'salaam', 'szia', 'halo', 'ciao']
      reply.text = "#{greetings.sample.capitalize}, #{message.from.first_name}!"

Here, I’ve created an array with a few different ways to say hello, and then added one to the message at random by using the sample method.

Turning your bot into something awesome

You can add as many commands, responses, and features to your bot as you like. Most of it is imagination, and a lot of Googling as you go. If you want to learn a lot of things that are applicable to this bot, start with Learn Ruby the Hard Way to get to grips with the basics of the language. With a bit of practice and a healthy reliance on StackOverflow, you’ll be able to:

  • Connect other APIs to pull data from sources like Airtable, Slack, RSS, or Twitter. This is where the really exciting functionality comes in — you can create a bot that acts as a conversational interface to a set of data or features, like a bot that returns search results from Twitter or posts to Slack.
  • Store user input in a database. You could create a Telegram bot that offers automated support to users or responds to inquiries, and stores their emails addresses in a database. The Sequel gem makes it easy to create, write, edit, and read databases.
  • Build a text adventure. Colossal Cave Adventure, one of the first terminal games, has been ported over to Telegram as a bot. Check it out here, and see the source here.

If you need inspiration, you can read other people’s bot source code, and check a list of Telegram bots — try to figure out how they work and recreate them as practice.

Running your bot 24/7

Right now, your bot is running in your terminal on your computer. That’s fine until you need to restart your computer, your wi-fi drops, or your computer goes to sleep. When that happens, it terminates the bot’s process and users won’t get a response from it.

The process of moving your bot from a development environment (your computer where you used Atom to write the bot) to a production environment (a server) is known as deployment. There are a few options for deploying your bot, but in both cases we’re going to start by uploading the files to Bitbucket. Bitbucket lets you use git, a version control system that helps you to safely make and track changes to your bot’s code. By uploading your bot’s files to Bitbucket, you can use Bitbucket as a way to grab the bot’s files when you’re logged into the host.

Sign up for Bitbucket and create a new repository.

With terminal open and in the same directory as your bot’s source code, type the following:

git init
git add .
git commit -m 'initial commit'

Now, follow the instructions shown by Bitbucket after making the new repository. Mine are:

After entering those two highlighted commands in my terminal and providing my Bitbucket password when requested, the files are uploaded. With your code living in the cloud, it’s time to pick a way to deploy.

Deploying with a Raspberry Pi

This little Raspberry Pi computer on my desk hosts a bunch of bots

A Raspberry Pi is a great investment if you’re planning on creating and deploying bots — you can get one from as little as $7 plus the price of an SD card. It uses very little power, so you can keep it on all the time and not worry about the cost. It might be tempting to buy a bundle that comes with a keyboard, mouse, and case but all you need is a USB charger, SD card, ethernet cable and the computer itself. You probably have most of these things in your office already.

Deploying with a cloud server

You don’t need to own the computer that your bot is running on, you can use the memory and power of someone else’s machine to run the bot remotely. Popular solutions for deploying in the cloud include Amazon Web Services (AWS), DigitalOcean, and Heroku.

Out of the three, the most entry-level are DigitalOcean and Heroku. Click here to get a DigitalOcean account that comes with $10 of credit — enough to run a server for two months while you test it out.

When you sign up for DigitalOcean and create a new droplet, you’ll learn how to connect to the server via SSH and launch the console.

From here, it’s the same process as you did on your local machine regardless of the server you’re using. In the end, it’s just a bash terminal. With some kind of server set up, let’s move onto the actual deployment.

The deployment process

On a fresh server — whether that’s a Raspberry Pi or a cloud server like Digital Ocean — you’ll need to install Ruby, Bundler, and Git:

sudo apt-get update
sudo apt-get upgrade
curl -L https://get.rvm.io | bash -s stable --ruby
sudo apt-get install bundler
sudo apt-get install git

Then make a new directory for your bot, navigate there, and download the files from Bitbucket with the following commands:

mkdir bots
cd bots
git clone https://[email protected]/benjbrandall/telegram-bot.git

Remember to replace the URL above (https://benjbran…) with the URL of your bot’s repository on Bitbucket. You’ll find the whole clone command through Bitbucket, so you won’t have to do that bit manually.

Next, type bundle to install the gem dependencies, and then ruby bot.rb to start the bot running permanently.

Note: if you’re accessing your server via SSH, you’ll need to run the bot with nohup ruby bot.rb & to make sure the bot doesn’t stop working when the SSH session is terminated. Now you’re free to close the terminal window, safe in the knowledge that your bot is quietly beep booping away in the background.

That concludes your first stab at a Telegram bot. Along the way, you learned about the terminal, Ruby, gems, the Telegram API, and how to deploy a bot to a server. Any questions or suggestions? You can message me on Twitter.

Get our posts & product updates earlier by simply subscribing

Leave a Reply

Your email address will not be published. Required fields are marked *

Take control of your workflows today