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.)
[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