Create a bot quote bot to be precise
Requirements
Must have an ide
Basic or advanced knowledge in Ruby
project_folder/
├── bot.rb
├── quote.rb
├── help.rb
├── start.rb
└── Gemfile
Note: no .env here cause it’s meant to be secure and not to be commited to git
- Let’s start with start.rb
#start.rb
class Start
def initialize(bot)
@bot = bot
start_handler
end
def start_handler
@bot.command("start") do |ctx|
ctx.reply("welcome to quote_bot use /quote to get astonishing quotes")
end
end
end
this file uses telegem two methods one .command this helps you with handling / commands e.g /help /start /quote and so on
second is the ctx.reply method this is used to send a reply back to the current chat it automatically adds the id and it can take **options e.g reply_markup, parse_mode and so on with time you will eventually see how they are been used
- help.rb
#help.rb
class Help
def initialize(bot)
@bot = bot
send_help_message
end
def send_help_message
@bot.command("help") do |ctx|
help_message = <<~TEXT
use /quote to get quotes
use /help to show this help message
TEXT
ctx.reply(help_message, parse_mode: 'Markdown')
end
end
end
-quote.rb
this is where knowledge in some gems is required in this special case we using httparty
require 'httparty'
require 'json'
class Quote
def initialize(bot)
@bot = bot
find_quotes
end
def find_quotes
@bot.command("quote") do |ctx|
response = HTTParty.get("https://zenquotes.io/api/random")
if response.success?
data = JSON.parse(response.body)
quote_data = data.first
quote = quote_data['q']
author = quote_data['a']
message = <<~TEXT
QUOTE OF THE DAY
quote: #{quote}
author: #{author}
credit: zenquotes
TEXT
ctx.reply(message, parse_mode: 'Markdown')
else
ctx.reply("failed to fetch code")
end
end
end
end
-bot.rb the main file
#bot.rb
require 'telegem'
require 'dotenv/load'
require_relative 'help'
require_relative 'start'
require_relative 'quote'
bot = Telegem.new(ENV['BOT_TOKEN'])
Start.new(bot)
Help.new(bot)
Quote.new(bot)
bot.start_polling
puts "bot has started")
- now we need our Gemfile
source 'https://rubygems.org'
gem "telegem", "~>3.0.4"
gem "httparty", "~>0.21.0"
gem "dotenv", "~>2.8"
important don’t forget your .env
BOT_TOKEN=<your token here>
Now we need to install and run using bundle
-if you don’t have bundle gem still works or run
$ gem install bundle
- now you can run using bundle but first let’s install all gems we need
$ bundle install
Then now we run our code
$ bundle exec ruby bot.rb
For more detailed examples
Visit repo
- Star the repo
- Visit the examples to study more examples
Top comments (0)