开发者

Ruby 24/7 working XMPP bot

Could someone help me with this? I would to create a bot which receives word in one language, looks in database, gets translation and sends it back开发者_开发问答. How i understand it's not possible on shared hostings, but possible on own servers or VDS. So do i need to make my bot using libs like EventMachine and xmpp4r? If yes how to work with many requests at one time?


Receing a word, looking in database and sending the response back is very simple . Your bot should accept every new contact and add them to its roster (contact list).

Take a look a this code. I wrote a bot like "Google Bots" it uses google translation service.

require 'rubygems'  
require 'xmpp4r-simple'
require 'yaml'

class MonBotTraducteur

 def initialize( from='fr', to='en' )
  @url  = 'http://ajax.googleapis.com/ajax/services/language/translate' 
  @from = from
  @to   = to
 end
 # 
 def connect  
  config= YAML::load( File.read( 'config/settings.yaml' ) )
  @client = Jabber::Simple.new( config['settings']['jabber']['jid'], 
          config['settings']['jabber']['password'] )
  @client
 end
 # Translate the received message
 def translate( text="" ) 
   params = {
     :langpair => "#{@from}|#{@to}", 
     :q => text,
     :v => 1.0  
   } 
   query = params.map{ |k,v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&')
   reponse = Net::HTTP.get_response( URI.parse( "#{@url}?#{query}" ) )    
   repondre( reponse )
 end
 # Start the bot activity
 def demarrer
  while true
     .received_messages do |msg|
    translated_text = translate( msg.body )
    @client.deliver( msg.from.to_s, translated_text.to_s )  
      end   
     sleep 1
  end
 end

 private
 # A method to send back the response
 def repondre( reponse )
  json = JSON.parse( reponse.body )
  if json['responseStatus'] == 200
      json['responseData']['translatedText']
  else
   raise(StandardError, response['responseDetails'])
  end
 end 
end

bot = MonBotTraducteur.new
bot.connect
bot.demarrer

This bot receives messages, translate them using google service and send them back to senders.

PS : I used a yaml file for the setting.

Best regards,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜