玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置: 玩蛇网首页 > Python源码实例_Python程序源代码_网站项目下载 > 正文内容

Python WebSocket服务端编程代码完成gtalk机器人

Python入门佳作 经典教程的全新修订 10个项目引人入胜
玩蛇网推荐图文教程:python黑客多线程扫描器

本文python源码为实现,Python WebSocket服务端编程代码完成gtalk机器人的全部代码段。需要用到python sys、sleekxmpp、reactor等python模块及方法,在代码中导入部分可以查看到详细方法。

python websocket库,运作机制及客户端和服务端的 API 实现。Python WebSocket的具体操作方法和工作原理也可以查看相关文章来学习。

Python socket套接字模块server/client端操作

import sys
from twisted.internet import reactor
from twisted.python import log
from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol
import sleekxmpp

reload(sys)
sys.setdefaultencoding('utf8')

class gtalkBot(sleekxmpp.ClientXMPP):

    """
    A basic SleekXMPP bot that will log in, send a message,
    and then log out.
    """

    def __init__(self, jid, password):
        sleekxmpp.ClientXMPP.__init__(self, jid, password)
        self.recipient = 'wxg4net@gmail.com'
        self.status_text = ''
        self.add_event_handler("session_start", self.start)
        self.add_event_handler("message", self.muc_message)
        self.add_event_handler('presence_available',
                               self.handle_presence_available)
        self.add_event_handler('presence_unavailable',
                               self.handle_presence_unavailable)
        self.add_event_handler('presence_dnd',
                               self.handle_presence_dnd)


    def start(self, event):
        self.send_presence()
        self.get_roster()

    def handle_presence_unavailable(self, presence):
        if cmp(presence['from'].bare, self.recipient) == 0:
            self.status_text = presence['status']

    def handle_presence_available(self, presence):
        if cmp(presence['from'].bare, self.recipient) == 0:
            self.status_text = presence['status']

    def handle_presence_dnd(self, presence):
        if cmp(presence['from'].bare, self.recipient) == 0:
            self.status_text = presence['status']

    def muc_message(self, msg):
        fwho = msg['from'].bare
        body = msg['body']
        if cmp(body,'-qsbk') == 0:
            self.send_message(mto=fwho,
                              mbody='当前服务已关闭',
                              mtype='chat')
        elif cmp(body,'-help') == 0:
            self.send_message(mto=fwho,
                              mbody='当前服务开发中...',
                              mtype='chat')
        elif cmp(fwho, self.recipient) == 0:
            factory.broadcast(str(body))
        else:
            self.send_message(mto=fwho,
                              mbody='当前服务开发中...',
                              mtype='chat')

    def sendMessageTome(self, message):
        self.send_message(mto="wxg4net@gmail.com",
                          mbody=message,
                          mtype='chat')
    #python websocket

class BroadcastServerProtocol(WebSocketServerProtocol):

    def __init__(self):
        self.istip = True
        self.Heartbeat()

    def Heartbeat(self):
        reactor.callLater(1, self.Heartbeat)

    def onOpen(self):
        self.factory.register(self)

    def onMessage(self, msg, binary):
        xmpp.sendMessageTome(msg)
        if self.istip:
            self.sendMessage('你好,websocket python的当前状态是:'+str(xmpp.status_text)+'。---祝你生活愉快!')
            self.istip = False

    def connectionLost(self, reason):
        WebSocketServerProtocol.connectionLost(self, reason)
        self.factory.unregister(self)

class BroadcastServerFactory(WebSocketServerFactory):

    protocol = BroadcastServerProtocol

    def __init__(self):
        WebSocketServerFactory.__init__(self)
        self.clients = []

    def register(self, client):
        if not client in self.clients:
            self.clients.append(client)

    def unregister(self, client):
        if client in self.clients:
            self.clients.remove(client)

    def broadcast(self, message):
        if self.clients:
            for c in self.clients:
                c.sendMessage(message)

#www.iplaypython.com

if __name__ == '__main__':
   
1a58
 log.startLogging(sys.stdout)
    xmpp = gtalkBot("phzggzs@gmail.com", "*******")
    xmpp.register_plugin('xep_0030') # Service Discovery
    xmpp.register_plugin('xep_0199') # XMPP Ping
    if xmpp.connect():
        xmpp.process(threaded=True)
        factory = BroadcastServerFactory()
        reactor.listenTCP(9090, factory)
        reactor.run()

玩蛇网文章,转载请注明出处和来源网址:http://www.iplaypython.com/code/c2700.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网PythonQQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
出炉日期:2016-01-26 12:13 玩蛇网 www.iplaypython.com

我要分享到:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules