asyncio-based Python wrapper for the Rocket.Chat Realtime API.
Supported Rocket.Chat versions: 6.x. (The library might also work or partially work with other versions.)
Use this library if you:
- want to integrate with Rocket.Chat from Python
- are using asyncio to drive your code
- want to use Rocket.Chat's efficient websockets-based Realtime API
pip install rocketchat-async
importasyncioimportrandomfromrocketchat_asyncimportRocketChatdefhandle_message(channel_id, sender_id, msg_id, thread_id, msg, qualifier, unread, repeated): """Simply print the message that arrived."""print(msg) asyncdefmain(address, username, password): whileTrue: try: rc=RocketChat() awaitrc.start(address, username, password) # Alternatively, use rc.resume for token-based authentication:# await rc.resume(address, username, token)# A possible workflow consists of two steps:## 1. Set up the desired callbacks...forchannel_id, channel_typeinawaitrc.get_channels(): awaitrc.subscribe_to_channel_messages(channel_id, handle_message) # 2. ...and then simply wait for the registered events.awaitrc.run_forever() except (RocketChat.ConnectionClosed, RocketChat.ConnectCallFailed) ase: print(f'Connection failed: {e}. Waiting a few seconds...') awaitasyncio.sleep(random.uniform(4, 8)) print('Reconnecting...') # Side note: Don't forget to use the wss:// scheme when TLS is used.asyncio.run(main('ws://localhost:3000/websocket', 'username', 'password'))Brief overview of the currently implemented methods.
As of now, Rocket.Chat's API is only covered partially (based on my original needs). I am open to both feature requests as well as pull requests.
Get a list of channels the logged-in user is currently member of.
Send a text message to a channel.
Send a reaction to a specific message.
Send the "typing" event to a channel or to a specified thread within that channel.
Subscribe to all messages in the given channel. Returns the subscription ID.
The provided callback should accept eight arguments: channel_id, sender_id, msg_id, thread_id, msg_text, msg_qualifier and repeated. The qualifier can help to determine if e.g. the message is a system message about the user being removed from the channel. The repeated flag assists in distinguishing whether the message has been received again as a result of thread replies, or if it is a new message post.
Subscribe to all changes in channels. Returns the subscription ID.
The provided callback should accept two arguments: channel_id and channel_qualifier. The qualifier helps to determine e.g. if it's a direct message or a normal room.
Cancel a subscription.