user2607418
user2607418

Reputation: 41

SleekXMPP send a message at will and still listen for incoming messages.

I am trying to modify the sleekxmpp echobot example to act more like a client. I am able to receive and print messages with the code below but how do I make the code also allow me to send messages to another JID at will and not as an auto response to a message received. I am relatively new to python so any help will be very useful THANK YOU.

#!/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 = "[email protected]"

    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.")

Upvotes: 4

Views: 7619

Answers (2)

hackrole
hackrole

Reputation: 121

I have figure out this problem. this problem can use xmlstream._start_thread to fix. but it still a litte ugly.

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")

Upvotes: 4

hannes
hannes

Reputation: 964

The answer to your question is given in the "sign in, send, logout" tutorial. The main changes to the standard EchoBot code you posted are that you

  • do not register a method for incoming messages and
  • call send_message in the start function:

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

obviously, you're not limited to the start function; you can call this function at any point in your program when you want to send a message.

Upvotes: 2

Related Questions