/ instagramUtil / instagramBlockerClient.js
instagramBlockerClient.js
 1  import readline from 'readline';
 2  import { appendDataToFile } from '../utils/ioUtils.js';
 3  import { IgApiClient } from 'instagram-private-api';
 4  import process from "node:process";
 5  
 6  const ig = new IgApiClient();
 7  
 8  function waitFor(milliseconds) {
 9      return new Promise((resolve) => {
10          setTimeout(resolve, milliseconds);
11      });
12  }
13  
14  export async function login(username, password) {
15      ig.state.generateDevice(username);
16  
17      // Attempt login
18      try {
19          await ig.account.login(username, password);
20          console.info('logged in');
21      } catch (error) {
22          // Check if 2FA is required
23          if (
24              error.name === 'IgCheckpointError' ||
25              error.name === 'IgLoginTwoFactorRequiredError'
26          ) {
27              await ig.challenge.auto(true); // Requesting SMS code or Email code
28              console.log('2FA required, check your SMS or Email for the code.');
29  
30              const rl = readline.createInterface({
31                  input: process.stdin,
32                  output: process.stdout,
33              });
34  
35              // Prompt user to enter the 2FA code
36              const code = await new Promise((resolve) =>
37                  rl.question('Enter 2FA code: ', resolve),
38              );
39              rl.close();
40  
41              await ig.challenge.sendSecurityCode(code.trim());
42          } else {
43              throw error;
44          }
45      }
46  }
47  
48  export async function blockAccounts(accounts, delay) {
49      const newlyBlocked = [];
50  
51      for (const account of accounts) {
52          try {
53              const userId = await ig.user.getIdByUsername(account);
54              await ig.friendship.block(userId);
55              console.log(`Blocked: ${account}`);
56              newlyBlocked.push(account);
57              await waitFor(delay);
58          } catch (error) {
59              console.error(`Failed to block ${account}: ${error.message}`);
60          }
61      }
62  
63      // Append newly blocked accounts to alreadyBlocked.txt
64      if (newlyBlocked.length > 0) {
65          appendDataToFile(newlyBlocked.join('\n') + '\n');
66      }
67  }