Simple Slack API client made with Python

I think the Official Python Client for Slack API is well done, but for some reason I need to use the Slack API from Python without using it. I wrote my own Slack client in a super-simple way.

import urllib.request
import json

class SlackAPI:
    
    def __init__(self, token: str, api_base: str = 'https://slack.com/api/'):
        self.token = token
        self.api_base = api_base
    
    def __call__(self, name: str, charset: str = 'utf-8', **kwargs) -> dict:
        req = urllib.request.Request(
            url = self.api_base + name,
            data = json.dumps(kwargs).encode(charset),
            headers = {
                'Authorization': f'Bearer {self.token}',
                'Content-Type': f'application/json; charset={charset}',
            })
        with urllib.request.urlopen(req) as res:
            return json.load(res)
    
    def __getitem__(self, key: str):
        return lambda **kwargs: self(key, **kwargs)

You can use it like this.

token = 'xoxb-000000000000-0000000000000-xxxxxxxxxxxxxxxxxxxxxxxx'
slack_api = SlackAPI(token)
#Get user list
slack_api['users.list']()
#Post a message
slack_api['chat.postMessage'](channel='XXXXXXXXX',text='Yo!',as_user=True)

Of course, you can't use the RTM API, but if it's a Web API, you can probably do it with this. (I haven't tried so many things, so please comment if you can't run this API.)

Postscript (2020.05.18)

[Comment](# comment-a97ebf6ddf92cfa5447a) pointed out that some APIs do not support the JSON request body, so I tried to support it.

import urllib.request
import json

class SlackAPI:

    def __init__(self, token: str, api_base: str = 'https://slack.com/api/'):
        self.token = token
        self.api_base = api_base

    def __getitem__(self, key: str):
        return lambda **kwargs: self.post(key, **kwargs)

    def get(self, name: str, **kwargs) -> dict:
        req = urllib.request.Request(
            url = self.api_base + name + '?' + urllib.parse.urlencode(kwargs),
            headers = {
                'Authorization': f'Bearer {self.token}',
            })
        with urllib.request.urlopen(req) as res:
            return json.load(res)

    def post(self, name: str, charset: str = 'utf-8', **kwargs) -> dict:
        req = urllib.request.Request(
            url = self.api_base + name,
            data = json.dumps(kwargs).encode(charset),
            headers = {
                'Authorization': f'Bearer {self.token}',
                'Content-Type': f'application/json; charset={charset}',
            })
        with urllib.request.urlopen(req) as res:
            return json.load(res)

If you explicitly use the get method, send the data with ʻapplication / x-www-form-urlencoded`.

slack_api.get('conversations.list', limit=20)

Recommended Posts

Simple Slack API client made with Python
Serverless face recognition API made with Python
I made a simple blackjack with Python
[Python] Mention to multiple people with Slack API
Use Trello API with python
Use Twitter API with Python
I made blackjack with python!
Post to slack with Python 3
Web API with Python + Falcon
Crawling with Python and Twitter API 1-Simple search function
Play RocketChat with API / Python
Call the API with python3.
Use subsonic API with python3
I made blackjack with Python.
Simple IRC client in python
Othello made with python (GUI-like)
I made wordcloud with Python.
[Vagrant] Set up a simple API server with python
I tried hitting the API with echonest's python client
Twitter posting client made with Flask with simple login function
I made a simple typing game with tkinter in Python
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
I made a simple book application with python + Flask ~ Introduction ~
Get data from analytics API with Google API Client for python
Play with YouTube Data API v3 using Google API Python Client
SNS Python basics made with Flask
Create Awaitable with Python / C API
Run Rotrics DexArm with python API
Numer0n with items made in Python
Quine Post with Qiita API (Python)
I made a fortune with Python.
Hit the Etherpad-lite API with Python
Othello game development made with Python
[python] Read information with Redmine API
Automate simple tasks with Python Part0
Twitter search client made with bottle
I made a daemon with Python
I made a simple circuit with Python (AND, OR, NOR, etc.)
A story about adding a REST API to a daemon made with Python
[Python] I made an image viewer with a simple sorting function.
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
Collecting information from Twitter with Python (Twitter API)
Your own Twitter client made with Django
A simple RSS reader made with Django
Retrieving food data with Amazon API (Python)
HTTP split download guy made with Python
Automate simple tasks with Python Part1 Scraping
I made a character counter with Python
Machine learning with python (2) Simple regression analysis
Use Amazon Simple Notification Service with Python
Write a TCP client with Python Twisted
[Python] Quickly create an API with Flask
I made a Hex map with Python
"First Elasticsearch" starting with a python client
[Python] Get Python package information with PyPI API
I made a roguelike game with Python
I made a configuration file with Python
I made a neuron simulator with Python
Othello app (iOS app) made with Python (Kivy)
REST API of model made with Python with Watson Machine Learning (CP4D edition)
[Python] Python and security-â‘¡ Port scanning tool made with Python