我使用这个Ruby代码来运行Telegram messenger bot。使用/start
命令运行代码后,它崩溃并出现以下错误:
./bot.rb:26:in `block (3 levels) in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
from ./bot.rb:20:in `loop'
from ./bot.rb:20:in `block (2 levels) in <main>'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:41:in `block in fetch_updates'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:37:in `each'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:37:in `fetch_updates'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:29:in `listen'
from ./bot.rb:17:in `block in <main>'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:22:in `run'
from /var/lib/gems/2.1.0/gems/telegram-bot-ruby-0.3.11/lib/telegram/bot/client.rb:10:in `run'
from ./bot.rb:16:in `<main>'
Bot代码在这里:
require 'telegram/bot'
token = '...'
require 'net/http'
url = URI.parse('http://api.wotblitz.ru/wotb/clans/info/?application_id=...&clan_id=8')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
require 'json'
str = JSON.parse(res.body)
ids = str["data"]["8"]["members_ids"]
n = 0
m = ids.size - 1
players = ''
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
case message.text
when '/start'
loop do
url = URI.parse('http://api.wotblitz.ru/wotb/account/info/?application_id=...&account_id=' + ids[n].to_s)
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http| http.request(req)
}
str1 = JSON.parse(res.body)
nick = str1["data"][ids[n].to_s]["nickname"]
players = players + nick + "\n"
n += 1
break if n == m
end
bot.api.sendMessage(chat_id: message.chat.id, text:"#{players}")
end
end
end
答案 0 :(得分:0)
如果有人遇到同样的问题,我找到了一个解决方法。从我的 macOS 终端运行此代码时,我收到 undefined method 'run' 消息。另一方面,当我在我的 vscode 终端中运行它时,它可以正常工作。我在 Linux 机器上也遇到了同样的问题。这可能与我的环境设置方式有关。
希望这对某人有所帮助。