I want my bot sends and receives messages in parallel threads. I also want my bot sends message back to user when receives any message from user. But now he sends it back to user every 5 seconds. I understand that it's because i used "loop do" but without infinity loop i cant use callbacks. So how to send and receive messages in parallel threads? And how to overcome my "loop problem" when receiving messages?
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 }