-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
495 lines (402 loc) · 15.7 KB
/
main.py
File metadata and controls
495 lines (402 loc) · 15.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
493
494
495
#!/usr/bin/env python3
"""
Instagram DM Bulk Automation — Powered by SoClose
https://soclose.co
"""
import os
import sys
import csv
import time
import random
import logging
from pathlib import Path
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from rich.progress import (
Progress,
SpinnerColumn,
TextColumn,
BarColumn,
TaskProgressColumn,
)
from rich.logging import RichHandler
from rich.theme import Theme
from selenium import webdriver
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import (
TimeoutException,
ElementClickInterceptedException,
NoSuchElementException,
WebDriverException,
StaleElementReferenceException,
)
# ─── SoClose Brand Theme ────────────────────────────────────
SOCLOSE_THEME = Theme(
{
"info": "#575ECF",
"success": "bold green",
"warning": "bold yellow",
"error": "bold red",
"brand": "bold #575ECF",
"muted": "#c5c1b9",
}
)
console = Console(theme=SOCLOSE_THEME)
# ─── Configuration ───────────────────────────────────────────
load_dotenv()
INSTAGRAM_EMAIL = os.getenv("INSTAGRAM_EMAIL")
INSTAGRAM_PASSWORD = os.getenv("INSTAGRAM_PASSWORD")
BROWSER = os.getenv("BROWSER", "firefox").lower()
MESSAGE_FILE = os.getenv("MESSAGE_FILE", "message.txt")
PROFILES_FILE = os.getenv("PROFILES_FILE", "profile_links.csv")
SENT_FILE = os.getenv("SENT_FILE", "already_send_message.csv")
MAX_MESSAGES = int(os.getenv("MAX_MESSAGES", "10000"))
HEADLESS = os.getenv("HEADLESS", "false").lower() == "true"
MIN_DELAY = int(os.getenv("MIN_DELAY", "8"))
MAX_DELAY = int(os.getenv("MAX_DELAY", "15"))
# ─── Logging ─────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[RichHandler(console=console, rich_tracebacks=True, show_path=False)],
)
log = logging.getLogger("soclose")
# ─── Helpers ─────────────────────────────────────────────────
def show_banner():
"""Display the SoClose branded banner."""
console.print()
console.print(
Panel(
"[bold #575ECF]Instagram DM Bulk Automation[/]\n"
"[#c5c1b9]Digital Innovation Through Automation & AI[/]\n"
"[#c5c1b9]https://soclose.co[/]",
title="[bold #575ECF]SoClose[/]",
border_style="#575ECF",
padding=(1, 4),
)
)
console.print()
def extract_username(value: str) -> str:
"""Extract Instagram username from a URL or plain username."""
value = value.strip().strip("/")
if "instagram.com" in value:
parts = value.split("instagram.com/")
if len(parts) > 1:
username = parts[1].split("/")[0].split("?")[0]
return username
# Already a plain username
return value
def load_message(filepath: str) -> str:
"""Load the message template from file."""
path = Path(filepath)
if not path.exists():
console.print(f"[error]Message file not found: {filepath}[/]")
sys.exit(1)
message = path.read_text(encoding="utf-8").strip()
if not message:
console.print("[error]Message file is empty.[/]")
sys.exit(1)
log.info(f"Message loaded ({len(message)} chars)")
return message
def load_profiles(filepath: str) -> list:
"""Load target profile usernames from CSV."""
path = Path(filepath)
if not path.exists():
console.print(f"[error]Profile file not found: {filepath}[/]")
sys.exit(1)
profiles = []
with open(path, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if row:
raw = row[0].strip()
if not raw or raw.lower() == "profile link":
continue
username = extract_username(raw)
if username:
profiles.append(username)
log.info(f"Loaded {len(profiles)} profiles")
return profiles
def load_sent(filepath: str) -> set:
"""Load the set of already-messaged usernames."""
path = Path(filepath)
if not path.exists():
return set()
sent = set()
with open(path, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if row:
raw = row[0].strip()
if not raw or raw.lower() == "profile link":
continue
username = extract_username(raw)
if username:
sent.add(username)
log.info(f"Already sent: {len(sent)} profiles")
return sent
def save_sent(filepath: str, sent: set):
"""Save the set of messaged usernames to CSV."""
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Profile Link"])
for username in sorted(sent):
writer.writerow([username])
def random_delay(min_sec=None, max_sec=None):
"""Sleep for a random duration to mimic human behavior."""
lo = min_sec if min_sec is not None else MIN_DELAY
hi = max_sec if max_sec is not None else MAX_DELAY
time.sleep(random.uniform(lo, hi))
# ─── Browser ─────────────────────────────────────────────────
def create_driver():
"""Initialize and return the browser driver."""
if BROWSER == "chrome":
options = webdriver.ChromeOptions()
options.add_argument("--disable-notifications")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
if HEADLESS:
options.add_argument("--headless=new")
service = ChromeService(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
else:
options = webdriver.FirefoxOptions()
options.set_preference("dom.webnotifications.enabled", False)
if HEADLESS:
options.add_argument("--headless")
service = FirefoxService(GeckoDriverManager().install())
driver = webdriver.Firefox(service=service, options=options)
driver.maximize_window()
return driver
# ─── Instagram Actions ───────────────────────────────────────
def dismiss_popup(driver, timeout=5):
"""Try to dismiss common Instagram popups (cookies, notifications)."""
popup_xpaths = [
"//button[contains(text(), 'Allow')]",
"//button[contains(text(), 'Accept')]",
"//button[contains(text(), 'Autoriser')]",
"//button[contains(text(), 'Not Now')]",
"//button[contains(text(), 'Pas maintenant')]",
"//button[contains(text(), 'Plus tard')]",
"//button[contains(text(), 'Decline')]",
]
for xpath in popup_xpaths:
try:
btn = WebDriverWait(driver, timeout).until(
EC.element_to_be_clickable((By.XPATH, xpath))
)
btn.click()
time.sleep(1)
return True
except (TimeoutException, ElementClickInterceptedException):
continue
return False
def login(driver):
"""Log in to Instagram."""
console.print("[info]Navigating to Instagram login...[/]")
driver.get("https://www.instagram.com/accounts/login/")
random_delay(5, 8)
# Dismiss cookie consent if present
dismiss_popup(driver, timeout=4)
# Enter credentials
console.print("[info]Entering credentials...[/]")
username_field = WebDriverWait(driver, 15).until(
EC.visibility_of_element_located((By.NAME, "username"))
)
password_field = driver.find_element(By.NAME, "password")
username_field.clear()
username_field.send_keys(INSTAGRAM_EMAIL)
time.sleep(0.5)
password_field.clear()
password_field.send_keys(INSTAGRAM_PASSWORD)
time.sleep(0.5)
# Submit login
driver.find_element(By.XPATH, "//button[@type='submit']").click()
console.print("[info]Login submitted.[/]")
random_delay(5, 8)
# Wait for user to handle 2FA or any manual verification
console.print(
"[warning]If 2FA or a challenge appears, complete it in the browser now.[/]"
)
input("\n Press ENTER once you are logged in and ready to continue... ")
console.print()
random_delay(2, 4)
# Dismiss "Turn on notifications" popup
dismiss_popup(driver, timeout=4)
console.print("[success]Login complete.[/]")
def find_and_click_message_button(driver) -> bool:
"""Find and click the Message button on a profile page."""
selectors = [
(By.XPATH, "//div[@role='button'][text()='Message']"),
(By.XPATH, "//div[text()='Message']/ancestor::*[@role='button']"),
(By.XPATH, "//div[text()='Message']"),
(By.XPATH, "//button[text()='Message']"),
(By.XPATH, "//div[text()='Envoyer un message']"),
(By.XPATH, "//div[text()='Envoyer message']"),
]
for by, selector in selectors:
try:
btn = WebDriverWait(driver, 6).until(
EC.element_to_be_clickable((by, selector))
)
btn.click()
return True
except (
TimeoutException,
ElementClickInterceptedException,
StaleElementReferenceException,
NoSuchElementException,
):
continue
return False
def send_message(driver, message: str) -> bool:
"""Type and send a message in the DM chat window."""
try:
random_delay(3, 5)
# Try multiple selectors for the message input
input_selectors = [
(By.XPATH, "//div[@role='textbox'][@contenteditable='true']"),
(
By.XPATH,
"//textarea[contains(@placeholder, 'Message') or contains(@placeholder, 'message')]",
),
(By.TAG_NAME, "textarea"),
]
input_field = None
for by, selector in input_selectors:
try:
input_field = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((by, selector))
)
break
except TimeoutException:
continue
if not input_field:
log.error("Could not find message input field")
return False
input_field.click()
time.sleep(1)
# Send message with line breaks preserved
lines = message.split("\n")
for i, line in enumerate(lines):
ActionChains(driver).send_keys(line).perform()
if i < len(lines) - 1:
ActionChains(driver).key_down(Keys.SHIFT).send_keys(
Keys.ENTER
).key_up(Keys.SHIFT).perform()
time.sleep(0.3)
# Press Enter to send
time.sleep(1)
ActionChains(driver).send_keys(Keys.RETURN).perform()
random_delay(2, 4)
return True
except Exception as e:
log.error(f"Failed to send message: {e}")
return False
# ─── Main ────────────────────────────────────────────────────
def run():
"""Main execution flow."""
show_banner()
# Validate credentials
if not INSTAGRAM_EMAIL or not INSTAGRAM_PASSWORD:
console.print(
Panel(
"[error]Missing credentials.[/]\n\n"
"Set [bold]INSTAGRAM_EMAIL[/] and [bold]INSTAGRAM_PASSWORD[/] "
"in your [bold].env[/] file.\n"
"See [bold].env.example[/] for reference.",
title="[error]Configuration Error[/]",
border_style="red",
)
)
sys.exit(1)
# Load data
message = load_message(MESSAGE_FILE)
profiles = load_profiles(PROFILES_FILE)
sent = load_sent(SENT_FILE)
# Filter already-sent profiles
remaining = [p for p in profiles if p not in sent]
console.print(f"[info]Profiles to process:[/] {len(remaining)} / {len(profiles)}")
if not remaining:
console.print(
"[warning]No new profiles to message. Add profiles to profile_links.csv.[/]"
)
sys.exit(0)
# Launch browser
console.print(f"[info]Launching {BROWSER.title()} browser...[/]")
driver = create_driver()
try:
login(driver)
count = 0
with Progress(
SpinnerColumn(style="#575ECF"),
TextColumn("[bold #575ECF]{task.description}"),
BarColumn(complete_style="#575ECF", finished_style="green"),
TaskProgressColumn(),
console=console,
) as progress:
total = min(len(remaining), MAX_MESSAGES)
task = progress.add_task("Sending messages", total=total)
for username in remaining:
if count >= MAX_MESSAGES:
console.print(
f"\n[warning]Reached max messages limit ({MAX_MESSAGES})[/]"
)
break
progress.update(task, description=f"Processing @{username}")
# Navigate to profile
driver.get(f"https://www.instagram.com/{username}/")
random_delay(5, 10)
# Find and click Message button
if find_and_click_message_button(driver):
random_delay(3, 6)
if send_message(driver, message):
sent.add(username)
save_sent(SENT_FILE, sent)
count += 1
progress.advance(task)
console.print(
f" [success]Sent to @{username} ({count}/{total})[/]"
)
else:
console.print(
f" [error]Failed to send to @{username}[/]"
)
else:
console.print(
f" [muted]No Message button for @{username} — skipped[/]"
)
sent.add(username)
save_sent(SENT_FILE, sent)
progress.advance(task)
# Human-like delay between profiles
random_delay()
console.print()
console.print(
Panel(
f"[success]{count} messages sent successfully.[/]",
title="[bold #575ECF]Complete[/]",
border_style="#575ECF",
)
)
except KeyboardInterrupt:
console.print("\n[warning]Interrupted. Progress saved.[/]")
except WebDriverException as e:
log.error(f"Browser error: {e}")
finally:
try:
driver.quit()
except Exception:
pass
console.print("[muted]Browser closed.[/]")
if __name__ == "__main__":
run()