2010-12-23 7 views
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 } 

答えて

0

おはよう。ループなしでコールバックを使用できます(例を参照)。例:in 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 
関連する問題