我已成功向个人用户发送消息。如何向房间发送消息?我正在尝试以下代码:
cl.send(xmpp.Message('99999_myroom@chat.hipchat.com', 'test message', typ='groupchat'))
另外,我发送此消息时未发送出席信息。
一些较旧的 XMPP 服务器需要初始状态通知。在你之前试试这个cl.send
:
cl.SendInitPresence(requestRoster=0)
要向房间发送消息,您必须先加入该房间。来自XEP-0045,第 7.2.2 节:
<presence to='99999_myroom@chat.hipchat.com/my_nickname'>
<x xmlns='http://jabber.org/protocol/muc'/>
</presence>
那么你的信息应该有效。
这是向聊天室发送消息的基本实现。您需要将您的状态发送到群组,并将消息类型设置为“群聊”。
用 Openfire 服务器测试
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,time,xmpp
def sendMessageToGroup(server, user, password, room, message):
jid = xmpp.protocol.JID(user)
user = jid.getNode()
client = xmpp.Client(server)
connection = client.connect(secure=False)
if not connection:
print 'connection failed'
sys.exit(1)
auth = client.auth(user, password)
if not auth:
print 'authentication failed'
sys.exit(1)
# Join a room by sending your presence to the room
client.send(xmpp.Presence(to="%s/%s" % (room, user)))
msgObj = xmpp.protocol.Message(room, message)
#Set message type to 'groupchat' for conference messages
msgObj.setType('groupchat')
client.send(msgObj)
# some older servers will not send the message if you disconnect immediately after sending
time.sleep(1)
client.disconnect()