Making a simple Telegram Chatbot

Registration

(1) You need to download and install a Telegram client. E.g. Android or iOS.

(2) Register an account on Telegram.

(3) Now, Telegram has this BotFather service where you can create and register a bot with Telegram. BotFather is located at https://telegram.me/botfather

(4) While in the conversation with BotFather, send the following command to start creating a new bot. Remember that the name of your bot has to end with "bot".

/newbot

(5) Once a bot is created, BotFather will send a congratulation message that contains an access token to use the HTTP API. Copy this token as you will need it later.


The Backend

(1) Next, you will need a backend server to process the incoming messages from your Bot. Telegram has 2 ways of receiving messages - Polling or Webhook. In this example, we will be using Webhook method.

(2) We start by creating a new Rails App that handles just 1 route. Let's use the bot ID (XXXXXXXX) as the path.

Rails.application.routes.draw do
  post 'botXXXXXXXX', :to => 'telegram_requests#create'
end

(3) We will inform Telegram that we have a Webhook. To do this, we create an initializer and use it to call the setWebhook API.

HTTParty.get("https://api.telegram.org/botXXXXXXXX:YYYYYYYYYYYY/setWebhook?url=https://myurl/botXXXXXXXX")

(4) Note that all telegram Bot APIs have the following format. They are quite flexible, support both GET/POST and the parameters could be sent via query string, form body or JSON.

https://api.telegram.org/bot<YourToken>/<MethodName>

(5) We also need a controller to parse the message and send a response when we receive a message from the Webhook.

class TelegramRequestsController < ApplicationController
  def create

    chat_id = params[:message][:chat][:id]
    user_first_name = params[:message][:from][:first_name]
    message_text = params[:message][:text]

    case message_text
      when '/start'
        response_text = "Hello #{user_first_name}!"
      when '/stop'
        response_text = "Bye!"
      when '4'
        number = SecureRandom.random_number(9999) + 1
        response_text = "#{'%04d' % number}"
      else
        response_text = "Sorry! I could not understand this command."
    end
    HTTParty.post('https://api.telegram.org/botXXXXXXXX:YYYYYYYYYY/sendMessage',
      :headers => {
        'Content-Type' => 'application/json'
      },
      :body => {
        :chat_id => chat_id,
        :text => response_text
      }.to_json
    )
    render status: :ok

  end
end

(6) Deploy and run your App.

Test It!

(1) To access your Bot, go to https://telegram.me/your_bot or https://t.me/your_bot 

(2) Click the start button to start the conversation.

(3) Type a supported command and check the response.


That's all. You got a simple bot running.


AI Summary
Chrome On-device AI 2024-11-09 05:07:34

Share Article