Advertisement
Guest User

See all subreddit interactions based on users

a guest
Oct 24th, 2024
1,296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import snoowrap from 'snoowrap';
  2. import fs from 'fs';
  3.  
  4. // Create CSV header
  5. let csvRows = [];
  6. let submissionCount = 0;
  7. csvRows.push(['Subreddit', 'Interaction Count'].join(','));
  8.  
  9. const r = new snoowrap({
  10.     userAgent: 'Node.js script for subreddit analysis',
  11.     clientId: 'YOUR_CLIENT_ID',
  12.     clientSecret: 'YOUR_CLIENT_SECRET',
  13.     username: 'REDDIT_USERNAME',
  14.     password: 'REDDIT_PASSWORD'
  15. });
  16.  
  17. async function main() {
  18.     const subredditName = process.argv[2];
  19.     if (!subredditName) {
  20.         console.error('Please provide a subreddit name as an argument.');
  21.         process.exit(1);
  22.     }
  23.  
  24.     try {
  25.         // Fetch the last 50 submissions from the subreddit
  26.         const subreddit = r.getSubreddit(subredditName);
  27.         const submissions = await subreddit.getNew({ limit: 50 });
  28.  
  29.         // Object to store subreddit interaction counts
  30.         const subredditCounts = {};
  31.  
  32.         // Set to keep track of processed users to avoid duplicates
  33.         const processedUsers = new Set();
  34.  
  35.         for (const submission of submissions) {
  36.             submissionCount = submissionCount + 1;
  37.             console.log(`Processing submission ${submissionCount}: ${submission.title}`);
  38.             // Process the submission author (OP)
  39.             if (submission.author && submission.author.name !== '[deleted]') {
  40.                 const authorName = submission.author.name;
  41.                 if (!processedUsers.has(authorName)) {
  42.                     processedUsers.add(authorName);
  43.                     await processUser(authorName, subredditCounts);
  44.                 }
  45.             }
  46.  
  47.             // Fetch comments for the submission
  48.             let comments;
  49.             try {
  50.                 comments = await submission.expandReplies({ limit: Infinity, depth: Infinity });
  51.             } catch (err) {
  52.                 console.error(`Error fetching comments for submission ${submission.id}:`, err.message);
  53.                 continue;
  54.             }
  55.  
  56.             // Process commenters
  57.             if (comments && comments.comments) {
  58.                 for (const comment of comments.comments) {
  59.                     if (comment.author && comment.author.name !== '[deleted]') {
  60.                         const commenterName = comment.author.name;
  61.                         if (!processedUsers.has(commenterName)) {
  62.                             processedUsers.add(commenterName);
  63.                             await processUser(commenterName, subredditCounts);
  64.                         }
  65.                     }
  66.                 }
  67.             }
  68.         }
  69.  
  70.         // Convert subredditCounts to CSV rows
  71.         for (const [subreddit, count] of Object.entries(subredditCounts)) {
  72.             csvRows.push([subreddit, count].join(','));
  73.         }
  74.  
  75.         // Save the CSV file after processing
  76.         saveCSV(`${subredditName}_interactions.csv`, csvRows);
  77.     } catch (error) {
  78.         console.error('An error occurred:', error.message);
  79.     }
  80. }
  81.  
  82. // Function to process a user and update subredditCounts
  83. async function processUser(username, subredditCounts) {
  84.     const user = r.getUser(username);
  85.  
  86.     try {
  87.         // Fetch the user's recent comments and submissions
  88.         const [comments, userSubmissions] = await Promise.all([
  89.             user.getComments({ limit: Infinity }),
  90.             user.getSubmissions({ limit: Infinity })
  91.         ]);
  92.  
  93.         // Count the subreddits from comments
  94.         comments.forEach((comment) => {
  95.             const subreddit = comment.subreddit.display_name;
  96.             subredditCounts[subreddit] = (subredditCounts[subreddit] || 0) + 1;
  97.         });
  98.  
  99.         // Count the subreddits from submissions
  100.         userSubmissions.forEach((submission) => {
  101.             const subreddit = submission.subreddit.display_name;
  102.             subredditCounts[subreddit] = (subredditCounts[subreddit] || 0) + 1;
  103.         });
  104.     } catch (userError) {
  105.         console.error(`Error fetching data for user ${username}:`, userError.message);
  106.     }
  107. }
  108.  
  109. // Function to save CSV to file
  110. function saveCSV(filename, rows) {
  111.     const csvContent = rows.join('\n');
  112.     fs.writeFileSync(filename, csvContent);
  113. }
  114.  
  115. main();
  116.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement