Quickly Create a Telegram Bot in Ruby

Share this article

Screenshot 2016-03-16 07.17.12

Telegram might be a new name to you, but it’s gaining popularity the in the last few years, in recent news Telegram reported 100,000,000 monthly active users. So what is it all about ?

Telegram is a cloud based messaging app which is well known for a variety of features and it’s secure messaging being one of key features. It supports a variety of platforms like Windows, OSX, GNU/Linux, Android, iOS and Windows Phone. It is also worth mentioning that the client side of Telegram is open source, so we cold be using any other messaging app like Pidgin to connect with Telegram.

Some of the features of Telegram:

  • Encryption
  • Super Groups (1000 members or more)
  • File/Photos transfer
  • Open source client side
  • Synchronizes your messages through all your devices
  • File size sharing limit 1.5 GB
  • Bots

We are going to talk about the last one in particular. Telegram offers two APIs: The developer API and the bot API

First, we need to sign up for an account. Either download one of the clients or go directly to the web version of Telegram. From there, you’ll be asked to give a phone number and Telegram will send a confirmation SMS.

Meet The BotFather

The BotFather

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them commands in private or group chats. We control our bots using HTTPS requests to the bot API.

What can we do with bots ?

  • Take notes in Telegram groups
  • Get weather updates
  • Play Games
  • Interact with other services such as social networks, IRC, etc.

We can do a lot of stuff with bots. The first step in creating our bot is to talk to the BotFather.

Type in the search form BotFather.

search_botfather

Click on the BotFather and a chat container will be opened so we can chat with him. Hit the start button which will display a list of commands that we can use to interact with the BotFather.

bot_commands

Let’s create our bot using the command /newbot. It is going to ask for a name for our bot, so we’ll call our bot sitepbot.

Now we have to register for a username, note: it must end in bot, If our bot is named TetrisBot the username must be tetrisbot. Let it be sitepointbot.

BotFather will congratulate us, and give a link to our bot telegram.me/sitepoint_bot.

We can add a description and also add a profile picture to our bot. The /help command will give us a list of commands we can interact with BotFather.

/newbot - create a new bot
/token - generate authorization token
/revoke - revoke bot access token
/setname - change a bot's name
/setdescription - change bot description
/setabouttext - change bot about info
/setuserpic - change bot profile photo
/setinline - change inline settings
/setinlinefeedback - change inline feedback settings
/setcommands - change bot commands list
/setjoingroups - can your bot be added to groups?
/setprivacy - what messages does your bot see in groups?
/deletebot - delete a bot
/cancel - cancel the current operation

Using one of the commands above, we can make various changes to our bot. But, right now, the most important command is /token, as it will give us an API token to access our bot through HTTPS. Go ahead and type that now:

/token

The return value will look something like this: 197372558:AAEtvechentOstoPmVyb1_aF2Dbe7k

After creating our bot and having it listen to us, it’s time for some Ruby power. There are several gems to interact with the bot API. We will be using telegram-bot-ruby.

Installation

We can install it directly from your terminal:

gem install telegram-bot-ruby

Or add it to our Gemfile:

gem 'telegram-bot-ruby'

If we are using it with the Gemfile we need to enter bundle install in our project directory. This will install the gem and the dependencies it needs.

Hello SitePoint Example

Create a file named sitepointbot.rb, we’ll build out the content of this file here.

First, we need to import our gem:

require 'telegram/bot'

Next, we need to add our token, which we generated earlier:

token = 'YOUR API TOKEN'

Using the bot.api object, we can use all the methods from Bot API:

Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    case message.text
    when '/sitepoint'
      bot.api.send_message(chat_id: message.chat.id, text: "Welcome to https://www.sitepoint.com")
    end
  end
end

send_message is one of the methods from the Bot API and it sends a message to the current chat_id. chat_id is the unique identifier for the target chat, or user name of the target channel. Of course, text is message to be sent to the chat. Whenever the bot sees /sitepoint in our chat message, it will respond with the “Welcome to https://www.sitepoint.com!”

Note: It is strongly suggested that we use a slash (/) before our commands, we don’t want our bots to interfere with our conversations.

Complete Code

require 'telegram/bot'

token = 'YOUR API TOKEN'
Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    case message.text
    when '/sitepoint'
      bot.api.send_message(chat_id: message.chat.id, text: "Welcome to https://www.sitepoint.com")
    end
  end
end

Now it is time to run our bot:

ruby sitepointbot.rb

We have to search for the bot. It will appear in the search result area.

sitepointbot

As you can see, there is a “Start” button. If we click the button a /start command will execute. This should always contain a welcome message from our bot, it is the best place to add general information about the bot, like what it does and what commands it understands.

hello_bot

This is the effect of the Start button or the /start command. If you wanted to start the bot inside a chat, you can also type

start@SitepBot

which is necessary if you have more than one bot in a chat.

Now let’s try /sitepoint.

sitepoint_command

The result is a welcome message with a link to SitePoint’s website.

One More Example

Let’s use the sendLocation method. This method will make a point on the map. We will be using the same object bot.api, but this time we want the send_location method:

bot.api.send_location(chat_id: message.chat.id, latitude: -37.807416, longitude: 144.985339)

Complete Code

require 'telegram/bot'

token = 'YOUR API KEY'
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: "I am the SitePoint bot, My commands are /sitepoint /map")
    when '/sitepoint'
      bot.api.send_message(chat_id: message.chat.id, text: "Welcome to https://www.sitepoint.com")
    when '/map'
      bot.api.send_location(chat_id: message.chat.id, latitude: -37.807416, longitude: 144.985339)
   end
  end
end

Note: We need to exit the bot and start again before seeing the changes.

sitepoint_map

Conclusion

Telegram offers a solid, secure messaging service. Like Slack, Telegram offers the ability to create bots that can interact with users. We have seen some basic features that bots can do, but we can make them smarter and more functional, take a look at the API of Telegram and be creative. If you make something great share it with us.

Frequently Asked Questions (FAQs) about Creating a Telegram Bot in Ruby

How can I handle different types of updates in my Telegram bot using Ruby?

Handling different types of updates in your Telegram bot using Ruby involves using the ‘message’ method. This method allows you to specify the type of update you want to handle. For instance, if you want to handle text messages, you can use the ‘text’ method. If you want to handle photo messages, you can use the ‘photo’ method. You can also use the ‘command’ method to handle commands. Remember to always include the appropriate methods in your bot’s script to ensure it can handle the updates you want.

How can I test my Telegram bot locally?

Testing your Telegram bot locally involves running your bot’s script on your local machine. You can do this by opening your terminal, navigating to the directory where your bot’s script is located, and then running the script using the ‘ruby’ command followed by the name of your bot’s script. Once your bot is running, you can interact with it on Telegram to see if it’s working as expected.

How can I deploy my Telegram bot to a server?

Deploying your Telegram bot to a server involves uploading your bot’s script to the server and then running it. You can upload your bot’s script to the server using a variety of methods, such as FTP or SSH. Once your bot’s script is on the server, you can run it using the ‘ruby’ command followed by the name of your bot’s script. Remember to ensure that your server has Ruby installed and that it’s configured to allow your bot to connect to the Telegram API.

How can I add custom commands to my Telegram bot?

Adding custom commands to your Telegram bot involves using the ‘command’ method in your bot’s script. This method allows you to specify the name of the command and the code that should be executed when the command is used. For instance, if you want to add a command that sends a greeting, you can do so by including the following code in your bot’s script: ‘command :greet do |message| bot.api.send_message(chat_id: message.chat.id, text: “Hello, #{message.from.first_name}!”) end’.

How can I handle errors in my Telegram bot?

Handling errors in your Telegram bot involves using the ‘rescue’ keyword in your bot’s script. This keyword allows you to specify the code that should be executed when an error occurs. For instance, if you want to send a message to yourself when an error occurs, you can do so by including the following code in your bot’s script: ‘begin # Your bot’s code here rescue => e bot.api.send_message(chat_id: YOUR_CHAT_ID, text: “An error occurred: #{e.message}”) end’. Remember to replace ‘YOUR_CHAT_ID’ with your own chat ID.

How can I make my Telegram bot respond to inline queries?

Making your Telegram bot respond to inline queries involves using the ‘inline_query’ method in your bot’s script. This method allows you to specify the code that should be executed when an inline query is received. For instance, if you want to send a list of articles when an inline query is received, you can do so by including the following code in your bot’s script: ‘inline_query do |query| results = Article.search(query.query).map do |article| { type: ‘article’, id: article.id, title: article.title, description: article.description, input_message_content: { message_text: article.url } } end bot.api.answer_inline_query(inline_query_id: query.id, results: results) end’.

How can I use webhooks with my Telegram bot?

Using webhooks with your Telegram bot involves setting up a server that can receive updates from the Telegram API and then configuring your bot to use this server. You can set up a server using a variety of technologies, such as Ruby on Rails or Sinatra. Once your server is set up, you can configure your bot to use it by calling the ‘setWebhook’ method on the ‘bot.api’ object and passing the URL of your server as the argument.

How can I make my Telegram bot send messages at specific times?

Making your Telegram bot send messages at specific times involves using a scheduling library, such as ‘rufus-scheduler’. This library allows you to specify the times at which your bot should send messages. For instance, if you want your bot to send a message every day at 9 AM, you can do so by including the following code in your bot’s script: ‘scheduler = Rufus::Scheduler.new scheduler.cron ‘0 9 * * *’ do bot.api.send_message(chat_id: YOUR_CHAT_ID, text: ‘Good morning!’) end’. Remember to replace ‘YOUR_CHAT_ID’ with your own chat ID.

How can I make my Telegram bot interact with other APIs?

Making your Telegram bot interact with other APIs involves using the ‘net/http’ library in Ruby. This library allows you to send HTTP requests to other APIs and receive responses. For instance, if you want your bot to get the current weather from the OpenWeatherMap API, you can do so by including the following code in your bot’s script: ‘uri = URI(“http://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY“) response = Net::HTTP.get(uri) weather = JSON.parse(response) bot.api.send_message(chat_id: YOUR_CHAT_ID, text: “The current weather in London is #{weather[‘main’][‘temp’]} degrees.”)’. Remember to replace ‘YOUR_API_KEY’ and ‘YOUR_CHAT_ID’ with your own API key and chat ID.

How can I make my Telegram bot handle multiple conversations at once?

Making your Telegram bot handle multiple conversations at once involves using threads. Threads allow your bot to handle multiple tasks at the same time. For instance, if you want your bot to handle each incoming message in a separate thread, you can do so by including the following code in your bot’s script: ‘message do |message| Thread.new do bot.api.send_message(chat_id: message.chat.id, text: “You said: #{message.text}”) end end’. This code creates a new thread for each incoming message, allowing your bot to handle multiple conversations at once.

Ardian HaxhaArdian Haxha
View Author

Ardian is a web developer with a focus on building data-driven back-end APIs. He is very engaged with open source communities such as the Fedora Project and Mozilla.

botschatbotsEmerging TechGlennGtelegram bots
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week