Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
492 lines (412 loc) · 20.7 KB
/
Copy pathbot.py
File metadata and controls
492 lines (412 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import discord
from discord.ext import commands
from discord import app_commands
import asyncio
import math
import os
import re
import requests
import csv
import zipfile
import io
from datetime import datetime
from dotenv import load_dotenv
from keep_alive import keep_alive
# --- 1. SETUP ---
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD_ID = os.getenv('GUILD_ID')
RAPID_KEY = os.getenv('RAPIDAPI_KEY')
if not TOKEN or not RAPID_KEY or not GUILD_ID:
print("FATAL ERROR: Missing variables in .env file! Check TOKEN, GUILD_ID, and RAPIDAPI_KEY.")
exit()
MY_GUILD = discord.Object(id=int(GUILD_ID.strip()))
# --- 2. SHEET LINK PARSER ---
def parse_sheet_link(sheet_link: str) -> tuple[str | None, str]:
sheet_link = sheet_link.strip()
match_id = re.search(r'/spreadsheets/d/([a-zA-Z0-9-_]+)', sheet_link)
if not match_id:
return None, "0"
sheet_id = match_id.group(1)
match_gid = re.search(r'[?&]gid=([0-9]+)', sheet_link)
if not match_gid:
match_gid = re.search(r'#gid=([0-9]+)', sheet_link)
gid = match_gid.group(1) if match_gid else "0"
return sheet_id, gid
# --- 3. THE HYBRID EXTRACTOR (CSV + XLSX) ---
def extract_valid_reels_from_text(raw_text: str) -> list[str]:
"""Nuclear scanner: ignores formatting and rips IG links straight from raw text."""
valid_links = []
pattern = re.compile(r"(https?://(?:www\.)?instagram\.com/reel/[a-zA-Z0-9_-]+)")
matches = pattern.findall(raw_text)
for match in matches:
if match not in valid_links:
valid_links.append(match)
return valid_links
def fetch_sheet_links_sync(sheet_id: str, gid: str) -> list[str]:
"""
Attempts to fetch as CSV first. If blocked (Excel file), downloads
the XLSX, unzips it in memory, and scans the internal XML data.
"""
csv_url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv&gid={gid}"
print(f"[DEBUG] Attempting CSV Fetch: {csv_url}")
res = requests.get(csv_url, timeout=15)
if res.status_code == 200:
print("[DEBUG] CSV fetch successful.")
return extract_valid_reels_from_text(res.text)
print(f"[DEBUG] CSV blocked (HTTP {res.status_code}). Attempting XLSX Extraction Loophole...")
# THE EXCEL LOOPHOLE
xlsx_url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
res_xlsx = requests.get(xlsx_url, timeout=15)
if res_xlsx.status_code == 200:
try:
# Unzip the Excel file in memory
with zipfile.ZipFile(io.BytesIO(res_xlsx.content)) as z:
full_text = ""
# Read every internal XML file where text might be stored
for filename in z.namelist():
if filename.endswith('.xml'):
full_text += z.read(filename).decode('utf-8', errors='ignore') + " "
print("[DEBUG] XLSX extraction successful.")
return extract_valid_reels_from_text(full_text)
except Exception as e:
raise Exception(f"Failed to parse internal XLSX data: {e}")
if res.status_code in (401, 403):
raise Exception("HTTP 403: Sheet is not public. Change to 'Anyone with the link'.")
raise Exception(f"Google API blocked the request completely. (HTTP {res.status_code})")
# --- 4. JSON HUNTER ---
def extract_views_safely(json_data: dict) -> int:
try:
d = json_data.get('data', {})
if isinstance(d, dict):
for key in ('video_play_count', 'play_count', 'view_count', 'video_view_count'):
if d.get(key) is not None:
return int(d[key])
except Exception:
pass
found_plays, found_views = [], []
def search(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if k == 'video_play_count' and v is not None:
try: found_plays.append(int(v))
except: pass
elif k in ('video_view_count', 'play_count', 'view_count') and v is not None:
try: found_views.append(int(v))
except: pass
search(v)
elif isinstance(obj, list):
for item in obj: search(item)
search(json_data)
if found_plays: return found_plays[0]
if found_views: return found_views[0]
return -1
def extract_thumbnail(data: dict) -> str | None:
try:
candidates = data.get('image_versions2', {}).get('candidates', [])
if candidates:
for c in candidates:
if c.get('height') == 1080 or c.get('width') == 1080:
return c['url']
return candidates[0]['url']
except Exception:
pass
return data.get('display_url') or data.get('thumbnail_url')
def extract_caption(data: dict) -> str:
raw = data.get('caption')
if raw is None: return 'No caption provided.'
if isinstance(raw, str): return raw or 'No caption provided.'
if isinstance(raw, dict): return raw.get('text') or 'No caption provided.'
return 'No caption provided.'
def detect_media_type(data: dict) -> str:
product_type = data.get('product_type', '')
media_type = data.get('media_type', -1)
if product_type == 'clips' or data.get('clips_metadata') is not None: return 'reel'
if media_type == 2: return 'reel'
if media_type == 8: return 'carousel'
if media_type == 1: return 'photo'
return 'unknown'
# --- 5. API ENGINES ---
def fetch_views_via_api(reel_url: str) -> tuple[int, str]:
url = "https://instagram-scraper-stable-api.p.rapidapi.com/get_media_data.php"
headers = {
"x-rapidapi-key": RAPID_KEY,
"x-rapidapi-host": "instagram-scraper-stable-api.p.rapidapi.com",
"Content-Type": "application/json"
}
try:
response = requests.get(url, headers=headers, params={"reel_post_code_or_url": reel_url, "type": "reel"}, timeout=15)
if response.status_code == 200:
json_data = response.json()
inner = json_data.get('data', json_data)
return extract_views_safely(json_data), detect_media_type(inner)
return -1, 'error'
except Exception:
return -1, 'error'
def fetch_detailed_reel_data(reel_url: str) -> dict:
url = "https://instagram-scraper-stable-api.p.rapidapi.com/get_media_data.php"
headers = {
"x-rapidapi-key": RAPID_KEY,
"x-rapidapi-host": "instagram-scraper-stable-api.p.rapidapi.com",
"Content-Type": "application/json"
}
try:
response = requests.get(url, headers=headers, params={"reel_post_code_or_url": reel_url, "type": "reel"}, timeout=15)
if response.status_code != 200:
return {"success": False, "error": f"API returned HTTP {response.status_code}"}
json_data = response.json()
inner = json_data.get('data', json_data)
owner = inner.get('owner') or inner.get('user') or {}
taken_at = inner.get('taken_at_timestamp') or inner.get('taken_at')
# --- THE FIX: SMART EXTRACTORS FOR LIKES & COMMENTS ---
# 1. Hunt for Likes
likes = 0
if 'edge_media_preview_like' in inner and isinstance(inner['edge_media_preview_like'], dict):
likes = inner['edge_media_preview_like'].get('count', 0)
elif 'like_count' in inner:
likes = inner.get('like_count', 0)
# 2. Hunt for Comments
comments = 0
if 'edge_media_to_parent_comment' in inner and isinstance(inner['edge_media_to_parent_comment'], dict):
comments = inner['edge_media_to_parent_comment'].get('count', 0)
elif 'edge_media_to_comment' in inner and isinstance(inner['edge_media_to_comment'], dict):
comments = inner['edge_media_to_comment'].get('count', 0)
elif 'comment_count' in inner:
comments = inner.get('comment_count', 0)
return {
"success": True,
"views": extract_views_safely(json_data),
"likes": likes,
"comment_count": comments,
"caption": extract_caption(inner),
"username": owner.get('username', 'Unknown Creator'),
"is_verified": owner.get('is_verified', False),
"profile_pic": owner.get('profile_pic_url') or (owner.get('hd_profile_pic_url_info') or {}).get('url'),
"thumbnail": extract_thumbnail(inner),
"post_date": datetime.utcfromtimestamp(taken_at).strftime('%b %d, %Y') if taken_at else 'Unknown',
"shortcode": inner.get('code') or inner.get('shortcode') or 'N/A',
"media_type": detect_media_type(inner),
}
except Exception as e:
return {"success": False, "error": str(e)}
# --- 6. UI HELPERS ---
def generate_progress_bar(current, total, length=20):
if total <= 0: return f"[{'░' * length}] 0%"
pct = current / total
filled = math.floor(length * pct)
return f"[{'█' * filled}{'░' * (length - filled)}] {int(pct * 100)}%"
def format_number(n: int) -> str:
if n >= 1_000_000: return f"{n / 1_000_000:.1f}M"
if n >= 1_000: return f"{n / 1_000:.1f}K"
return f"{n:,}"
# --- 7. BULK DASHBOARD VIEW ---
class DashboardView(discord.ui.View):
def __init__(self, sheet_link: str, sheet_id: str, gid: str):
super().__init__(timeout=None)
self.sheet_link = sheet_link
self.sheet_id = sheet_id
self.gid = gid
self.is_processing = False
self.stop_requested = False
@discord.ui.button(label="🔄 Recount Views", style=discord.ButtonStyle.primary, custom_id="recount_btn")
async def recount_button(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.is_processing:
await interaction.response.send_message("⏳ Already running!", ephemeral=True)
return
await interaction.response.defer()
self.is_processing = True
self.stop_requested = False
button.disabled = True
button.label = "Scraping..."
button.style = discord.ButtonStyle.secondary
stop_btn = next(x for x in self.children if getattr(x, 'custom_id', None) == 'stop_btn')
stop_btn.disabled = False
await interaction.message.edit(view=self)
embed = discord.Embed(title="📊 Bulk Reel Tracker", color=discord.Color.brand_red())
embed.add_field(name="Target Sheet", value=f"[Open Document]({self.sheet_link})", inline=False)
embed.add_field(name="Status", value="🟡 Fetching Links...", inline=True)
embed.add_field(name="Reels Checked", value="0 / ?", inline=True)
embed.add_field(name="Total Views", value="0 👀", inline=True)
embed.add_field(name="Dead/Private", value="0 🗑️", inline=True)
embed.add_field(name="Skipped (Photos)", value="0 🖼️", inline=True)
embed.add_field(name="Progress", value=generate_progress_bar(0, 1), inline=False)
await interaction.message.edit(embed=embed)
try:
# Use the new hybrid extractor
links = await asyncio.to_thread(fetch_sheet_links_sync, self.sheet_id, self.gid)
total_reels = len(links)
if total_reels == 0:
raise Exception("No valid Instagram Reel links found anywhere in this file.")
current_p = total_v = dead_v = skipped_v = 0
for link in links:
if self.stop_requested:
embed.set_field_at(1, name="Status", value="🟠 Stopped by user.", inline=True)
break
views, mtype = await asyncio.to_thread(fetch_views_via_api, link)
if mtype in ('photo', 'carousel'):
skipped_v += 1
elif views >= 0:
total_v += views
else:
dead_v += 1
current_p += 1
if current_p % 3 == 0 or current_p == total_reels:
embed.set_field_at(1, name="Status", value=f"🟡 Scraping {current_p}/{total_reels}...", inline=True)
embed.set_field_at(2, name="Reels Checked", value=f"{current_p:,} / {total_reels:,}", inline=True)
embed.set_field_at(3, name="Total Views", value=f"{format_number(total_v)} 👀", inline=True)
embed.set_field_at(4, name="Dead/Private", value=f"{dead_v:,} 🗑️", inline=True)
embed.set_field_at(5, name="Skipped (Photos)", value=f"{skipped_v:,} 🖼️", inline=True)
embed.set_field_at(6, name="Progress", value=generate_progress_bar(current_p, total_reels), inline=False)
await interaction.message.edit(embed=embed)
await asyncio.sleep(2.5)
if not self.stop_requested:
embed.color = discord.Color.green()
embed.set_field_at(1, name="Status", value="🟢 Done. Ready for recount.", inline=True)
except Exception as e:
embed.color = discord.Color.red()
embed.set_field_at(1, name="Status", value=f"❌ Error: {e}", inline=True)
self.is_processing = False
button.disabled = False
button.label = "🔄 Recount Views"
button.style = discord.ButtonStyle.primary
stop_btn.disabled = True
await interaction.message.edit(embed=embed, view=self)
@discord.ui.button(label="🛑 Stop", style=discord.ButtonStyle.danger, custom_id="stop_btn", disabled=True)
async def stop_button(self, interaction: discord.Interaction, button: discord.ui.Button):
self.stop_requested = True
button.disabled = True
await interaction.response.edit_message(view=self)
# --- 8. BOT CORE ---
class ReelBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='!', intents=discord.Intents.default())
async def setup_hook(self):
try:
synced = await self.tree.sync(guild=MY_GUILD)
print(f"✅ Synced {len(synced)} command(s) to Guild ID: {GUILD_ID}")
except Exception as e:
pass
bot = ReelBot()
# --- 9. COMMAND: BULK DASHBOARD ---
@bot.tree.command(name="track_reels", description="Spawn the bulk analytics dashboard from your Document", guild=MY_GUILD)
@app_commands.describe(sheet_link="The full link to your Google Sheet or Excel File")
async def track_reels(interaction: discord.Interaction, sheet_link: str):
await interaction.response.defer()
sheet_id, gid = parse_sheet_link(sheet_link)
if not sheet_id:
await interaction.followup.send("❌ Could not find a Sheet ID in that link.", ephemeral=True)
return
if len(sheet_id) < 25:
await interaction.followup.send(f"❌ The ID looks too short (`{sheet_id}`). Paste the full URL.", ephemeral=True)
return
try:
# Pre-flight using the new Hybrid Extractor
valid_links = await asyncio.to_thread(fetch_sheet_links_sync, sheet_id, gid)
valid_count = len(valid_links)
except Exception as e:
await interaction.followup.send(f"❌ Could not reach document: `{e}`", ephemeral=True)
return
embed = discord.Embed(
title="📊 Bulk Reel Tracker Dashboard",
color=discord.Color.blue(),
description=f"Document validated ✅ — found **{valid_count} reel link(s)**.\nClick **Recount Views** to start."
)
embed.add_field(name="Document", value=f"[Open File]({sheet_link})", inline=True)
embed.add_field(name="System", value="`Hybrid XLSX/CSV Parser`", inline=True)
embed.set_footer(text="Reel Tracker Pro • RapidAPI Engine")
view = DashboardView(sheet_link, sheet_id, gid)
await interaction.followup.send(embed=embed, view=view)
# --- 10. COMMAND: SINGLE REEL DEEP DIVE ---
@bot.tree.command(name="check_reel", description="Get deep analytics for a single Instagram post or Reel", guild=MY_GUILD)
@app_commands.describe(reel_link="The full link to the Instagram Reel or post")
async def check_reel(interaction: discord.Interaction, reel_link: str):
await interaction.response.defer()
if "instagram.com" not in reel_link:
await interaction.followup.send("❌ Please provide a valid Instagram link.", ephemeral=True)
return
data = await asyncio.to_thread(fetch_detailed_reel_data, reel_link.strip())
if not data.get("success"):
await interaction.followup.send(f"❌ Failed: `{data.get('error')}`")
return
eng_rate = "N/A"
if data['views'] and data['views'] > 0 and data['likes'] > 0:
eng_rate = f"{(data['likes'] / data['views']) * 100:.2f}%"
mtype_badge = {'reel': '🎬 Reel', 'photo': '🖼️ Photo', 'carousel': '🎠 Carousel'}.get(data['media_type'], '❓ Unknown')
verified_tag = " ✅" if data['is_verified'] else ""
embed = discord.Embed(
title=f"{mtype_badge} Analytics",
url=reel_link,
color=0xE1306C,
timestamp=discord.utils.utcnow()
)
if data['username'] != 'Unknown Creator':
embed.set_author(
name=f"@{data['username']}{verified_tag}",
url=f"https://instagram.com/{data['username']}",
icon_url=data.get('profile_pic') or discord.Embed.Empty
)
else:
embed.set_author(name="👤 Unknown Creator")
views_display = f"` {format_number(data['views'])} `" if data['views'] != -1 else "` ⚠️ N/A `"
embed.add_field(name="▶️ Plays", value=f"**{views_display}**", inline=True)
embed.add_field(name="❤️ Likes", value=f"**` {format_number(data['likes'])} `**", inline=True)
embed.add_field(name="💬 Comments", value=f"**` {format_number(data['comment_count'])} `**", inline=True)
embed.add_field(name="📈 Engagement", value=f"**` {eng_rate} `**", inline=True)
embed.add_field(name="📅 Posted", value=f"**` {data['post_date']} `**", inline=True)
embed.add_field(name="🔗 Shortcode", value=f"**` {data['shortcode']} `**", inline=True)
if data['caption'] != 'No caption provided.':
cap = (data['caption'][:300] + '...') if len(data['caption']) > 300 else data['caption']
embed.add_field(name="📝 Caption", value=f">>> {cap}", inline=False)
if data.get('thumbnail'):
embed.set_image(url=data['thumbnail'])
embed.set_footer(
text="Reel Tracker Pro • RapidAPI Engine",
icon_url="https://cdn-icons-png.flaticon.com/512/2111/2111463.png"
)
await interaction.followup.send(embed=embed)
# --- 11. COMMAND: HELP ---
@bot.tree.command(name="help", description="The master guide for Reel Tracker Pro", guild=MY_GUILD)
async def help_command(interaction: discord.Interaction):
embed = discord.Embed(
title="🛠️ Reel Tracker Pro | Command Center",
description="The WAF-bypassing Instagram analytics engine. Here is your full arsenal:",
color=0x2b2d31
)
embed.set_thumbnail(url="https://cdn-icons-png.flaticon.com/512/1055/1055644.png")
embed.add_field(
name="📊 `/track_reels [sheet_link]`",
value=(
"**Bulk Dashboard.**\n"
"Paste any Google Sheet or Excel link. The bot scans the whole document, "
"tallies live view counts in real-time, flags dead/private links, "
"and skips photos/carousels automatically."
),
inline=False
)
embed.add_field(
name="🎯 `/check_reel [reel_link]`",
value=(
"**Deep Dive.**\n"
"Paste any Instagram link. Returns Plays, Likes, Comments, Engagement Rate, "
"Post Date, Shortcode, Caption, and a full HD thumbnail."
),
inline=False
)
embed.add_field(
name="💡 Requirements",
value=(
"> • Sheet must be **'Anyone with the link can view'**.\n"
"> • Link can be anywhere in the document.\n"
"> • Both Google Sheets & Excel files are supported."
),
inline=False
)
embed.set_footer(
text="System Online • Made By @rvvwl",
icon_url="https://cdn-icons-png.flaticon.com/512/2111/2111463.png"
)
await interaction.response.send_message(embed=embed)
# WAKE UP THE FAKE WEBSITE SO RENDER DOESN'T KILL US
keep_alive()
# START THE DISCORD BOT
bot.run(TOKEN)