我希望我的机器人在并行线程中发送和接收消息。我也希望我的机器人发送消息回用户时,从用户收到任何消息。但现在他每隔5秒就会把它发回给用户。我知道这是因为我使用了"loop do“,但如果没有无限循环,我就不能使用回调。那么如何在并行线程中发送和接收消息呢?如何克服接收消息时的“循环问题”?
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('from@example.xmpp','123456')
t1 = Thread.new do
bot.wait4msg
end
t2 = Thread.new do
bot.send_message('to@example.xmpp',Random.new.rand(100).to_s)
end
Thread.list.each { |t| t.join if t != Thread.main }
发布于 2010-12-30 20:47:07
日安。你可以在没有循环的情况下使用回调,参见示例。例如:在initialize
中添加
@client.add_message_callback do |m|
if m.type != :error
m2 = Message.new(m.from, "You sent: #{m.body}")
m2.type = m.type
@client.send(m2)
end
end
https://stackoverflow.com/questions/4520421
复制相似问题