Skip to content

Commit fce9255

Browse files
committed
update: Updated instagram command with more error handling and updated user agents and headers
1 parent c0ccff2 commit fce9255

File tree

3 files changed

+124
-28
lines changed

3 files changed

+124
-28
lines changed

src/commands/InstaNotification/instaNotification.js

Lines changed: 60 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,71 @@ const InstagramSchema = require('../../schemas/instaNotificationSystem');
33
const fetch = require('node-fetch');
44
const { color, getTimestamp } = require('../../utils/loggingEffects');
55

6+
const USER_AGENTS = [
7+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
8+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
9+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
10+
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
11+
];
12+
13+
function getRandomUserAgent() {
14+
return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
15+
}
16+
17+
async function fetchWithRetry(url, options, maxRetries = 2) {
18+
let lastError;
19+
20+
for (let attempt = 0; attempt < maxRetries; attempt++) {
21+
try {
22+
if (attempt > 0) {
23+
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
24+
options.headers['User-Agent'] = getRandomUserAgent();
25+
}
26+
27+
return await fetch(url, options);
28+
} catch (error) {
29+
lastError = error;
30+
}
31+
}
32+
33+
throw lastError;
34+
}
35+
636
async function validateInstagramUser(username) {
737
try {
8-
const response = await fetch(`https://www.instagram.com/api/v1/users/web_profile_info/?username=${username}`, {
9-
headers: {
10-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
11-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
12-
'Accept-Language': 'en-US,en;q=0.9',
13-
'X-IG-App-ID': '936619743392459'
14-
}
15-
});
38+
const encodedUsername = encodeURIComponent(username);
39+
const apiUrl = `https://www.instagram.com/api/v1/users/web_profile_info/?username=${encodedUsername}`;
40+
41+
const headers = {
42+
'User-Agent': getRandomUserAgent(),
43+
'Accept': '*/*',
44+
'Accept-Language': 'en-US,en;q=0.9',
45+
'X-IG-App-ID': '936619743392459',
46+
'X-Requested-With': 'XMLHttpRequest',
47+
'Referer': `https://www.instagram.com/${username}/`,
48+
'Origin': 'https://www.instagram.com',
49+
'Sec-Fetch-Site': 'same-origin',
50+
'Sec-Fetch-Mode': 'cors',
51+
'Sec-Fetch-Dest': 'empty',
52+
};
53+
54+
const response = await fetchWithRetry(apiUrl, { headers });
55+
56+
if (!response.ok) {
57+
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Failed to validate user ${username}: Status ${response.status}${color.reset}`);
58+
return false;
59+
}
1660

17-
if (!response.ok) return false;
1861
const data = await response.json();
19-
return !!data.data.user;
62+
63+
if (!data?.data?.user) {
64+
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] User ${username} not found or private${color.reset}`);
65+
return false;
66+
}
67+
68+
return true;
2069
} catch (error) {
21-
console.error('Error validating Instagram user:', error);
70+
console.error(`${color.red}[${getTimestamp()}] [INSTA_NOTIFICATION] Error validating Instagram user ${username}: ${color.reset}`, error);
2271
return false;
2372
}
2473
}

src/events/CommandEvents/instaNotificationEvent.js

Lines changed: 63 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,40 @@ const logRateLimiter = {
4242
}
4343
};
4444

45+
const USER_AGENTS = [
46+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
47+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
48+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0',
49+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
50+
];
51+
52+
function getRandomUserAgent() {
53+
return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
54+
}
55+
56+
async function fetchWithRetry(url, options, maxRetries = 3) {
57+
let lastError;
58+
59+
for (let attempt = 0; attempt < maxRetries; attempt++) {
60+
try {
61+
if (attempt > 0) {
62+
await delay(1000 * attempt);
63+
}
64+
65+
if (attempt > 0) {
66+
options.headers['User-Agent'] = getRandomUserAgent();
67+
}
68+
69+
return await fetch(url, options);
70+
} catch (error) {
71+
lastError = error;
72+
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Fetch attempt ${attempt + 1} failed: ${error.message}${color.reset}`);
73+
}
74+
}
75+
76+
throw lastError;
77+
}
78+
4579
function delay(ms) {
4680
return new Promise(resolve => setTimeout(resolve, ms));
4781
}
@@ -52,22 +86,33 @@ async function getLatestPost(username) {
5286
}
5387

5488
try {
55-
const userResponse = await fetch(`https://www.instagram.com/api/v1/users/web_profile_info/?username=${username}`, {
56-
headers: {
57-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
58-
'Accept': 'application/json',
59-
'Accept-Language': 'en-US,en;q=0.9',
60-
'X-IG-App-ID': '936619743392459',
61-
'X-Requested-With': 'XMLHttpRequest',
62-
'Referer': `https://www.instagram.com/${username}/`,
63-
'Cookie': 'ig_did=1; csrftoken=1; mid=1;'
64-
}
65-
});
89+
const headers = {
90+
'User-Agent': getRandomUserAgent(),
91+
'Accept': '*/*',
92+
'Accept-Language': 'en-US,en;q=0.9',
93+
'X-IG-App-ID': '936619743392459',
94+
'X-Requested-With': 'XMLHttpRequest',
95+
'Referer': `https://www.instagram.com/${username}/`,
96+
'Origin': 'https://www.instagram.com',
97+
'Sec-Fetch-Site': 'same-origin',
98+
'Sec-Fetch-Mode': 'cors',
99+
'Sec-Fetch-Dest': 'empty',
100+
};
101+
102+
const encodedUsername = encodeURIComponent(username);
103+
const apiUrl = `https://www.instagram.com/api/v1/users/web_profile_info/?username=${encodedUsername}`;
104+
105+
const userResponse = await fetchWithRetry(apiUrl, { headers });
66106

67107
if (!userResponse.ok) {
68-
if (userResponse.status !== 429) {
69-
if (logRateLimiter.shouldLog(`api_error_${username}`, 60)) {
70-
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Warning: Instagram API returned ${userResponse.status} for ${username}${color.reset}`);
108+
const statusCode = userResponse.status;
109+
if (logRateLimiter.shouldLog(`api_error_${username}_${statusCode}`, 30)) {
110+
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Instagram API returned ${statusCode} for ${username}${color.reset}`);
111+
112+
if (statusCode === 429) {
113+
console.error(`${color.red}[${getTimestamp()}] [INSTA_NOTIFICATION] Rate limited by Instagram${color.reset}`);
114+
} else if (statusCode === 401 || statusCode === 403) {
115+
console.error(`${color.red}[${getTimestamp()}] [INSTA_NOTIFICATION] Authentication error for Instagram API${color.reset}`);
71116
}
72117
}
73118
return null;
@@ -83,9 +128,10 @@ async function getLatestPost(username) {
83128

84129
const userData = await userResponse.json();
85130

86-
if (!userData || !userData.data || !userData.data.user) {
131+
if (!userData?.data?.user) {
87132
if (logRateLimiter.shouldLog(`no_user_data_${username}`, 60)) {
88-
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Warning: No user data found for ${username}${color.reset}`);
133+
const errorDetails = userData?.status === 'fail' ? ` - Reason: ${userData.message}` : '';
134+
console.error(`${color.yellow}[${getTimestamp()}] [INSTA_NOTIFICATION] Warning: No user data found for ${username}${errorDetails}${color.reset}`);
89135
}
90136
return null;
91137
}
@@ -110,7 +156,7 @@ async function getLatestPost(username) {
110156
const now = Date.now();
111157
const lastErrorTime = rateLimiter.lastWarning[`error_${username}`] || 0;
112158
if (now - lastErrorTime > 60 * 60 * 1000) {
113-
console.error(`${color.red}[${getTimestamp()}] [INSTA_NOTIFICATION] Error fetching Instagram posts for ${username}: ${color.reset}`, error);
159+
console.error(`${color.red}[${getTimestamp()}] [INSTA_NOTIFICATION] Error fetching Instagram posts for ${username}: ${error.message}${color.reset}`);
114160
rateLimiter.lastWarning[`error_${username}`] = now;
115161
}
116162
return null;

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ client.skinsTier = null;
6969
const giveawayClient = require('./client/giveawayClientEvent.js');
7070
const distubeClient = require('./client/distubeClientEvent.js');
7171
const auditLogsClient = require('./client/auditLogsClientEvent.js');
72+
7273
const { handleLogs } = require("./events/CommandEvents/handleLogsEvent");
7374
const { checkVersion } = require('./lib/version');
7475
const { fetchValorantAPI } = require('./utils/fetchValorantApi.js');

0 commit comments

Comments
 (0)