- rocketchat
- Подробности проекта
- Ссылки проекта
- Статистика
- Метаданные
- Сопровождающие
- Классификаторы
- История выпусков Уведомления о выпусках | Лента RSS
- Загрузка файлов
- Source Distribution
- Built Distribution
- Хеши для rocketchat-1.0.0.tar.gz
- Хеши для rocketchat-1.0.0-py3-none-any.whl
- Помощь
- О PyPI
- Внесение вклада в PyPI
- Использование PyPI
- Saved searches
- Use saved searches to filter your results more quickly
- License
- jadolg/rocketchat_API
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Saved searches
- Use saved searches to filter your results more quickly
- License
- Pipoline/rocket-python
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Using Python to Interact with the RocketChat API
- Comments
- Subscribe to Sysadmins
rocketchat
Python API wrapper for the rocket.chat REST API. Attempts to follow the REST api names and syntax as closely as possible.
Подробности проекта
Ссылки проекта
Статистика
Метаданные
Лицензия: MIT License
Метки rocketchat, chat, api
Требует: Python >=3.6
Сопровождающие
Классификаторы
История выпусков Уведомления о выпусках | Лента RSS
Загрузка файлов
Загрузите файл для вашей платформы. Если вы не уверены, какой выбрать, узнайте больше об установке пакетов.
Source Distribution
Uploaded 17 янв. 2020 г. source
Built Distribution
Uploaded 17 янв. 2020 г. py3
Хеши для rocketchat-1.0.0.tar.gz
Алгоритм | Хеш-дайджест | |
---|---|---|
SHA256 | 9302e0d1f0a473c0e58841660901ba25d8610554ed19b84393f2ceade4376d42 | Копировать |
MD5 | fe9df3409a4bef68973f827e81d9831f | Копировать |
BLAKE2b-256 | 157bf5d53de7965b6784b8bd101ebfa4c7ac5eb61ad1d0bb04c6b21c2a322f07 | Копировать |
Хеши для rocketchat-1.0.0-py3-none-any.whl
Алгоритм | Хеш-дайджест | |
---|---|---|
SHA256 | 9f813de1ffcd84b1990063dcc48572fc56c2637a615c8e57bf2f4c991ee50500 | Копировать |
MD5 | 14889693b6c95f25897e03f5d8c2ba99 | Копировать |
BLAKE2b-256 | 744abe7d2dc77e3eb4f768f88024a96231b1d989133e49fb86883221d89ad6a2 | Копировать |
Помощь
О PyPI
Внесение вклада в PyPI
Использование PyPI
Разработано и поддерживается сообществом Python’а для сообщества Python’а.
Пожертвуйте сегодня!
PyPI», «Python Package Index» и логотипы блоков являются зарегистрированными товарными знаками Python Software Foundation.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Python API wrapper for Rocket.Chat
License
jadolg/rocketchat_API
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
…compose-action-1.5.0 Bump isbang/compose-action from 1.4.1 to 1.5.0
Git stats
Files
Failed to load latest commit information.
README.md
- From pypi: pip3 install rocketchat_API
- From GitHub: Clone our repository and python3 setup.py install
from pprint import pprint from rocketchat_API.rocketchat import RocketChat proxy_dict = < "http" : "http://127.0.0.1:3128", "https" : "https://127.0.0.1:3128", > rocket = RocketChat('user', 'pass', server_url='https://demo.rocket.chat', proxies=proxy_dict) pprint(rocket.me().json()) pprint(rocket.channels_list().json()) pprint(rocket.chat_post_message('good news everyone!', channel='GENERAL', alias='Farnsworth').json()) pprint(rocket.channels_history('GENERAL', count=5).json())
note: every method returns a requests Response object.
If you are going to make a couple of request, you can user connection pooling provided by requests . This will save significant time by avoiding re-negotiation of TLS (SSL) with the chat server on each call.
from requests import sessions from pprint import pprint from rocketchat_API.rocketchat import RocketChat with sessions.Session() as session: rocket = RocketChat('user', 'pass', server_url='https://demo.rocket.chat', session=session) pprint(rocket.me().json()) pprint(rocket.channels_list().json()) pprint(rocket.chat_post_message('good news everyone!', channel='GENERAL', alias='Farnsworth').json()) pprint(rocket.channels_history('GENERAL', count=5).json())
Using a token for authentication instead of user and password
from pprint import pprint from rocketchat_API.rocketchat import RocketChat rocket = RocketChat(user_id='WPXGmQ64S3BXdCRb6', auth_token='jvNyOYw2f0YKwtiFS06Fk21HBRBBuV7zI43HmkNzI_s', server_url='https://demo.rocket.chat') pprint(rocket.me().json())
Only required parameters are explicit on the RocketChat class but you can still use all other parameters. For a detailed parameters list check the Rocket chat API
Most of the API methods are already implemented. If you are interested in a specific call just open an issue or open a pull request.
Tests run on a Rocket.Chat Docker container so install Docker and docker-compose.
- To start test server do docker-compose up and to take test server down docker-compose down
- To run the tests run pytest
You can contribute by doing Pull Requests. (It may take a while to merge your code but if it’s good it will be merged). Please, try to implement tests for all your code and use a PEP8 compliant code style.
Reporting bugs and asking for features is also contributing 😉 Feel free to help us grow by registering issues.
We hang out here if you want to talk.
JetBrains supports this project by providing us with licenses for their fantastic products.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
RocketChat API Implemented in Python
License
Pipoline/rocket-python
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Python API wrapper for the Rocket chat API
Initialize the client with a username and password or token and user_id. This user must have Admin privs:
from rocketchat.api import RocketChatAPI api = RocketChatAPI(settings=) # or api = RocketChatAPI(settings=)
api.send_message('message', 'room_id') api.get_private_rooms() api.get_private_room_history('room_id', oldest=date) api.get_public_rooms() api.get_room_info('room_id') api.get_private_room_info('room_id') api.get_room_history('room_id') api.create_public_room('room_name', members=[], read_only=False) api.delete_public_room('room_id') api.get_my_info() api.get_users() api.get_user_info('user_id') api.create_user('email', 'name', 'password', 'username', active=True, roles=['user'], join_default_channels=True, require_password_change=False, send_welcome_email=False, verified=False, customFields=None) api.delete_user('user_id') api.upload_file(room_id='room_id', file='file', description='File description', message='Example message')
check /rocketchat/calls/api.py for more.
You’ll first need to get the _id of the room you want to send a message to. Currently, Rocket can only send messages to public rooms.
api.send_message('Your message', room_id)
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:
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=)
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:
List all the Public Channels:
Listing all the public channels that is configured on our server:
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) 6
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 :
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
Now to get information about a channel, you can simply use:
>>> api.get_room_info(rocketchat_rooms['docker']) , 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:
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'_updatedAt': u'2017-09-23T23:44:30.680Z', u'msg': u'hello there @rocket.cat', u'mentions': [], 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:
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=<> 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", "color":"#764FA5" >] > r = requests.post(uri, json.dumps(data)).content
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.
Comments
Subscribe to Sysadmins
Subscribe today and get access to a private newsletter and new content every week!