我的任务是不久前使用ruby创建一个电报机器人。 我不知道从哪里开始,就像其他程序员一样,我转向互联网寻找线索。 我找不到好的文章,因此在创建该机器人时遇到了很多问题。 我决定写一篇文章来解释如何从头开始创建电报机器人。
我将通过创建一个激励电报机器人来教您。 可以在下面找到每行要使用的代码: telegram_repository 。
我们需要它来运行电报机器人并对其进行初始化。 要创建一个帐户,请点击以下链接: telegram-signUp 。
我们将使用Ruby编程语言来编写所需的代码,因此,您将需要在计算机中安装ruby。 要安装Ruby,请阅读此Ruby安装文档并按照说明进行操作。
安装ruby并创建帐户后,我们还需要从电报中获取称为API令牌的代码。 为此,我们需要机器人父亲的帮助。 只需输入命令/ new bot,然后按照 机器人父亲的指示。
现在有趣的部分开始了,您需要在计算机中创建一个目录,然后使用所选的代码编辑器将其打开。 然后通过在终端或命令行中运行bundle init
来初始化ruby Gemfile 。 确保您在工作目录中。
然后,您需要在您的gem文件中添加这些gem,因为我们将要使用它们
gem 'telegram-bot-ruby'
gem 'json'
gem 'net-http-persistent' , '~> 2.9' , '>= 2.9.4
然后run bundle install
安装依赖项
我们需要创建一个可执行文件来负责初始化我们的机器人。 为此,请创建一个bin目录,并在其中创建一个名为main.rb
的文件。
要初始化我们的应用程序,我们需要一个bot类的实例,稍后将要创建它。 因此,在您的main.rb
文件中键入以下代码。
require_relative '../lib/bot.rb'
require_relative '../lib/motivate.rb
Bot.new
我们需要为逻辑创建几个ruby类。 我们将创建一个BOT类来托管所有电报机器人API逻辑,并创建MOTIVE类以向API端点发出请求。
创建一个lib目录并创建一个bot.rb
文件。 我们需要对Telegram的Bot API使用Ruby 包装器 。 在bot.rb
文件中键入以下代码。
require 'telegram/bot'
require_relative 'motivate.rb'
class Bot
def initialize
token = '{enter your code}'
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: "Hello, #{message.from.first_name} , welcome to motivation chat bot created by peter robert, the chat bot is to keep you motivated and entertained. Use /start to start the bot, /stop to end the bot, /motivate to get a diffrent motivational quote everytime you request for it or /joke to get a joke everytime you request for it" )
when '/stop'
bot.api.send_message( chat_id: message.chat.id, text: "Bye, #{message.from.first_name} " , date: message.date)
when '/motivate'
values = Motivate.new
value = values.select_random
bot.api.send_message( chat_id: message.chat.id, text: " #{value[ 'text' ]} " , date: message.date)
else bot.api.send_message( chat_id: message.chat.id, text: "Invalid entry, #{message.from.first_name} , you need to use /start, /stop , /motivate or /joke" )
end
end
end
end
end
您需要插入从上述第三步获得的API令牌。
我们正在创建一个激励机器人,为了实现这一目标,我们需要向终结点发出请求,该终结点将激励消息作为JSON响应返回。
我们将使用类型适合引号来获取消息。 首先,让我们创建一个类来托管我们的逻辑。 在lib目录中,创建一个名为motive.rb
的文件,然后键入该代码。
require 'telegram/bot'
require 'net/http'
require 'json'
require_relative 'bot.rb'
class Motivate
@values = nil
def initialize
@values = make_the_request
end
def make_the_request
url = 'https://type.fit/api/quotes'
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
response
end
def select_random
@values = @values.sample
@values
end
end
我们已经完成了繁重的工作。 现在初始化我们的机器人,只需在命令行ruby bin/main.rb
运行此代码
然后导航到您的电报帐户并搜索您在上述第三步中创建的漫游器。
请享用!
From: https://hackernoon.com/how-to-create-a-telegram-bot-using-ruby-n7ag32c1