向 XMPP/Jabber 会议室发送消息的简单方法是什么?是在命令行(Shell)还是使用 Python?理想情况下,所有命令和/或库都应该在 Debian wheezy(或 jessie)中可用,而不使用 pip。
4 回答
我在让 python-pyxmpp 工作时遇到了一些问题,也许我只是不耐烦。无论如何,我找到了另一个对我有用的解决方案,但在他们的网站上使用了 slimxmpp。该解决方案并不比 goncalopps 好(我希望也不差),只是我在 Debian wheezy 上工作得更快。
$ sudo apt-get install python-sleekxmpp
这是代码:
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"
不确定,是否xep_0199
真的需要插件。
第一的
apt-get install python-pyxmpp
然后,像这样
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!")
我从我放置的一些旧代码中蚕食了它,我现在没有办法测试它,但它应该是一个很好的起点。随意改进它
您可以使用Gajims remote_control来完成该任务。您可以在顶部获得 OMEMO-encrpytion 选项。
首先在偏好设置 -> 高级 -> 高级配置编辑器中激活Gajim 中的remote_control。然后重新启动 Gajim。
现在您可以通过终端发送消息:
gajim-remote send_groupchat_message to@xmppserver.com 'Hello'
在 python 中,您可以使用subprocess,例如:
from subprocess import call
call(gajim-remote send_groupchat_message to@xmppserver.com 'Hello', shell=True)
我第一次使用python-xmpp,但该软件包在 Ubuntu 20.04 上不再可用,可能是因为它似乎只适用于 Python 2.x。
到目前为止,@user923543 的答案中的python-sleekxmpp替代方案已被弃用,取而代之的是 Slixmpp,这是一个充分利用 Python 3 和 asyncio 的分支。
在Slixmpp的文档中,有一个示例应用程序允许发送单个 XMPP 消息。这在 Ubuntu 20.04 / Python 3.8 上运行良好,但在 Ubuntu 18.04 / Python 3.6(也不受官方支持)上出现错误。
我在这里复制它以避免陈旧的链接;请注意,即使标题显示此文件是 Slixmpp 的一部分。,它不是我安装的软件包的一部分:
#!/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)