How to integrate a Telegram bot to a Rails app

In this tutorial, we are going to learn how to create a Telegram Bot and use it to send messages to a Telegram channel from a Rails application in a few simple lines of code.
Person coding on a laptop
Summary

Stay on top of the latest tech trends & AI news with Le Wagon’s newsletter

Written by Francesca Santoriello, Full Stack Web Developer, ex freelancer & Le Wagon teacher now writing a daily dose of code @Miyagami

 


 

Welcome! In this tutorial, we are going to learn how to create a Telegram Bot and use it to send messages to a Telegram channel from a Rails application.

Using a bot to work in the background of your web application can serve many purposes, such as notifying users about specific events, handling customer support queries, or broadcasting important updates to a group or channel.

Telegram is just one of the many ways to send a push message from a web application and it’s extremely popular due to its security, robust privacy, and most of all it offers the possibility to use their Telegram Bots for free and without any limitation.

Thanks to how quick it is to setup a Rails app with the Telegram API, you’ll need just a few simple lines of code to have your personal bot up and running! Let’s start.

 


 

1. Install boilerplate

To kickstart the implementation, we’ll start with a pre-built Rails boilerplate: this contains a minimal Rails application with a pages controller and an homepage styled with TailwindCSS. The design is simple, as the boilerplate’s going to be our starting point and it can be customised later.

 

1.1 Clone the repository

To clone the boilerplate code from git, run the following command in your terminal:

git clone <https://github.com/francescamilk/telegram.git>  

 

1.2 Install gems

Next up, let’s navigate to the project folder and remove the git-connection to the original repository, to make it independent.

After, let’s install the dependencies of the project with bundle install:

cd telegram && git remote remove origin   bundle install

 

1.3 Run the Rails server

We are ready to see the app! Launch you rails server:

bin/rails server  

Open your browser and visit http://localhost:3000 to see the app running. You should see this simple homepage with a form ready for user input: for now the form is a dummy, but we are going to use it later to send dynamic messages via a personal Telegram Bot.

 

2. Create Telegram bot

Now that a simple Rails app is up and running, we can set up the Telegram bot that will handle sending messages. This process is very simple and can be done via the BotFather Telegram Bot.

Here is a tutorial from the Telegram docs, which we are going to simplify here but can be useful for further reads.

 

2.1 Generate a bot using BotFather

To create your bot, open Telegram from your laptop or phone and find the user BotFather: you can start a conversation with the bot and type /newbot to start the creation process; a set of questions will guide you to create your bot.

Once completed, BotFather will generate an API token for your bot and that’s all you need to set it up. The token will look like this: 123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ).

Copy it: we’ll need it later to authenticate with the Telegram API.

 

2.2 Install dotenv

Since we are introducing an environment variable (which are private and global keys such as the Telegram bot token), we need to provide the app with a secure place to store them.

We’ll use the dotenv gem to securely store the token in our environment variables and have it accessible throughout the entire app.

  1. Add dotenv-rails to your Gemfile:
    gem 'dotenv-rails', groups: [:development, :test]

  2. Run bundle install to install the gem.
  3. Create a .env file in the root of your project and add the bot token:
    TELEGRAM_BOT_TOKEN=123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ

  4. Add .env to your .gitignore file to ensure the token isn’t pushed to git.
    echo '.env' >> .gitignore

 

3. Create Telegram service

Now that our app and bot are all set up, we can implement the functionality to send a message to a Telegram chat. We are going to need a gem to make HTTP requests, and a Bot Class to handle sending messages via the Telegram API.

To follow Rails best practices, let’s write the code for handling requests to the Telegram API as a service — that’s a neat place to store the logic to interact with third parties API.

 

3.1 Install HTTParty

As anticipated, we’ll use the httparty gem to handle HTTP requests to the Telegram API.

  1. Add httparty to your Gemfile:
    gem 'httparty'  

  2. Run bundle install to install the gem.

 

3.2 Create TelegramBot

It’s time to code the Bot Class! Let’s start by creating new service-class file to encapsulate the logic for communicating with the Telegram API.

  1. First, create a directory for services if it doesn’t already exist:
    mkdir -p app/services

  2. Create a new file telegram_bot.rb in the app/services directory and code the initialize and create method:
    # app/services/telegram_bot.rb

    require ‘httparty’

    class TelegramBot
    # telegram base URL
    TELEGRAM_API_URL = “https://api.telegram.org/bot”

    def initialize
    @token = ENV[‘TELEGRAM_BOT_TOKEN’] # read from .env
    end

    def send_message(chat_id, message)
    # URL to send messages via bot
    url = “#{TELEGRAM_API_URL}#{@token}/sendMessage”

    # send post request with httparty
    response = HTTParty.post(url, body: { chat_id: chat_id, text: message })
    JSON.parse(response.body)
    end
    end

 

A simple class method that sends a dynamic message via HTTP is all the Bot needs to interact with Telegram! This implementation is the base for any use-case and can be customised further: this Telegram introduction for developers offers some interesting guide to integrate advanced features.

 

4. Test service

Before moving on with the rest of the implementation, let’s verify if the TelegramBot works by creating a new instance and using it to send a message from the console. This is the first interaction between Rails and Telegram!

 

4.1 Create Telegram channel

To test the TelegramBot, we need a channel to receive messages. Create a Telegram group or channel: here, you can add other participants and you should add your bot as an admin — this is needed to send messages and is the only permission that you need to grant, the others are optional.

 

4.2 Get channel id

Next up, we want to connect the channel with the Rails application: we are going to do it via the unique id of the channel.

To retrieve the channel id, you can send a message in the channel and forward it to the “JsonDumpBot” on Telegram (this is a little, useful bot to expose public Telegram data).

In the chat with JsonDumpBot, look for the forwarded_from_chat["id"] in the response and copy the value — it should start with a - for channels.

 

4.3 Send a message from the console

With a Bot service and a channel id, we have everything we need to send the first message!

  1. Open your Rails console:
    bin/rails console  

  2. Instantiate the TelegramBot service, plug your chat id and send a test message:
    bot = TelegramBot.new chat_id = "<your-chat-id>" # Replace with the target chat ID bot.send_message(chat_id, "Hello from Rails!")

If everything worked correctly, you should have received a message from your bot.

 

5. Connect the frontend

The core of the Telegram configurations is done, and we only have a few extra steps to connect it to the rest of the application and start using its functionalities.

 

5.1 Add TELEGRAM_CHAT_ID to the .env file

Before proceeding, ensure that your Telegram chat id is added to the .env file as this id is required to send messages to the correct chat — remember to keep the - at the beginning!

  1. Open your .env file and add the following line, replacing <your-chat-id> with the one you copied before:
     TELEGRAM_CHAT_ID=<your-chat-id>

 

5.2 Create messages controller

Time for a good old Rails implementation! To start sending messages, we need a POST route and a controller action to handle the logic.

To keep the code neat, we’ll create a new controller to handle incoming messages and connect them to the Telegram service. Here, we need a create action to read data from the form and process it through the TelegramBot we created before.

  1. Start by generating a new controller:
    rails generate controller Messages

  2. Open app/controllers/messages_controller.rb and define the create action – here we are going to instantiate a new TelegramBot and use it to send the message from the form:
    class MessagesController < ApplicationController
    def create
    @message_content = params[:message][:content]if @message_content.present?
    bot = TelegramBot.new # instantiate new bot
    chat_id = ENV[‘TELEGRAM_CHAT_ID’] # reading from .env
    response = bot.send_message(chat_id, @message_content)if response[“ok”]
    flash[:notice] = “Message sent successfully!”
    else
    flash[:alert] = “Failed to send message: \#{response[“description”]}”
    end
    else
    flash[:alert] = “Message content cannot be blank.”
    endredirect_to root_path
    end
    end

 

5.3 Setup the POST route

Next, let’s add the POST route to handle form submissions and invoke the logic we just wrote.

  1. Open config/routes.rb and add the following line:
    Rails.application.routes.draw do
    root “pages#home”
    resources :messages, only: :create
    end

 

5.4 Connect the form

It’s finally time to connect the frontend! Navigating to app/views/pages/home.html.erb you can see there is a simple_form form already coded, but without action. All you need to do is use the path of the create action we just implemented in the controller. Don’t forget to restart the server to load the new gems and environment variables!

  1. Replace the url: '#' with the correct :message route – this is the route to post messages, which will receive and process the text from the user to send it via the bot:
    <div class=”flex flex-col items-center gap-8″>
    <h1 class=”text-4xl pb-2 font-bold font-[‘Roboto’]”>🤖 Rails x Telegram 🤖</h1><%= simple_form_for :message, url: messages_path, method: :post, html: { class: ‘flex gap-2’ } do |f| %>
    <%= f.input :content,
    label: false,
    placeholder: ‘Type your message…’,
    input_html: {
    class: ‘px-4 py-2 border-gray-200 border rounded-lg w-80 focus:outline-none shadow-sm’
    } %><%= f.button :button, type: :submit, class: ‘px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-700 flex items-center gap-2 cursor-pointer shadow-sm’ do %>
    <svg xmlns=”http://www.w3.org/2000/svg” fill=”none” viewBox=”0 0 24 24″ stroke-width=”1.5″ stroke=”currentColor” class=”w-5 h-5″>
    <path stroke-linecap=”round” stroke-linejoin=”round” d=”M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5″ />
    </svg>
    Send
    <% end %>
    <% end %>
    </div>

That’s it! You should be receiving the messages in your Telegram channel. With this foundation, you can expand your bot’s functionality to handle user interactions, automate workflows, or provide real-time updates.

The full code of this tutorial can be found under the implementation branch of the same project. To discover all the available features, refer to the Telegram API docs and their detailed guide to bot features. Happy hacking!

Our users have also consulted:
Life Long Learning And A Community That Cares

Jack is someone who continually strives to learn, to keep up with the tech landscape

Pour développe mes compétences
Formation développeur web
Formation data scientist
Formation data analyst
Les internautes ont également consulté :

Suscribe to our newsletter

Receive a monthly newsletter with personalized tech tips.