📜 ⬆️ ⬇️

Writing a Telegram bot in Ruby in 10 lines


After the release of the Telegram Bot Platform, many thought about writing their own bot. This post describes the minimum steps required to write your own Ruby bot. All you need is a Telegram account and a machine with Ruby installed on it.

I chose Ruby because of the convenient gem for working with Telegram bot api.

The first thing to do is to create a .rb file in which the bot's logic will be stored, for example, start_bot.rb, and add the minimum code necessary for the bot to work:
require 'telegram/bot' token = 'YOUR_TELEGRAM_BOT_API_TOKEN' Telegram::Bot::Client.run(token) do |bot| bot.listen do |message| case message.text when '/start' bot.api.sendMessage(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}") end end end 

For the server is missing only the installation of the gem . Installation can be done in two ways:
1. Install the heme directly on the machine:
 gem install telegram-bot-ruby 

2. Using a gemfile
 gem 'telegram-bot-ruby' 

followed by execution
 bundle 

For simplicity, I used the first method.

Now you need to get a token for the bot.
Go to Telegram, add the @BotFather bot, and create a bot:

')
Next, add the token to the file and get the ready server for the bot:
 require 'telegram/bot' token = '118997426:AAFVFtYa15Z7ckyDUIHb578NazgepL4kmU8' Telegram::Bot::Client.run(token) do |bot| bot.listen do |message| case message.text when '/start' bot.api.sendMessage(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}") end end end 


To check the operation of the bot at the beginning we start the server:
 ruby start_bot.rb 

And then we write the bot in Telegram:


As you can see, everything works.

PS: I deleted the bot after, so my token, like the bot, is inaccessible.

UPD:
3 lines in ruby
 require 'telegram/bot' token = '<>' Telegram::Bot::Client.run(token) { |bot| bot.listen { |message| bot.api.sendMessage(chat_id: message.chat.id, text: 'Hi!') if message.text == '/start' } } 


Thanks for Python lybin
3 lines in Python
 from twx.botapi import TelegramBot token = '<>' while True: [lambda update: TelegramBot(token).send_message(update.message.chat.id, 'test message body') if update.message.text.startswith('/start') else None for update in TelegramBot(token).get_updates().wait()] 

Source: https://habr.com/ru/post/264707/


All Articles