4

我正在尝试修改 slimxmpp echobot 示例以更像客户端。我可以使用下面的代码接收和打印消息,但是如何使代码还允许我随意向另一个 JID 发送消息,而不是作为对收到消息的自动响应。我对 python 比较陌生,所以任何帮助都会非常有用,谢谢。

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

"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2010  Nathanael C. Fritz
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

import sys
import logging
import getpass
from optparse import OptionParser

import sleekxmpp

# Python versions before 3.0 do not use UTF-8 encoding
# by default. To ensure that Unicode is handled properly
# throughout SleekXMPP, we will set the default encoding
# ourselves to UTF-8.
if sys.version_info < (3, 0):
    reload(sys)
    sys.setdefaultencoding('utf8')
else:
    raw_input = input


class EchoBot(sleekxmpp.ClientXMPP):

    """
    A simple SleekXMPP bot that will echo messages it
    receives, along with a short thank you message.
    """

    def __init__(self, jid, password):
        sleekxmpp.ClientXMPP.__init__(self, jid, password)

        # The session_start event will be triggered when
        # the bot establishes its connection with the server
        # and the XML streams are ready for use. We want to
        # listen for this event so that we we can initialize
        # our roster.
        self.add_event_handler("session_start", self.start)

        # The message event is triggered whenever a message
        # stanza is received. Be aware that that includes
        # MUC messages and error messages.
        self.add_event_handler("message", self.message)





    def start(self, event):
        """
        Process the session_start event.

        Typical actions for the session_start event are
        requesting the roster and broadcasting an initial
        presence stanza.

        Arguments:
            event -- An empty dictionary. The session_start
                     event does not provide any additional
                     data.
        """
        self.send_presence()
        self.get_roster()

    def message(self, msg):

        if msg['type'] in ('chat', 'normal'):
            print "%(body)s" % msg


    """        
    def send_message(self, mto, mbody, msubject=None, mtype=None,
                     mhtml=None, mfrom=None, mnick=None):

        self.make_message(mto, mbody, msubject, mtype,
                          mhtml, mfrom, mnick).send()  """




if __name__ == '__main__':
    # Setup the command line arguments.
    optp = OptionParser()

    # Output verbosity options.
    optp.add_option('-q', '--quiet', help='set logging to ERROR',
                    action='store_const', dest='loglevel',
                    const=logging.ERROR, default=logging.INFO)
    optp.add_option('-d', '--debug', help='set logging to DEBUG',
                    action='store_const', dest='loglevel',
                    const=logging.DEBUG, default=logging.INFO)
    optp.add_option('-v', '--verbose', help='set logging to COMM',
                    action='store_const', dest='loglevel',
                    const=5, default=logging.INFO)

    # JID and password options.
    optp.add_option("-j", "--jid", dest="jid",
                    help="JID to use")
    optp.add_option("-p", "--password", dest="password",
                    help="password to use")

    opts, args = optp.parse_args()

    # Setup logging.
    logging.basicConfig(level=opts.loglevel,
                        format='%(levelname)-8s %(message)s')



    # Hard coded for testing.

    opts.jid = "username@x.x.x.x"

    opts.password = "password"

    # Setup the EchoBot and register plugins. Note that while plugins may
    # have interdependencies, the order in which you register them does
    # not matter.
    xmpp = EchoBot(opts.jid, opts.password)
    xmpp.register_plugin('xep_0030') # Service Discovery
    xmpp.register_plugin('xep_0004') # Data Forms
    xmpp.register_plugin('xep_0060') # PubSub
    xmpp.register_plugin('xep_0199') # XMPP Ping

    # If you are working with an OpenFire server, you may need
    # to adjust the SSL version used:
    # xmpp.ssl_version = ssl.PROTOCOL_SSLv3

    # If you want to verify the SSL certificates offered by a server:
    # xmpp.ca_certs = "path/to/ca/cert"

    # Connect to the XMPP server and start processing XMPP stanzas.
    if xmpp.connect():
        # If you do not have the dnspython library installed, you will need
        # to manually specify the name of the server if it does not match
        # the one in the JID. For example, to use Google Talk you would
        # need to use:
        #
        # if xmpp.connect(('talk.google.com', 5222)):
        #     ...
        xmpp.process(block=True)
        print("Done")
    else:
        print("Unable to connect.")
4

2 回答 2

4

我已经弄清楚了这个问题。这个问题可以使用 xmlstream._start_thread 来解决。但它仍然有点难看。

import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp

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


class EchoBot(sleekxmpp.ClientXMPP):
    u"""
    a simple sleekxmmp bot that will echo message
    """

    def __init__(self, jid, pwd):
        sleekxmpp.ClientXMPP.__init__(self, jid, pwd)

        self.add_event_handler('session_start', self.start)

        self.add_event_handler('message', self.message)

    def start(self, event):
        u"""
        process session start
        """
        self.send_presence()
        self.get_roster()
        self._start_thread("chat_send", self.chat_send)

    def message(self, msg):
        if msg['type'] in ('chat', 'normal'):
            print "others send: %s" % msg
            msg.reply('Thanks for sending\n%(body)s' % msg).send()

    def chat_send(self):
        while True:
            line = raw_input("send: ")
            if line == "quit":
                break
            print "you send: %s" % line
            self.send_message("test2@dp-pc", line)


if __name__ == "__main__":
    optp = OptionParser()

    optp.add_option('-q', '--quiet', help='set logging to error',
                action="store_const", dest="loglevel",
                const=logging.ERROR, default=logging.INFO)
    optp.add_option('-d', '--debug', help='set logging to debug',
                action="store_const", dest="loglevel",
                const=logging.DEBUG, default=logging.INFO)
    optp.add_option('-v', '--verbose', help='set logging to comm',
                action="store_const", dest="loglevel",
                const=5, default=logging.INFO)

    optp.add_option('-j', '--jid', dest="jid",
                help="jid to use")
    optp.add_option('-p', '--password', dest='password',
                help="password to use")

    opts, args = optp.parse_args()

    logging.basicConfig(level=opts.loglevel,
                    format='%(levelname)-8s %(message)s')

    if opts.jid is None:
        opts.jid = raw_input("username:")
    if opts.password is None:
        opts.password = getpass.getpass("Password: ")

    xmpp = EchoBot(opts.jid, opts.password)
    xmpp.register_plugin('xep_0030')  # service discovery
    xmpp.register_plugin('xep_0004')  # date form
    xmpp.register_plugin('xep_0060')  # pubsub
    xmpp.register_plugin('xep_0199')  # xmpp ping

    if xmpp.connect():
        print("xmpp start")
        xmpp.process(block=True)
        print("Done")
    else:
        print("unable to connected")
于 2014-09-02T10:19:55.843 回答
2

您的问题的答案在“登录、发送、注销”教程中给出。您发布的标准 EchoBot 代码的主要更改是您

  • 不要注册传入消息的方法和
  • 调用send_message启动函数:

    self.send_message(mto="some@jid", mbody="some message text")
    

显然,您不仅限于start功能;当您想发送消息时,您可以在程序中的任何位置调用此函数。

于 2013-10-02T22:13:33.430 回答