Skip to content

Instantly share code, notes, and snippets.

@rednafi
Created May 11, 2025 12:14
Show Gist options
  • Save rednafi/e1e84b5c2b2673c6e0b8b7dddbe0046d to your computer and use it in GitHub Desktop.
Save rednafi/e1e84b5c2b2673c6e0b8b7dddbe0046d to your computer and use it in GitHub Desktop.
Delete comments from all subreddits except one
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
const (
clientID = ""
clientSecret = ""
username = ""
password = ""
userAgent = ""
excludedSubreddit = "" // Subreddit to exclude (without "r/")
)
type TokenResponse struct {
AccessToken string `json:"access_token"`
}
type Comment struct {
ID string `json:"id"`
SubredditName string `json:"subreddit"`
Permalink string `json:"permalink"`
}
type Listing struct {
Data struct {
Children []struct {
Data Comment `json:"data"`
} `json:"children"`
After string `json:"after"`
} `json:"data"`
}
func main() {
client := resty.New()
client.SetHeader("User-Agent", userAgent)
// Step 1: Obtain access token
tokenResp := TokenResponse{}
resp, err := client.R().
SetBasicAuth(clientID, clientSecret).
SetFormData(map[string]string{
"grant_type": "password",
"username": username,
"password": password,
}).
SetHeader("Content-Type", "application/x-www-form-urlencoded").
SetResult(&tokenResp).
Post("https://www.reddit.com/api/v1/access_token")
if err != nil || resp.StatusCode() != http.StatusOK {
log.Fatalf("Failed to get access token: %v", err)
}
client.SetAuthToken(tokenResp.AccessToken)
// Step 2: Fetch and delete comments
after := ""
deletedCount := 0
for {
url := fmt.Sprintf("https://oauth.reddit.com/user/%s/comments?limit=100&after=%s", username, after)
resp, err := client.R().Get(url)
if err != nil {
log.Fatalf("Failed to fetch comments: %v", err)
}
var listing Listing
if err := json.Unmarshal(resp.Body(), &listing); err != nil {
log.Fatalf("Failed to parse response: %v", err)
}
if len(listing.Data.Children) == 0 {
break
}
for _, child := range listing.Data.Children {
comment := child.Data
if strings.EqualFold(comment.SubredditName, excludedSubreddit) {
continue
}
// Delete comment
delURL := fmt.Sprintf("https://oauth.reddit.com/api/del?id=t1_%s", comment.ID)
_, err := client.R().
SetHeader("Content-Type", "application/x-www-form-urlencoded").
Post(delURL)
if err != nil {
log.Printf("Failed to delete comment %s: %v", comment.ID, err)
} else {
fmt.Printf("Deleted comment in r/%s: %s\n", comment.SubredditName, comment.Permalink)
deletedCount++
}
time.Sleep(2 * time.Second) // Respect API rate limits
}
if listing.Data.After == "" {
break
}
after = listing.Data.After
}
fmt.Printf("✅ Completed. Deleted %d comments (excluding r/%s).\n", deletedCount, excludedSubreddit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment