LoginSignup
21
16

More than 5 years have passed since last update.

slackメッセージの一括削除(python3)

Posted at

Slackの無料枠では10000メッセージまでしか見ることが(検索も)出来ない。
警告メッセージが来ていて困ったなーと。
リマインドなど無駄なメッセージを削除して、何とかならないかとおもったら、まさにQiitaでの投稿が。

早速下記からトークンを発行。

ここで削除対象とするチャネルのIDを確認。

https://api.slack.com/methods/channels.list/test?

早速、Qiitaのソースを実行してみるとpython3では動かないことが判明。
確かにpython2.7って書いてある。
せっかくなのでソースをpython3に書き直してみる。
下記は取得したメッセージがBotだったら削除するようにしている。

#coding: utf-8

import urllib.request
import urllib.parse
import json
import time

hist_url = "https://slack.com/api/channels.history"
delete_url = "https://slack.com/api/chat.delete"

token = 'ここにトークン'
channel = 'ここにチャネルのID'

hist_params = {
    'channel' : channel,
    'token' : token,
    'count' : '200'
}

req = urllib.request.Request(hist_url)
hist_params = urllib.parse.urlencode(hist_params).encode('ascii')
req.data = hist_params

res = urllib.request.urlopen(req)

body = res.read()
data = json.loads(body)

for m in data['messages']:
    if (m['user'] == 'USLACKBOT'):
        print(m)
        delete_params = {
            'channel' : channel,
            'token' : token,
            'ts' :  m["ts"]
        }
        req = urllib.request.Request(delete_url)
        delete_params = urllib.parse.urlencode(delete_params).encode('ascii')
        req.data = delete_params

        res = urllib.request.urlopen(req)
        body = res.read()

        print(body)

        time.sleep(2)
21
16
1

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
21
16