简体   繁体   中英

Simple XMPP bot on python

I have the simple code of XMPP bot by python and 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)

Please, tell me, how to translate this code to use http://wokkel.ik.nu/ and twistedmatrix.com/ Thanks a lot.

The following code should do it. A few notes:

  • Wokkel uses so-called subprotocol handlers to cover support for specific subprotocols, usually split up by conceptual feature, by namespace or per XEP.
  • XMPPClient is a so-called stream manager that establishes connections, and takes care of authentication with the server. It works with the hooked-up subprotocol handlers to process traffic with the XML stream it manages. It automatically reconnects if the connection has been lost.
  • This example defines one new handler to process incoming messages.
  • Unlike the original code, here the request to retrieve the IP address is done for each incoming message with ip in the body.
  • In the original code, status was never called. I now the use PresenceProtocol subprotocol handler to send out the presence each time a connection has been established and authentication has taken place.

The example is a so-called Twisted Application, to be started using twistd , as mentioned in the docstring. This will daemonize the process and logs go to twisted.log . If you specify -n (before -y ), it will not detach and log to the console instead.

#!/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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM