Lilly
(Lillian )
April 4, 2024, 5:01am
3
Btw I don’t believe there is a way to bulk delete via the API. I think you need to write a script to cycle through each post to delete. Depending on how many posts, rate limits could be an issue.
Lola, how do I write a script to bulk delete Discourse posts?
Lola the Coding Assistant Bot:
To accomplish batch processing for deleting Discourse posts, you can use a scripting language like Python. Below is an example script that demonstrates how to automate the deletion of posts for a specific user. This script:
Fetches posts by a specific user.
Iterates through the list of posts.
Deletes each post individually.
Example Python Script
import requests
# Configuration
discourse_base_url = 'http://yourdiscourse.example.com'
api_key = 'your_api_key'
api_username = 'your_admin_username'
target_username = 'targetUser'
# Headers for API requests
headers = {
'Api-Key': api_key,
'Api-Username': api_username
}
def get_user_posts(username):
"""Fetch posts by a specific user."""
posts = []
url = f'{discourse_base_url}/posts.json?username={username}'
response = requests.get(url, headers=headers)
if response.status_code == 200:
posts_data = response.json()
posts = posts_data.get('latest_posts', [])
return posts
def delete_post(post_id):
"""Delete a specific post."""
url = f'{discourse_base_url}/posts/{post_id}.json'
response = requests.delete(url, headers=headers)
return response.status_code == 200
def main():
# Fetch user posts
posts = get_user_posts(target_username)
# Delete each post
for post in posts:
post_id = post.get('id')
if delete_post(post_id):
print(f'Successfully deleted post {post_id}')
else:
print(f'Failed to delete post {post_id}')
if __name__ == '__main__':
main()
Explanation
Configuration : Set your Discourse instance’s base URL, API key, API username, and the target username whose posts you want to delete.
get_user_posts Function : Fetches posts by the specified user. Adjust the URL or parameters as needed based on your Discourse setup.
delete_post Function : Deletes a post by its ID.
main Function : Orchestrates the process by first fetching the user’s posts and then deleting each one.
Important Notes
Rate Limits : Be mindful of Discourse’s API rate limits. If you’re deleting a large number of posts, consider adding delays between requests.
Permissions : Ensure your API key has the necessary permissions to delete posts.
Testing : Test the script in a safe environment before running it in production.
This script provides a basic framework. Depending on your specific needs, you might need to adjust the API endpoints, parameters, or add error handling and logging.
BTW, Why are you using API to do this?
I think it can also be done as a rake task from command line.