SleekXMPP随意发送消息并仍然侦听传入的消息。

时间:2013-07-22 15:40:27

标签: python client xmpp chat

我正在尝试修改sleekxmpp 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.")

3 个答案:

答案 0 :(得分: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")

答案 1 :(得分:2)

您的问题的答案在“sign in, send, logout”教程中给出。您发布的标准EchoBot代码的主要更改是

  • 不为传入消息注册方法和
  • 在启动功能中调用send_message

    self.send_message(mto="some@jid", mbody="some message text")
    
显然,你不仅限于start功能;当你想发送信息时,你可以在程序的任何一点调用这个函数。

答案 2 :(得分:0)

问题是如何在不阻塞主线程的情况下监听stdin流。

我尝试使用类似下面的内容::

xmpp_client.process(block=False)
while True:
    line = sys.stdin.readline()
    if line == "quit":
         break
    print "you send: %s" % line
    self.send(line)

但它不起作用。 while会阻止所有的消息。 我查一下来源,真的很奇怪。 sleekxmpp似乎使用多线程。 但是仍然会阻碍整个过程。

所以我认为,你应该在sys.stdin文件上实现类似事件驱动程序的东西。 我查看了回调/ basehandler源代码。它似乎都不合适。 所以问题是如何在输入消息上进行事件驱动以及在何处启动事件循环。

@hannes,我们知道hte send_messages方法。但它没有完成聊天演示,因为你无法在运行时输入消息。

我也关注这个问题。希望有人能解决它。