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

Benjamin Brandall

Benjamin Brandall is a content marketer at Process Street, and runs Secret Cave on the side. Find him on Twitter here.

38 Comments

Thanks for this informative article. I have a question about writing codes, Can i code my bots using Python ? because i’m so interested in learning python for several different purposes.

Thanks for the lesson! A question: where do I get a list of all the methods? For example, how do I add an in-line keyboard and so on?

hi,
when i enter the “atm .” command it says “No command ‘atom’ found, did you mean:….”

how can i fix it?

i have installed atom.

i corrected the problem with atome with this alias atom=’/mnt/c//atom.exe’

now it opens in atom but there is no telegram-bot directory in there!

please help me!

Hi Paym,

This bit doesn’t have to be so tricky. It is intended as just a quick way to open up the files in a text editor. If you do that manually, you can just follow the rest along from that point.

Cheers

Hi, I followed your guide but have hit a snag with the following error when attempting to run the bot:

raceback (most recent call last):
8: from bot.rb:5:in `’
7: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:32:in `get_updates’
6: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:32:in `loop’
5: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:33:in `block in get_updates’
4: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:83:in `get_last_messages’
3: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:72:in `get_last_updates’
2: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:68:in `request’
1: from /usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:68:in `new’
/usr/local/lib/ruby/gems/2.5.0/gems/telegram_bot-0.0.8/lib/telegram_bot/api_response.rb:13:in `initialize’: uninitialized constant TelegramBot::ApiResponse::ResponseError (NameError)

is it possible to create a Telegram bot which you can ask questions and the bot queries a database or json file and returns a simple answer. e.g. “how many times has x appeared” and bot repsonds with “20 times” Is this is possible with minimal python code/knowledge

Hey bat,

Absolutely. The API makes it possible for you to listen for messages, and send responses back. Whatever happens in between that is up to you, so it’s definitely possible for the bot to parse a user’s message and then send back information from a database or JSON file conditionally.

I guess a good next step would be to check how to set up and query a database in Python. What about: https://pypi.org/project/tinydb/ ?

Cheers!

Hi Benjamin,

How can i make the bot to automatically greet someone entering a group where the bot is already running?

Hi. I’m new to coding and I’m totally confused with all these.

Please help me.

A video tutorial will be very much appreciated.

Thanks

Hi Benjamin, i am very new on this telegram api stuff. first of all i’m trying to make a project where i use Arduino Uno, and a gprs shield for internet (no wifi available), and i want to make a notification system to send a sensor value which was processed by arduino to my telegram account using a telegram bot. I’m still confused with the coding the bot, do i have to code the bot separately like ruby ? or i can just code it within the arduino IDE code? i already created a bot account and got the api token from botfather btw.
Sorry if my english is bad.

Hey Adnan,

That’s an interesting use case — and one you can be very flexible with. I’m not familiar with Arduino, its IDE, or what language it would expect to be programmed in, but if you can get the basic notification running (even if the outcome is just to write to a text file, or something), then you can hook up this Ruby bot separately, and have it listen for changes in that file every X seconds or something. That’s a rough and dirty way to do it. I recommend checking out: http://artoo.io/ and reading the tutorials, though, because it looks like you can write the bot all in one program with that framework. Basically what I’m saying is to not worry about the Telegram-delivering-the-message side of things first of all, and to try and get the notification going regardless of where it’ll end up. After that, it’ll be trivial to route the notification content through Telegram with this tutorial.

How could I create a bot that integrates with the goseedit wallet? Ideally I would host it for security purposes. The bot ideally would auto post a message that has the seedit sell codes in it. The user would reply as normal with the trade command and seedit would handle the transfer. The tough part for me to grasp is how to connect the wallet with to the bot. I am an SEO/PPC guy and have 0 coding experience but manage people that code. But this is a side project for me so I’m stuck. Ideally I would be able to recreate this bot over and over for clients as they needed and just deploy it for them except change the wallet address. It also would ideally have a way to trigger how often it posts to telegram. So like a timer that post it say every hour or so. So who/how can I accomplish this?

Hey….please I really dont know anything about this ruby or germ stuff…. But I created a bot with bot father, I had my token as usual but I can’t attend to a particular user…if I post anything to a particular user the post goes to all my users. I need to understand more about this bot creating well…
I will like you in person to help me with that…I will be very grateful.
Thanks

Hi Benjamin,
You talked about something that you built using RSS. Do you have a tutorial for that? I have a RSS feed ending with .xml but the ruby documentation you linked for RSS uses a .rss feed url. Anyways, if you can share a tutorial on reading RSS feed and posting, that would be really helpful. Thanks.

Hi Benjamin, thank you for the great content ,i got a good idea about my purpose,actually i started learning python and wana create a telegram bot.My goal is to create a telegram bot similar to online wikipedia ,like an encyclopedia.It would be like the user input a text,for example,a Chemical Material, and my bot returns all important information,with images if necessary. Would you be more kind and tell me is there any source which i can get closer to my dream?
appreciate your kind reply.cheers

I made a bot with support of botfather and manybot by use my Android phone. It work properly. But everyone access it’s command how can I make that bot respond only for group admins not for every members and how can I make sure that anyone not add this bot without my permission to any other group plz help

Hi! Followed every step of your tutorial, including the code you provided. But it returned the following error when I run it. Any idea what’s wrong?

/usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/api_response.rb:13:in `initialize’: uninitialized constant TelegramBot::ApiResponse::ResponseError (NameError)
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:68:in `new’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:68:in `request’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:72:in `get_last_updates’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:83:in `get_last_messages’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:33:in `block in get_updates’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:32:in `loop’
from /usr/local/var/rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/telegram_bot-0.0.8/lib/telegram_bot/bot.rb:32:in `get_updates’
from bot.rb:5:in `’

Hye, I’ve followed the tutorial up until the Bitbucket. I sit possible if I deploy the my git using Arduino UNO instead of Raspberry Pi.

A question:
When I type ->atom .<- system write this

atom : The term 'atom' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ atom .
+ ~~~~
+ CategoryInfo : ObjectNotFound: (atom:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Hi! it’s great article!
I did the whole thing, and it looks like it should work,
but…the bot is not response, what should I look for?

Thanks!
Yuval.

hi, I have a bot that wrote the code with R language. in this bot I want to get data from local and update run bot every 1 min or 30 seconds. do you have any idea for it?

Awesome tutorial, I have the bot running, but it’s only responding to the last of the when statements. If I comment one out, it will only respond to the last of the active when statements. Not sure why not matching any of the when statements?

Thanks for an awesome tutorial. I want to know when someone send URL through my telegram bot. my bot need to open that link and send HTML file automatically to the corresponding person. can you help me

Leave a Reply to David Cancel reply

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

Take control of your workflows today