Created
December 10, 2023 04:14
-
-
Save WillNilges/fe515b1b817b0d6f10538bd0c262acda to your computer and use it in GitHub Desktop.
Python script to delete a range of messages from a slack bot, using its token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from botocore import os | |
from dotenv import load_dotenv | |
import slack_sdk | |
from slack_sdk.errors import SlackApiError | |
def delete_messages(token, channel_id, start_ts, end_ts, inclusive=False): | |
client = slack_sdk.WebClient(token=token) | |
try: | |
response = client.conversations_history( | |
channel=channel_id, oldest=start_ts, latest=end_ts, inclusive=inclusive | |
) | |
messages = response.data["messages"] | |
for message in messages: | |
ts = message["ts"] | |
try: | |
client.chat_delete(channel=channel_id, ts=ts) | |
print(f"Deleted message at timestamp {ts}") | |
except SlackApiError as e: | |
print( | |
f"Error deleting message at timestamp {ts}: {e.response['error']}" | |
) | |
except SlackApiError as e: | |
print(f"Error retrieving conversation history: {e.response['error']}") | |
def main(): | |
load_dotenv() | |
token = os.getenv("SLACK_TOKEN") | |
parser = argparse.ArgumentParser( | |
description="Delete a range of messages using a bot's API token." | |
) | |
parser.add_argument( | |
"--channel-id", required=True, help="Channel the messages are in" | |
) | |
parser.add_argument("--start-ts", required=True, help="End TS") | |
parser.add_argument("--end-ts", required=True, help="End TS") | |
parser.add_argument( | |
"--inclusive", | |
action="store_true", | |
default=False, | |
help="Include start and end TS messages", | |
) | |
args = parser.parse_args() | |
delete_messages(token, args.channel_id, args.start_ts, args.end_ts, args.inclusive) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment