wasimbhalli
wasimbhalli

Reputation: 5242

How to send message to a chatroom using xmpppy?

I've successfully sent message to individual user. How can I send message to a room? I'm trying the following code:

cl.send(xmpp.Message('[email protected]', 'test message', typ='groupchat'))

Also, I'm sending this message without sending presence.

Upvotes: 2

Views: 3408

Answers (3)

Denis.Kipchakbaev
Denis.Kipchakbaev

Reputation: 1070

Here is the basic implementation for sending a message to a room chat. You need to send your presence to the group, and also set the message type to 'groupchat'.

Tested with Openfire server

#!/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()

Upvotes: 2

Joe Hildebrand
Joe Hildebrand

Reputation: 10414

To send a message to a room, you must join the room first. From XEP-0045, section 7.2.2:

<presence to='[email protected]/my_nickname'>
  <x xmlns='http://jabber.org/protocol/muc'/>
</presence>

Then your message should work.

Upvotes: 0

Ilmo Euro
Ilmo Euro

Reputation: 5105

Some older XMPP servers require an initial presence notification. Try this before your cl.send:

cl.SendInitPresence(requestRoster=0)

See also http://xmpppy.sourceforge.net/examples/xsend.py

Upvotes: 0

Related Questions