Skip to content

Instantly share code, notes, and snippets.

@konifar
Created January 13, 2023 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konifar/4a62846832fb4d3f1192f0e9a336a753 to your computer and use it in GitHub Desktop.
Save konifar/4a62846832fb4d3f1192f0e9a336a753 to your computer and use it in GitHub Desktop.
Slackのchatチャネル一覧を取得してメッセージを生成
import json
import urllib.request
import urllib.parse
import urllib.error
def load_all_public_channels(token):
"""全チャネルの情報を取得する
:param token: (str) SlackのAPI Token
:return: (str) レスポンスのjsonオブジェクト
"""
# curlコマンド例
# curl 'https://api.slack.com/methods/conversations.list?token={token}&exclude_archived=true&types=public_channel&limit=999'
url = 'https://slack.com/api/conversations.list'
channels = []
next_cursor = ''
while True:
params = {
'token': token,
'exclude_archived': 'true',
'types': 'public_channel',
'limit': 999,
}
if next_cursor != '':
params['cursor'] = next_cursor
req = urllib.request.Request('{}?{}'.format(url, urllib.parse.urlencode(params)))
try:
with urllib.request.urlopen(req) as res:
body = res.read()
body_json = json.loads(body.decode('utf-8'))
channels.extend(body_json['channels'])
next_cursor = body_json['response_metadata']['next_cursor']
except urllib.error.HTTPError as err:
print('[Error occurred] code:' + str(err.code) + ', reason: ' + err.reason)
except urllib.error.URLError as err:
print('[Error occurred] reason:' + err.reason)
if next_cursor == '':
break
return channels
def create_chat_channels_list(all_channels_json):
"""chat-チャネルのみのチャンネルID、チャネル名、Purposeの一覧を返す
:param token: (str) 全チャネル一覧のjson
:return: (array) チャネルID、チャネル名、Purposeのmapのarray
"""
chat_channels = []
for c in all_channels_json:
if c['name'].startswith('chat-'):
chat_channels.append({'id': c['id'], 'name': c['name'], 'purpose': c['purpose']['value']})
return sorted(chat_channels, key=lambda x: x['name'])
# Zapierから渡されるパラメータの取得
token = input_data['token']
# 全チャネルの取得
channels_json = load_all_public_channels(token)
# chat-チャネルのみのチャンネルID、チャネル名、Purposeの一覧にする
chat_channels = create_chat_channels_list(channels_json)
print(chat_channels)
# Slackに投稿するメッセージの作成
message = ''
for c in chat_channels:
message += '\n#' + c['name'] + ' : ' + c['purpose']
print('\nメッセージ出力:')
print(message)
# Zapierの返り値にセット
output = {
'message': message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment