/ Python

Using Python to Interact with the RocketChat API

In my previous post we went throught the steps on how to get Rocket Chat up and running.

Today we will go experiment Python and the RocketChat API using the rocket-python

Installing the Rocket-Python Library:

You will need python and the pip package manager installed, then running:

$ pip install rocket-python

Autenticating against RocketChat:

Now that you have rocketchat-python installed, import the library and initialize our client, so that we can authenticate against our server. You will need your servername, username and password:

>>> from rocketchat.api import RocketChatAPI
>>> api = RocketChatAPI(settings={'username': 'myuser', 'password': 'secret', 'domain': 'https://rocketchat.domain.com'})

Now if everything went according to plan, we should be able to interact with our server. Let's test it out and get your user's information that you have specified to authenticate against:

>>> api.get_my_info()
{u'status': u'away', u'username': u'myuser', u'name': u'John Smith', u'success': True, u'utcOffset': 2, u'statusConnection': u'away', u'active': True, u'_id': u'ASLkasdLSLAdae', u'emails': [{u'verified': True, u'address': u'john@domain.com'}]}

List all the Public Channels:

Listing all the public channels that is configured on our server:

>>> api.get_public_rooms()
[{'name': u'bigdata', 'id': u'hSAlkasdnasASD'}, {'name': u'datascience', 'id': u'ALalksdASLIodaw'}, {'name': u'discover', 'id': u'ASDlknasdiAWDLn'}, {'name': u'docker', 'id': u'ASdlkasdlkams'}, {'name': u'general', 'id': u'GENERAL'}, {'name': u'python', 'id': u'mLkaSAoiaDASdaks'}]

Now to get a better view of this, let's add the channels to a list, then we can use a for loop to iterate through each channel-name and channel-id:

>>> rooms = []
>>> rooms = api.get_public_rooms()

# how many rooms?
>>> len(rooms)

Now let's iterate through each one, printing the name and the id of each room/channel:

>>> for x in rooms:
...     print("Name: {}, ID: {}".format(x['name'], x['id']))
Name: bigdata, ID: hSAlkasdnasASD
Name: datascience, ID: ALalksdASLIodaw
Name: discover, ID: ASDlknasdiAWDLn
Name: docker, ID: ASdlkasdlkams
Name: general, ID: GENERAL
Name: python, ID: mLkaSAoiaDASdaks

Getting information about a Channel, requires the Room ID, for the General channel the ID will always be GENERAL:

>>> api.get_room_info('GENERAL')
{u'success': True, u'channel': {u'username': u'myuser', u'usernames': [u'rocket.cat', u'james', u'stephen', u'sysadmins.tutorials', u'abby', u'abigail'], u'name': u'general', u'msgs': 94, u'default': True, u'lm': u'2017-09-23T11:26:20.118Z', u'ts': u'2017-09-08T18:12:49.568Z', u't': u'c', u'_id': u'GENERAL', u'_updatedAt': u'2017-09-23T11:26:20.247Z'}}

For other channels, we need to do a lookup on the channel name to get the Room ID, an easy way that I found for myself, is to add the channel information to a dictionary, which can probably be done in a different ways, but the way that I did it was:

>>> rocketchat_rooms = {}
>>> for x in rooms:
...     rocketchat_rooms[x['name']] = x['id']
>>> rocketchat_rooms
{u'python': u'mLkaSAoiaDASdaks', u'bigdata': u'hSAlkasdnasASD', u'docker': u'ASdlkasdlkams', u'general': u'GENERAL', u'datascience': u'ALalksdASLIodaw', u'discover': u'ASDlknasdiAWDLn'}

Now to get information about a channel, you can simply use:

>>> api.get_room_info(rocketchat_rooms['docker'])
{u'success': True, u'channel': {u'usernames': [u'myuser', u'sysadmins.tutorials'], u'ro': False, u'name': u'docker', u'msgs': 6, u'lm': u'2017-09-16T09:07:26.211Z', u'ts': u'2017-09-08T21:46:32.432Z', u'u': {u'username': u'ruanbekker', u'_id': u'LasldkajSDLai'}, u't': u'c', u'fname': u'docker', u'customFields': {}, u'_id': u'LKSdiasSDLAISDj', u'sysMes': True, u'_updatedAt': u'2017-09-16T09:07:26.293Z'}}

List Private Channels:

Similarly, you can list private channels:

>>> api.get_private_rooms()
[{'name': u'api', 'id': u'LasiasDASDieoweiuw'}]

Getting History from a Channel's Activity:

>>> api.get_room_history('ROOM-ID')

Sending Messages:

We will send a message in the python channel, and we will also mention one of the users: rocket.cat:

>>> api.send_message('hello there @rocket.cat', rocketchat_rooms['python'])
{u'success': True, u'message': {u'parseUrls': True, u'groupable': False, u'ts': u'2017-09-23T23:44:30.658Z', u'channels': [], u'alias': u'', u'u': {u'username': u'myuser', u'_id': u'jkasdASDnasdkSd', u'name': u'John Smith'}, u'_updatedAt': u'2017-09-23T23:44:30.680Z', u'msg': u'hello there @rocket.cat', u'mentions': [{u'username': u'rocket.cat', u'_id': u'rocket.cat'}], u'rid': u'sdfskSoSdAspoM', u'_id': u'juiJsndsPIMsYhsd'}, u'ts': 1506210270731, u'channel': u'mLkaSAoiaDASdaks'}

Setup a Incoming Webhook:

We will setup a Incoming Webhook, so that we can use python and the requests and feedparser library to get data from an RSS News feed to get Sport news, and for simplistic reasons, we will only grab one article, and then post it to our news channel.

In order to setup the webhook, head over to:

  • Administration -> Integrations -> New Itegration -> Incoming Web Hook
  • Set the Name, Post to Channel, Post As, Emoji
  • Enabled -> True
  • Save

Once you saved the webhook, grab the Webhook URL as we will need it.

Install the requests and feedparser library with pip:

$ pip install requests

Create a python file, in my case news.py:

import feedparser
import requests
import json

uri = 'https://rocketchat.domain.com/hooks/sdlfkjsdflkjASdasdIiSpsPASDpwdAWpiwuSlk'
rss = feedparser.parse('http://ewn.co.za/RSS%20Feeds/Latest%20News?category=Sport')

data = {
    "username": "News24 RSS Feed",
    "icon_emoji": ":book:",
    "attachments": [
            "title": rss['entries'][0]['title'],
            "title_link": rss['entries'][0]['link'],
            "text": rss['feed']['title'],
            "image_url": "https://pbs.twimg.com/profile_images/875715923793072128/rLqRwylP.jpg",

r = requests.post(uri, json.dumps(data)).content

Now execute it:

$ python news.py

If you head over to your news channel on rocketchat, it should look like the following:

That's it for now, In a future post I will setup a Bot on RocketChat to interact with commands that it receives.