タイトルそのままだけれど、slackで「一部のチャンネルから」「一定日数経った」メッセージを自動的にごりごり消したいと思った結果書いたものです。
ブラウザで手動で気が向いた時に叩いてもいいし、cronに叩かせてもいい。
手順:
- Slack Web APIのページでtest tokenを作ってくる
- channels.list のTesterタブでチャンネルの名前とIDの対応を確認
- 下記phpファイルを適当な名前で保存
- configって書いたあたりを任意に編集する
- phpファイルを適当に叩けるところに置く
- ファイル名.php?id=チャンネル名でチャンネルを絞って叩けるし、指定しなければ設定を書いたチャンネル全部に対して削除が働く
- 満足するまで叩く
<?php
// ブラウザで叩く時に?id=チャンネル名で処理対象のチャンネルを選べる
// していなかったら設定書いたチャンネル全部をforeachする
if( isset($_GET['id']) ){
$id = $_GET['id'];
$id = htmlspecialchars( $id );
}else{ // なにもなかったら
$id = "all";
}
// configs
$token="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // web apiで出したやつ
$channels=array( // チャンネルid, 置いておきたい日数
"channel-name" => array("channel-id",7)
,"channel-name" => array("channel-id",30)
);
$msgcount = 100; // between 1-1000
// current vars for id
if($id == "all"){ // 全チャンネル処理
foreach($channels as $name => $details){
$channel = $details[0];
$days = $details[1];
$latest = time()-( ($days+1) * 24 * 60 * 60); // unix timestamp
// history
// チャンネル履歴を取得して配列に入れ直す
// see: https://api.slack.com/methods/channels.history
$history['json'] = shell_exec('curl -XPOST "https://slack.com/api/channels.history?token='.$token.'&channel='.$channel.'&latest='.$latest.'&count='.$msgcount.'"');
$history['temp'] = json_decode($history['json'],true);
$history['msg'] = $history['temp']['messages'];
if(empty($history['msg'])){
// No messages to delete
}else{
foreach($history['msg'] as $no => $msg){
$history['ts'][] = $msg['ts'];
}
// delete
// チャンネル履歴を取得して配列に入れ直す
// see: https://api.slack.com/methods/chat.delete
foreach($history['ts'] as $timestamp){
shell_exec('curl -XPOST "https://slack.com/api/chat.delete?token='.$token.'&channel='.$channel.'&ts='.$timestamp.'"');
}
}
// unset stuff
unset($channel);
unset($days);
unset($latest);
unset($history);
}
}else{ // idごとにやりたい場合
$channel = $channels[$id][0];
$days = $channels[$id][1];
$latest = time()-( ($days+1) * 24 * 60 * 60); // unix timestamp
// history
$history = shell_exec('curl -XPOST "https://slack.com/api/channels.history?token='.$token.'&channel='.$channel.'&latest='.$latest.'&count='.$msgcount.'"');
$history_temp = json_decode($history,true);
$histories = $history_temp['messages'];
foreach($histories as $no => $msg){
$histories_ts[] = $msg['ts'];
}
// delete
foreach($histories_ts as $timestamp){
shell_exec('curl -XPOST "https://slack.com/api/chat.delete?token='.$token.'&channel='.$channel.'&ts='.$timestamp.'"');
}
}
?>
世の中には多分もっとスマートなのが色々あると思いますが、
十七夜屋