What is an easy way to send a message to a XMPP/Jabber conference room? Either at the command line (Shell), or by using Python? Ideally, all commands and/or libraries should be available in Debian wheezy (or jessie), without using pip.
4 Answers
I had some problems in getting python-pyxmpp to work, maybe I was just to impatient. Anyway I found another solution, that worked for me, but using sleekxmpp for their website. The solution is not better (nor worse, I hope) than goncalopps, only I got it faster to work on Debian wheezy.
$ sudo apt-get install python-sleekxmpp
and here's the code:
import optparse
import sys
import time
import sleekxmpp
class MUCBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, room, nick, message):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.room = room
self.nick = nick
self.add_event_handler("session_start", self.start)
self.message = message
def start(self, event):
self.getRoster()
self.sendPresence()
self.plugin['xep_0045'].joinMUC(self.room, self.nick, wait=True)
self.send_message(mto=self.room, mbody=self.message, mtype='groupchat')
time.sleep(10)
self.disconnect()
if __name__ == '__main__':
op = optparse.OptionParser(usage='%prog [options] your message text')
op.add_option("-j", "--jid", help="JID to use")
op.add_option("-n", "--nick", help="MUC nickname")
op.add_option("-p", "--password", help="password to use")
op.add_option("-r", "--room", help="MUC room to join")
opts, args = op.parse_args()
if None in [opts.jid, opts.nick, opts.password, opts.room] \
or len(args) < 1:
op.print_help()
sys.exit(1)
xmpp = MUCBot(opts.jid, opts.password, opts.room, opts.nick,
" ".join(args))
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0045') # Multi-User Chat
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(threaded=False)
else:
print "connect() failed"
Not sure, whether the plugin for xep_0199
is really needed.
-
Poking around, I noticed that 'jid' must include username + server (e.g. myuser@myjabber.domain.com). Does the room also require some sort of domain on it? I'm having issues getting a chat message to go through. Issue might lie elsewhere but for clarify wondering if you could add example values for your params. – bgura Jul 19 '19 at 13:27
First
apt-get install python-pyxmpp
Then, something like this
from pyxmpp.all import JID,Iq,Presence,Message,StreamError
from pyxmpp.jabber.muc import MucRoomState, MucRoomManager, MucRoomHandler
from pyxmpp.jabber.client import JabberClient
from pyxmpp.interface import implements
from pyxmpp.interfaces import *
from pyxmpp.streamtls import TLSSettings
def execute(user, password, tls_option, message_handler, idle_function, delay=1):
global client, roomManager
tls_settings= TLSSettings(require = True, verify_peer = (tls_option!='tls_no_verify'))
client= Client(JID(user), password, tls_settings)
client.connect()
EchoHandler.message= message_handler
roomManager = MucRoomManager(client.stream);
roomManager.set_handlers()
def joinMUC( handler, room_jid, nick, password= None):
global roomManager
handler.password= password
roomState = roomManager.join( room=JID(room_jid), nick=nick, handler=handler, history_maxchars=0, password= password )
return roomState
from pyxmpp.jabber.muc import MucRoomHandler
roomManager= None
execute(username, password, 'tls_no_verify', process_message_callback, periodic_callback)
state= joinMUC( room_handler, "conferencename@mydomain.tld", user, passwd)
state.send_message("something spammy!")
I cannibalized this from some old code I had laying around, and I have no means to test it right now, but it should be a good starting point. Feel free to improve it

- 21,962
- 10
- 62
- 97
-
I `apt-get install`ed `python-pyxmpp python-xmpp`, but both `import xmpp; xmpp.execute(...)` and `import pyxmpp; pyxmpp.execute(...)` raise `AttributeError: 'module' object has no attribute 'execute'`. – Jul 29 '14 at 10:33
-
My bad, I apparently had a module called `xmpp`- bad idea. I've cannibalized more code. – loopbackbee Jul 29 '14 at 11:11
You could use Gajims remote_control for that task. You get the option for OMEMO-encrpytion on top.
First activate remote_control in Gajim in preferences -> advanced -> advanced config editor. Then restart Gajim.
Now you can send a message via terminal:
gajim-remote send_groupchat_message to@xmppserver.com 'Hello'
In python you can use subprocess, for example:
from subprocess import call
call(gajim-remote send_groupchat_message to@xmppserver.com 'Hello', shell=True)

- 327
- 1
- 3
- 10
I first used python-xmpp, but the package is not available any longer on Ubuntu 20.04, likely because it only seems to work with Python 2.x.
The python-sleekxmpp alternative in @user923543's answer by now is deprecated in favor of Slixmpp, a fork which takes full advantage of Python 3 and asyncio.
In Slixmpp's documentation, there's an example application that allows sending a single XMPP message. This works well on Ubuntu 20.04 / Python 3.8, but had errors on Ubuntu 18.04 / Python 3.6 (which also isn't officially supported).
I'm reproducing it here to avoid stale links; note that even though the header says This file is part of Slixmpp., it was not part of the package that I had installed:
#!/usr/bin/env python3
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2010 Nathanael C. Fritz
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
import logging
from getpass import getpass
from argparse import ArgumentParser
import slixmpp
class SendMsgBot(slixmpp.ClientXMPP):
"""
A basic Slixmpp bot that will log in, send a message,
and then log out.
"""
def __init__(self, jid, password, recipient, message):
slixmpp.ClientXMPP.__init__(self, jid, password)
# The message we wish to send, and the JID that
# will receive it.
self.recipient = recipient
self.msg = message
# 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)
async 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()
await self.get_roster()
self.send_message(mto=self.recipient,
mbody=self.msg,
mtype='chat')
self.disconnect()
if __name__ == '__main__':
# Setup the command line arguments.
parser = ArgumentParser(description=SendMsgBot.__doc__)
# Output verbosity options.
parser.add_argument("-q", "--quiet", help="set logging to ERROR",
action="store_const", dest="loglevel",
const=logging.ERROR, default=logging.INFO)
parser.add_argument("-d", "--debug", help="set logging to DEBUG",
action="store_const", dest="loglevel",
const=logging.DEBUG, default=logging.INFO)
# JID and password options.
parser.add_argument("-j", "--jid", dest="jid",
help="JID to use")
parser.add_argument("-p", "--password", dest="password",
help="password to use")
parser.add_argument("-t", "--to", dest="to",
help="JID to send the message to")
parser.add_argument("-m", "--message", dest="message",
help="message to send")
args = parser.parse_args()
# Setup logging.
logging.basicConfig(level=args.loglevel,
format='%(levelname)-8s %(message)s')
if args.jid is None:
args.jid = input("Username: ")
if args.password is None:
args.password = getpass("Password: ")
if args.to is None:
args.to = input("Send To: ")
if args.message is None:
args.message = input("Message: ")
# Setup the EchoBot and register plugins. Note that while plugins may
# have interdependencies, the order in which you register them does
# not matter.
xmpp = SendMsgBot(args.jid, args.password, args.to, args.message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
# Connect to the XMPP server and start processing XMPP stanzas.
xmpp.connect()
xmpp.process(forever=False)

- 167,457
- 16
- 250
- 324