如何使用Ruby在自定义Discord客户端中检索消息内容?

qyuhtwio  于 2023-06-29  发布在  Ruby
关注(0)|答案(1)|浏览(100)

我用Ruby创建的自定义Discord客户端有一个问题,它只用于阅读消息。当试图检索消息内容时,我什么也没有收到,而且出现了一个奇怪的错误,我不知道为什么。下面是我使用的代码:

require 'websocket-client-simple'
require 'json'

token = 'My discord account token (Not a bot token!)'
url = 'wss://gateway.discord.gg'
version = '9'
encoding = 'json'

client = WebSocket::Client::Simple.connect("#{url}/?v=#{version}&encoding=#{encoding}")

client.on(:open) do
  client.send({ op: 2, d: { token: token, intents: 513, properties: { '$os': 'linux', '$browser': 'chrome', '$device': '' } } }.to_json)
end

client.on(:message) do |msg|
  data = JSON.parse(msg.data)
  if data['op'] == 0 && !data['d']['webhooks']
    channel_id = data['d']['channel_id'] || ''
    username = data['d']['author']['username'] || ''
    content = data['d']['content'] || ''
    puts "[#{channel_id}] <#{username}> #{content}"
  end
end

client.on(:error) do |e|
  puts "Error: #{e.message}"
end

client.on(:close) do |e|
  puts "Closed: #{e}"
end

at_exit do
  client&.close
end

loop do
  # do something else while listening
end

运行程序并在Discord中发送了几条消息后,我收到了以下输出:

alex@Alexs-PC:/media/alex/2-TB/STORAGE/Absolute-Solver/ASLDC/ASLDC-4.0$ ruby main.rb
Error: undefined method `[]' for nil:NilClass
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
Error: undefined method `[]' for nil:NilClass
Error: undefined method `[]' for nil:NilClass
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
Error: undefined method `[]' for nil:NilClass
[1116271442372333572] <sobinec> 
[1116271442372333572] <sobinec> 
Error: 809: unexpected token at ''

正如您从输出中看到的,我无法检索消息内容,并收到一个奇怪的错误。我无法使用机器人令牌或某些机器人库,如discordrb,因为它们无法与Discord帐户令牌一起正常工作。任何见解或建议将不胜感激。谢谢你。
问题:未从ChatGPT接收到预期的响应和无错误消息
预期成果:接收已发送的消息和无错误的响应
采取的步骤:
1.尝试向ChatGPT寻求帮助
1.没有收到有用的回复
预期已发送消息,无错误。我问了ChatGPT,但没有帮助。

hc8w905p

hc8w905p1#

根据错误消息Error: 809: unexpected token at ''传入的消息不是有效的JSON文档。因此,尝试将此消息解析为JSON会引发该错误。
为了使你的代码安全,可以这样修改:

client.on(:message) do |msg|
  data = JSON.parse(msg.data)
  if data['op'] == 0 && !data['d']['webhooks']
    channel_id = data['d']['channel_id'] || ''
    username = data['d']['author']['username'] || ''
    content = data['d']['content'] || ''
    puts "[#{channel_id}] <#{username}> #{content}"
  end
rescue => e
  puts "Error occurred: #{e} on #{msg}"
end

UPD:这有助于识别问题:在接收的消息中没有“作者”键。应该使用“user”键:

username = data['d']['user']['username'] || ''

相关问题