`

xmpppy + openfire

阅读更多
最近公司有个在线聊天的需求,最新看了一下xmpp
Server 使用的事OpenFire 数据库使用的事Mysql
功能到时齐全,但是,跟自有项目的整合就成了问题,有一些需求实现不了,下面是个实验的例子,仅供参考 :)

#coding=utf-8
""" notgen.py """

import sys, os
import xmpp
import time
import string
from threading import Thread

ROOM = ''
LOGGING = 1


#utility functions
def buildTrans():
	"""
create a translation table using string.maketrans to help remove unwanted
chars from the sql string to output. If a char is not in the set 'printable'
translate it to a space.
"""
	dl = ''
	sl = ''
	for i in range(256):
		c = chr(i)
		if c not in string.printable:
			dl = dl + c
			sl = sl + ' '
	return string.maketrans(dl, sl)

#global translate table built from above function...used to remove
#unwanted chars from sql record output.
TTABLE = buildTrans()


def messageCB(conn, msg):
	mt = msg.getType()
	mgf = msg.getFrom()
	mb = msg.getBody()
	try:
		msg = msg.encode("utf-8")
	except:
		pass

	if mt == 'groupchat':
		print mgf + ': ' + mb
	if mt == 'chat':
		print "\033[1m\033[36m %s say: %s\033[0m" % ( mgf, mb)
		print


def presenceCB(conn, msg):
	""""
Please note: this function is a call back invoked when a 'presence' type
packet is received. I put a try/except around the code...as we were getting
unicode errors from some source..in the print statement. Did not want to take
the time to troubleshoot further for now.
"""
	try:
		print "presence msg rec'd: ", msg
		prs_type = msg.getType()
		who = msg.getFrom()
		if prs_type == "subscribe":
			conn.send(xmpp.Presence(to=who, typ='subscribed'))
			conn.send(xmpp.Presence(to=who, typ='subscribe'))
	except Exception, e:
		print e
		print 'exception in presenceCB...ignoring'


class gChat(Thread):
	""" to hold data and methods for doing group chat """

	def __init__(self, room=ROOM, jid="edisonlz@localhost", pwd="wwwwww"):
		"""set up connection and etc."""
		Thread.__init__(self)
		self.flag = True
		self.pwds = pwd
		self.rooms = room
		self.jids = jid

	def run(self):
		self.mainloop()

	def stop(self):
		self.flag = False


	def setupConn(self):
		""" set up the IM Connection """
		self.jid = xmpp.protocol.JID(self.jids)
		self.cl = xmpp.Client(self.jid.getDomain(), debug=None)
		self.cl.connect()
		self.cl.auth(self.jid.getNode(), self.pwds)

		self.cl.sendInitPresence()
		self.cl.sendPresence(typ='Available')

		self.cl.RegisterHandler('message', messageCB)
		self.cl.RegisterHandler('presence', presenceCB)

		self.room = self.rooms
		if self.room:
			self.cl.send(xmpp.Presence(to=self.room, status='Available'))

	def StepOn(self):
		try:
			self.cl.Process(1)
		except KeyboardInterrupt:
			return 0
		time.sleep(1)
		return 1

	def sendAvailable(self):
		""" send Available presence """
		self.cl.send(xmpp.Presence(to=self.room, status='Available'))

	def sendMsg(self, msg):
		msg = msg.translate(TTABLE) #REMOVE unwanted chars
		msg = xmpp.protocol.Message(body=msg, typ="chat", to='shaols@localhost', frm='edisonlz@localhost')
		mid = self.cl.send(msg)
		print 'message sent with mid: ', `mid`
		time.sleep(1)


	def mainloop(self):
		""" main loop for this groupchat session """
		while self.flag:
			self.setupConn()
			ct = 0
			while self.StepOn():
				if ct > 60:
					self.sendAvailable()
					ct = 0


class gTalk(Thread):
	def __init__(self, gc):
		Thread.__init__(self)
		self.flag = True
		self.gc = gc

	def run(self):
		while self.flag:
			data = raw_input("\033[1m\033[33m\033[42mchat: \033[0m")
			if data:
				if data == "exit":
					self.stop()
					self.gc.stop()
					exit(1)
					print "exit......."
					
				try:
					self.gc.sendMsg(data.decode("utf-8"))
				except Exception, e:
					self.gc.sendMsg(data)
				print

			time.sleep(0.1)

	def stop(self):
		self.flag = False


def main():
	gc = gChat()
	gt = gTalk(gc)
	try:
		print "[run chat]"
		gc.start()
		print "[run talk]"
		gt.start()
	except KeyboardInterrupt:
		gc.stop()
		gt.stop()
	except Exception, e:
		gc.stop()
		gt.stop()


if __name__ == '__main__':
	main()
分享到:
评论
2 楼 edisonlz 2011-12-27  
danshenwuzui 写道
您好,请问下如何用python向openfire服务器进行注册呢?


直接写mysql 数据库
1 楼 danshenwuzui 2011-12-27  
您好,请问下如何用python向openfire服务器进行注册呢?

相关推荐

    xmpp即时通讯

    描述中提到的“简易集成的第三方库”,指的是XMPP的客户端库,如Smack(Java)、xmpppy(Python)、SwiftXMPP(Swift)等。这些库为开发者提供了方便的API,使得在不同编程语言环境中使用XMPP变得更加便捷。 **7. ...

    python-xmpp-client:非常简单的 Python 命令行工具,用于与 XMPP 服务器交互以发送通知消息

    要求Python 2.6+ Python xmpppy 库 -> 示例用法 python xmpp_cli.py --helpusage: xmpp_cli.py [-h] [-d HOST] [-u USER] [-pw PASSWORD] [-t [TO [TO ...]]] [-g GROUP] [-p PORT] [-m MESSAGE] [-de]A simple XMPP...

    分布式 XMPP Server 共32页.ppt

    XMPP的核心组件包括服务器、客户端和库,它们分别由不同的开源项目支持,如ejabberd、openfire(服务器)、Pidgin、Spark(客户端)以及libjingle、smack(库)。XMPP的优势在于它拥有完整的开源生态系统,能够快速...

    raspi_gtalk_robot:适用于Raspberry Pi的Python Gtalk(XMPP)Bot

    3.安装GPIO,xmpppy和pydns模块。 sudo pip install RPi.GPIO xmpppy pydns 4.克隆该存储库。 git clone https://github.com/UlisesGascon/raspi_gtalk_robot.git 5输入文件夹。 cd raspi_gtalk_robot 6.编辑...

    python标准库和扩展库.docx

    xmpppy 模块支持 XMPP 协议,Google Talk 也是采用 XMPP 协议的 IM 系统,我们可以通过该模块与 Jabber 服务器通信。 这些库和模块只是 Python 标准库和扩展库的一部分,Python 的强大之处就在于其丰富的库和模块,...

    GTalkShell:通过Google Talk环聊命令您的服务器

    GTalkShell 关于: GTalkShell允许您通过Google Talk / Hangouts将命令... 安装xmpppy 安装pydns 克隆此存储库 为您的服务器创建一个新的Google帐户 在“ login.txt”中设置适当的身份验证详细信息 在Web浏览器中以

    Python模块篇[定义].pdf

    XMPPPY 是一个用于处理XMPP(Extensible Messaging and Presence Protocol)协议的Python库,常用于即时通讯应用。 16. cjkcodecs: cjkcodecs 是一个Python模块,提供了对CJK(中日韩)字符编码的支持,帮助处理...

    xmpp聊天:El mejor proyecto de todos:smiling_face_with_heart-eyes:

    请使用您的Python软件包安装程序并下载以下软件包: $ pip install bullet$ pip install tkinter$ pip install colorama$ pip install xmpppy$ pip install sleekxmpp 另外,该程序使用以下库: base64 穿线时间...

    Packt.Practical.XMPP.

    - **利用现有库和框架**:许多编程语言提供了专门针对XMPP的库和框架,例如Java中的Smack、Python中的xmpppy等。 - **设计和实现**:根据具体需求设计应用程序的逻辑流程,实现客户端和服务器之间的通信。 ##### 5....

Global site tag (gtag.js) - Google Analytics