向 XMPP/Jabber 会议室发送消息的简单方法? (Shell 或 Python,Debian wheezy)
Posted
技术标签:
【中文标题】向 XMPP/Jabber 会议室发送消息的简单方法? (Shell 或 Python,Debian wheezy)【英文标题】:Easy way to send a message to an XMPP/Jabber conference room? (Shell or Python, Debian wheezy) 【发布时间】:2014-09-20 15:38:15 【问题描述】:向 XMPP/Jabber 会议室发送消息的简单方法是什么?是在命令行(Shell)还是使用 Python?理想情况下,所有命令和/或库都应该在 Debian wheezy(或 jessie)中可用,而不使用 pip。
【问题讨论】:
【参考方案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!")
我从我放置的一些旧代码中蚕食了它,我现在没有办法测试它,但它应该是一个很好的起点。随时改进它
【讨论】:
我apt-get install
ed python-pyxmpp python-xmpp
,但import xmpp; xmpp.execute(...)
和import pyxmpp; pyxmpp.execute(...)
都提高了AttributeError: 'module' object has no attribute 'execute'
。
我的错,我显然有一个名为 xmpp
的模块 - 坏主意。我已经蚕食了更多的代码。【参考方案2】:
我在让 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
的插件是否真的需要。
【讨论】:
四处寻找,我注意到“jid”必须包含用户名 + 服务器(例如 myuser@myjabber.domain.com)。房间是否也需要某种域?我在获取聊天消息时遇到问题。问题可能出在其他地方,但为了澄清是否可以为参数添加示例值。【参考方案3】:您可以使用 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)
【讨论】:
【参考方案4】:我第一次使用 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)
【讨论】:
以上是关于向 XMPP/Jabber 会议室发送消息的简单方法? (Shell 或 Python,Debian wheezy)的主要内容,如果未能解决你的问题,请参考以下文章
如何将 custon xmpp/jabber 请求发送到服务器
agsXMPP,创建 muc 房间“只允许占用者向会议发送消息”