一个小XMPP client机器人

简单地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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值