How to use the Slack API using Python to delete messages that have passed a certain period of time for a specific user on a specific channel

Premise

The explanation of how to register Slack API and how to use Slack API is omitted. If you haven't done so yet, please register from the URL below. https://api.slack.com/

References

https://qiita.com/kou_pg_0131/items/56dd81f2f4716ca292ef

Purpose

Use the Slack API to remove messages from a particular channel, a particular user, that have been posted for more than 3 days.

Language to use

Python3.8.5

procedure

(1) Use the Slack API to get the message of a specific channel and get the time stamp of the message in it. (2) Use the Slack API to delete messages that are older than 3 days from the message time stamps.

Slack API to use

-Getting the time stamp of a message on a specific channel is conversations.history https://api.slack.com/methods/conversations.history -Delete the message is chat.delete https://api.slack.com/methods/chat.delete

Source code

#Import required libraries
import requests
from datetime import datetime
import re

#Get a message by specifying a channel
#Web API URL
url = "https://slack.com/api/conversations.history"
#Workspace token
token = "Workspace token"
#ID of the target channel
channel = "ID of the target channel"

#A list for storing the time stamp of each message
timestamplist = []

#Make information dictionary type
payload = {"token": token,  "channel": channel}
#Get channel information
response = requests.get(url, params=payload)
#Convert to json format
message_json = response.json()

#Store the message time stamp in the list
for m in message_json["messages"]:
    try:
        #Create a list of user list(There is duplication)
        timestamplist.append(m["ts"])
    #If there is no ts key, a KeyError will occur, so exception handling
    except KeyError:
        pass
print(timestamplist)

#Get Timestamp for Today's Date
current_ts = int(datetime.now().strftime('%s'))
#Delete a message for a specific user on a channel
for ts in timestamplist:
    #Web API URL
    url = "https://slack.com/api/chat.delete"
    #Workspace token
    token = "Workspace token"
    #ID of the target channel
    channel = "ID of the target channel"
    #3 days ago
    term = 60 * 60 * 24 * 3
    #Time stamp
    ts = ts
    #User specification
    as_user = "User ID"
    #Delete message if time stamp is more than 3 days old
    if current_ts - int(re.sub(r'\.\d+$', '', ts)) > term:
        payload = {"token": token,  "channel": channel,
                   "ts": ts, "as_user": as_user}
        response = requests.post(url, params=payload)
        json = response.json()

Supplement

as_user In the above source code, by passing the ID of a specific user to the variable as_user, I am trying to delete the message of a specific user within the target period. If no user is specified, the messages of all users within the target period will be deleted.

Variable term

In Python, you can represent a time interval by using "seconds * minutes * hours * days". For example, one week is "60 * 60 * 24 * 7" and 12 hours 30 minutes 40 seconds is "40 * 30 * 12". By changing this number, you can change the range of messages to be deleted.

re module

A standard library for processing regular expressions in Python. You can extract, replace, and divide character strings using regular expression patterns.

sub method

You can replace the matched part with another character string. The usage is as follows. sub (r'character string to be replaced','character string after replacement', target object name) In the case of re.sub (r'\. \ D + $','', ts) this time It means "in ts, if there is a half-width number from the dot to the end, it is converted to empty (synonymous with deleting)."

References

ยท Python documentation https://docs.python.org/ja/3/library/re.html -How to use Python's regular expression module re (match, search, sub, etc.) https://note.nkmk.me/python-re-match-search-findall-etc/

References

https://michimani.net/post/programming-delete-old-slack-messages/

Recommended Posts

How to use the Slack API using Python to delete messages that have passed a certain period of time for a specific user on a specific channel
Delete files that have passed a certain period of time with Raspberry PI
For the time being using FastAPI, I want to display how to use API like that on swagger
Put the process to sleep for a certain period of time (seconds) or more in Python
How to use pip, a package management system that is indispensable for using Python
[Introduction to Python] How to use the in operator in a for statement?
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
The story of creating a bot that displays active members in a specific channel of slack with python
The story of creating Botonyan that returns the contents of Google Docs in response to a specific keyword on Slack
[2015/11/19] How to register a service locally using the python SDK on naoqi os
[Python] Create a list of date and time (datetime type) for a certain period
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
How to build an environment for using multiple versions of Python on Mac
Use twitter API to get the number of tweets related to a certain keyword
How to make a Raspberry Pi that speaks the tweets of the specified user
[Introduction to Python] How to get the index of data with a for statement
[Python] Throw a message to the slack channel
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
How to unit test a function containing the current time using freezegun in python
A python script that wants to use Mac startup / end time for attendance management
[BigQuery] How to use BigQuery API for Python -Table creation-
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
How to easily draw the structure of a neural network on Google Colaboratory using "convnet-drawer"
[python] How to use the library Matplotlib for drawing graphs
How to use the __call__ method in a Python class
[Hyperledger Iroha] Notes on how to use the Python SDK
I didn't know how to use the [python] for statement
I tried to make a script that traces the tweets of a specific user on Twitter and saves the posted image at once
The story of releasing a Python text check tool on GitHub x CircleCI for the first time
[Python] I tried to make a simple program that works on the command line using argparse.
How to determine the existence of a selenium element in Python
A story that struggled to handle the Python package of PocketSphinx
How to get followers and followers from python using the Mastodon API
How to check the memory size of a variable in Python
I tried to make a regular expression of "time" using Python
How to use Python Kivy (reference) -I translated Kivy Language of API reference-
How to check the memory size of a dictionary in Python
How to build a Python environment using Virtualenv on Ubuntu 18.04 LTS
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
How to use Jupyter on the front end of supercomputer ITO
How to use machine learning for work? 01_ Understand the purpose of machine learning
How to update the python version of Cloud Shell on GCP
How to send a request to the DMM (FANZA) API with python
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A program that rotates the contents of the list to the left
How to run the practice code of the book "Creating a profitable AI with Python" on Google Colaboratory
[For beginners] I want to get the index of an element that satisfies a certain conditional expression
Use AWS lambda to scrape the news and notify LINE of updates on a regular basis [python]
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
I refactored "I tried to make a script that saves posted images at once by going back to the tweets of a specific user on Twitter".
How to use OpenPose's Python API
[Python] How to use Typetalk API
From the introduction of GoogleCloudPlatform Natural Language API to how to use it
[Python] I made a decorator that doesn't seem to have any use.
Have Alexa run Python to give you a sense of the future
[Python] Explains how to use the range function with a concrete example
[Python] A program that calculates the number of socks to be paired
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to create a wrapper that preserves the signature of the function to wrap