简单地echo回去,使用两个配置文件,config/database.yml, config/xmpp_account.yml
需要生成rails结构,实际上没有用到数据库连接,只是准备而已。
require "rubygems"
require "active_record"
require "yaml"
require "logger"
Dir["app/models/*.rb"].each(){|f| require f}
require "xmpp4r"
class Robot
DEFAULT_PORT=5222
@@xmpp_conn=nil
@@logger=Logger.new("log/robot.log", "daily")
def self.error_log(msg)
@@logger.error(msg)
end
def self.exception_log(title,exp)
error_log(title+exp.message)
exp.backtrace.each(){|e|error_log("#{e}")}
end
def self.debug_log(msg)
@@logger.debug(msg)
end
def self.connect_db
ActiveRecord::Base.establish_connection(
YAML.load_file("config/database.yml")["development"])
end
def self.connect_xmpp
ac=YAML.load_file("config/xmpp_account.yml")["default_account"]
jid=Jabber::JID.new(ac["login_user"])
j=Jabber::Client.new(jid)
j.connect(ac["login_host"],ac["login_port"] || Robot::DEFAULT_PORT)
#auth
j.auth(ac["password"])
#online
p=Jabber::Presence.new(:chat)
j.send(p)
#receive message
j.add_message_callback do |m|
if m.body!=nil && !m.body.empty?
process_command(m.body,m)
end
end
@@xmpp_conn=j
end
#process command
def self.process_command(cmd,msg)
debug_log(cmd)
return_msg=Jabber::Message::new(msg.from,"command is : #{cmd}")
return_msg.type=msg.type
@@xmpp_conn.send(return_msg)
end
def self.init_all
begin
connect_db()
rescue => detail
exception_log("connect database server error:",detail)
raise(detail)
end
begin
connect_xmpp()
rescue => detail
exception_log("connect im server error:",detail)
raise(detail)
end
end
def self.destory_all
begin
if @@xmpp_conn && @@xmpp_conn.is_connected?
@@xmpp_conn.close()
end
rescue => detail
exception_log("connect im server error:",detail)
end
end
def self.get_status
"im server connection:#{@@xmpp_conn && @@xmpp_conn.is_connected?()} db server connection:#{ActiveRecord::Base.connected?}\n"
end
def self.prompt
"input command(type 'help' to get help):"
end
def self.run
puts "init..."
init_all()
puts get_status()
puts prompt()
#loop
while (cmd=gets.chomp().strip()) != ?\e do
case cmd
when "exit"
puts "exit..."
destory_all()
return
when "status"
puts get_status
when "help"
puts "\nexit - exit program\nstatus - show im server and db server connection\n"
end
puts prompt()
end
end
end
连接im服务器是这样的:
先包括XMPP库
require "xmpp4r"
载入帐号配置信息
ac=YAML.load_file("config/xmpp_account.yml")["default_account"]
连接,并且登录
jid=Jabber::JID.new(ac["login_user"])
j=Jabber::Client.new(jid)
j.connect(ac["login_host"],ac["login_port"] || Robot::DEFAULT_PORT)
#auth
j.auth(ac["password"])
上线
p=Jabber::Presence.new(:chat)
j.send(p)
process_command是处理发来的消息,现在就是简单地echo回去。
run里面接受三个命令:help,status,exit