开发者

Ruby XMPP4R bot and Threads - trouble

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
    开发者_JAVA技巧    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 }


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜