将消息发送到XMPP / Jabber会议室的简单方法是什么?在命令行(Shell),还是使用Python?理想情况下,所有命令和/或库都应该在Debian wheezy(或jessie)中使用,而不使用pip。
答案 0 :(得分:2)
我在让python-pyxmpp工作时遇到了一些问题,也许我只是不耐烦。无论如何,我找到了另一个解决方案,对我有用,但使用sleekxmpp为他们的网站。解决方案并不比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
的插件。
答案 1 :(得分:1)
第一
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!")
我从一些旧的代码中蚕食了这个,我现在没办法测试它,但它应该是一个很好的起点。随意改进它
答案 2 :(得分:0)
您可以将 Gajims remote_control 用于该任务。您可以在顶部获得OMEMO加密选项。
首先在偏好设置->高级->高级配置编辑器中激活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)
答案 3 :(得分:0)
我第一次使用 python-xmpp,但该软件包在 Ubuntu 20.04 上不再可用,可能是因为它似乎只适用于 Python 2.x。
@user923543 的答案中的 python-sleekxmpp 替代方案是 deprecated in favor of Slixmpp, a fork which takes full advantage of Python 3 and asyncio。
在 Slixmpp 的文档中,an example application 允许发送单个 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)