python - python 上的简单 XMPP 机器人

标签 python xmpp twisted bots

我有Python的XMPP机器人的简单代码和http://xmpppy.sourceforge.net/

#!/usr/bin/python
# -*- coding: utf-8 -*-

import xmpp
import urllib2
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('ipbot.conf')

##########################
user= (config.get('account', 'login'))
password=(config.get('account', 'password'))
presence=(config.get('presence','presence'))
##########################

jid=xmpp.protocol.JID(user)
client=xmpp.Client(jid.getDomain())
client.connect()
client.auth(jid.getNode(),password)

################Parse IP##################
strURL='http://api.wipmania.com/'
f = urllib2.urlopen(urllib2.Request(strURL))
response = f.read()
ipget= response.split("<br>")
f.close()
#############################################

def status(xstatus):
    status=xmpp.Presence(status=xstatus,show=presence,priority='1')
    client.send(msging)

def message(conn,mess):

  global client

  if ( mess.getBody() == "ip" ):
    client.send(xmpp.protocol.Message(mess.getFrom(),ipget[1]+" => "+ipget[0]))#Send IP

client.RegisterHandler('message',message)

client.sendInitPresence()

while True:
    client.Process(1)

请告诉我如何翻译此代码以使用 http://wokkel.ik.nu/和twistedmatrix.com/ 非常感谢。

最佳答案

下面的代码应该可以做到这一点。一些注意事项:

  • Wokkel 使用所谓的子协议(protocol)处理程序来支持特定的 子协议(protocol),通常按概念特征、命名空间或每个 XEP。
  • XMPPClient 是所谓的流管理器,用于建立连接, 并负责与服务器的身份验证。它与 连接子协议(protocol)处理程序来处理带有 XML 流的流量 管理。如果连接丢失,它会自动重新连接。
  • 此示例定义了一个新处理程序来处理传入消息。
  • 与原始代码不同,这里检索 IP 地址的请求是 对正文中包含 ip 的每条传入消息执行此操作。
  • 在原始代码中,从未调用过status。我现在使用 PresenceProtocol 子协议(protocol)处理程序,用于每次发送出席信息 连接已建立并且身份验证已进行。

该示例是一个所谓的 Twisted 应用程序,将使用 twistd 启动,如文档字符串中所述。这将使进程守护进程并将日志发送到 twisted.log。如果您指定 -n(在 -y 之前),它将不会分离并记录到控制台。

#!/usr/bin/python

"""
XMPP example client that replies with its IP address upon request.

Usage:

    twistd -y ipbot.tac
"""

import ConfigParser

from twisted.application import service
from twisted.python import log
from twisted.web.client import getPage
from twisted.words.protocols.jabber.jid import JID
from twisted.words.protocols.jabber.xmlstream import toResponse

from wokkel.client import XMPPClient
from wokkel.xmppim import PresenceProtocol, MessageProtocol

class IPHandler(MessageProtocol):
    """
    Message handler that sends presence and returns its IP upon request.

    @ivar presenceHandler: Presence subprotocol handler.
    @type presenceHandler: L{PresenceProtocol}

    @ivar show: Presence show value to send upon connecting.
    @type show: C{unicode} or C{NoneType}
    """

    def __init__(self, presenceHandler, show=None):
        self.presenceHandler = presenceHandler
        self.show = show


    def connectionInitialized(self):
        """
        Connection established and authenticated.

        Use the given presence handler to send presence.
        """
        MessageProtocol.connectionInitialized(self)
        self.presenceHandler.available(show=self.show, priority=1)


    def onMessage(self, message):
        """
        A message has been received.

        If the body of the incoming message equals C{"ip"}, retrieve our
        IP address and format the response message in the callback.
        """
        def onPage(page):
            address, location = page.split(u"<br>")
            body = u"%s => %s" % (location, address)
            response = toResponse(message, stanzaType=message['type'])
            response.addElement("body", content=body)
            self.send(response)

        if unicode(message.body) != u"ip":
            return

        d = getPage("http://api.wipmania.com")
        d.addCallback(onPage)
        d.addErrback(log.err)



# Read the configuration file
config = ConfigParser.ConfigParser()
config.read('ipbot.conf')

user =  config.get('account', 'login')
password = config.get('account', 'password')
presence = config.get('presence','presence')

# Set up a Twisted application.
application = service.Application('XMPP client')

# Set up an XMPP Client.
jid = JID(user)
client = XMPPClient(jid, password)
client.logTraffic = True
client.setServiceParent(application)

# Add a presence handler.
presenceHandler = PresenceProtocol()
presenceHandler.setHandlerParent(client)

# Add our custom handler
ipHandler = IPHandler(presenceHandler, presence)
ipHandler.setHandlerParent(client)

关于python - python 上的简单 XMPP 机器人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5950156/

相关文章:

java - 使用 Pidgin 测试 XMPP Camel 路由

python - 如何获取 n*m 矩阵行的所有可能和的列表

python - 如何将数据框中的符号转换为 python 中的 float ?

python - 如何旋转数据框

ios - XMPPFramework - 如果尚未创建 vCard,则不会更新昵称

xml - JSON Schema 与 XML Schema 的比较及其 future

python - 非阻塞 Scrapy 管道到数据库

twisted - 如何将结构化数据从 Twisted 发送到系统日志?

python - 在 Python3 中对 Twisted 代码运行测试

python - 用 Python 绘制实时数据