1
我想让我的机器人在并行线程中发送和接收消息。我也希望我的机器人在收到用户的任何消息时将消息发回给用户。但现在他每5秒发回一次。我明白,这是因为我用“循环做”,但没有无限循环,我不能使用回调。 那么如何在并行线程中发送和接收消息呢?如何在接收消息时克服我的“循环问题”?Ruby XMPP4R机器人和线程 - 麻烦
require 'xmpp4r'
class Bot
include Jabber
def initialize jid,jpassword
@jid = jid
@jpassword = jpassword
@client = Client.new(JID::new(@jid))
@client.connect
@client.auth(@jpassword)
@client.send(Presence.new.set_type(:available))
end
def wait4msg
loop do
@client.add_message_callback do |msg|
send_message(msg.from,msg.body)
sleep 5
end
end
end
def send_message to,message
msg = Message::new(to,message)
msg.type = :chat
@client.send(msg)
end
def add_user jid
adding = Presence.new.set_type(:subscribe).set_to(jid)
@client.send(adding)
end
end
bot = Bot.new('[email protected]','123456')
t1 = Thread.new do
bot.wait4msg
end
t2 = Thread.new do
bot.send_message('[email protected]',Random.new.rand(100).to_s)
end
Thread.list.each { |t| t.join if t != Thread.main }