Ruby XMPP4R bot and Threads - trouble

1k Views Asked by At

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('[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 }
1

There are 1 best solutions below

0
On

Good day. You can use callbacks without loop, see an examples. For example: in initialize add

@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