0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Slack API の使い方

Posted at

#temperature というチャンネルが次のようになっていた時の操作です。
image.png

Token の取得

 App の作成
 Scope の追加

Token が有効かの確認

https://api.slack.com/methods/auth.test/test
https://api.slack.com/methods/conversations.list/test

次のスクリプトでも確認が出来ます。

TOKEN="xoxp-22829108884-22835664966-5533445229095-145fdab56b******"
#
URL_A=https://slack.com/api/auth.test?pretty=1
#
curl -H GET $URL_A -H 'Content-Type:application/json;charset=utf-8' -H 'Authorization: Bearer '$TOKEN
#
URL_B=https://slack.com/api/conversations.list?pretty=1
#
curl -H GET $URL_B -H 'Content-Type:application/json;charset=utf-8' -H 'Authorization: Bearer '$TOKEN

channel_id を調べる

右クリックで、「チャンネル詳細を表示する」
image.png

image.png

メッセージの一覧

list_slack.py
#! /usr/bin/python
#
#	list_slack.py
#
#					Jul/08/2023
#
import requests

def list_slack_messages(channel_id, token, limit=20):
	url = "https://slack.com/api/conversations.history"
	headers = {
		"Authorization": f"Bearer {token}",
		"Content-Type": "application/x-www-form-urlencoded"
	}
	params = {
		"channel": channel_id,
		"limit": limit
	}
	response = requests.get(url, headers=headers, params=params)
	if response.status_code == 200 and response.json().get("ok"):
		messages = response.json()["messages"]
		for message in messages:
			str_out = message["ts"] + "\t" + message["text"]
			print(str_out)
	else:
		print(response.json())
		print("メッセージの取得に失敗しました。")

# 使用例
channel_id = "C05FH3HQ***"
token = "xoxp-22829108884-22835664966-5533445229095-145fdab56b******"
list_slack_messages(channel_id, token)
#

メッセージの削除

slack_delete.py
#! /usr/bin/python
#
#	slack_delete.py
#
#					Jul/08/2023
#
import requests

def delete_slack_message(channel_id, message_ts, token):
	url = "https://slack.com/api/chat.delete"
	headers = {
		"Authorization": f"Bearer {token}",
		"Content-Type": "application/json; charset=utf-8"
	}
	data = {
		"channel": channel_id,
		"ts": message_ts
	}
	response = requests.post(url, headers=headers, json=data)
	print(response.status_code)
	print(response.json())
	if response.status_code == 200 and response.json().get("ok"):
		print("メッセージを削除しました。")
	else:
		print("メッセージの削除に失敗しました。")

# 使用例
channel_id = "C05FH3HQ***"
message_ts = "1688795734.342379"

token = "xoxp-22829108884-22835664966-5533445229095-145fdab****"

delete_slack_message(channel_id, message_ts, token)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?