-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsend_bulk_from_csv.py
More file actions
149 lines (121 loc) · 4.28 KB
/
Copy pathsend_bulk_from_csv.py
File metadata and controls
149 lines (121 loc) · 4.28 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Send DMs to artists from CSV file"""
import sys
import os
import time
import pandas as pd
import re
import random
# Fix Windows console encoding issues
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
from instagram_client import InstagramClient
def extract_username_from_url(instagram_url):
"""Extract Instagram username from URL or handle"""
if pd.isna(instagram_url) or not instagram_url:
return None
# Remove trailing slashes
instagram_url = instagram_url.strip().rstrip('/')
# Extract username from URL patterns
# https://www.instagram.com/username/
# https://instagram.com/username
# @username
# username
patterns = [
r'instagram\.com/([^/\?]+)', # From URL
r'@([a-zA-Z0-9._]+)', # From @mention
r'^([a-zA-Z0-9._]+)$' # Plain username
]
for pattern in patterns:
match = re.search(pattern, instagram_url)
if match:
return match.group(1)
return None
def send_bulk_from_csv(csv_file, message_file):
"""Send DMs to all artists in CSV with Instagram accounts"""
# Read message template
try:
with open(message_file, 'r', encoding='utf-8') as f:
message = f.read().strip()
except FileNotFoundError:
print(f"[!] Message file not found: {message_file}")
return
print(f"[*] Message to send:")
print("-" * 60)
print(message)
print("-" * 60)
print()
# Read CSV file
try:
df = pd.read_csv(csv_file)
except FileNotFoundError:
print(f"[!] CSV file not found: {csv_file}")
return
print(f"[*] Loaded {len(df)} entries from CSV")
# Extract Instagram usernames (starting from row 39)
START_FROM_ROW = 39
usernames = []
for idx, row in df.iterrows():
# Skip rows before the start row
if idx + 1 < START_FROM_ROW:
continue
if 'instagram' in df.columns and pd.notna(row['instagram']):
username = extract_username_from_url(row['instagram'])
if username:
artist_name = row['name'] if 'name' in df.columns else username
usernames.append({
'username': username,
'artist_name': artist_name,
'row_num': idx + 1
})
print(f"[*] Found {len(usernames)} artists with Instagram accounts\n")
# Initialize Instagram client
client = InstagramClient()
if not client.login():
print("[!] Login failed")
return
print(f"\n[*] Starting to send DMs...\n")
# Send DMs
sent_count = 0
failed_count = 0
skipped_count = 0
for i, artist in enumerate(usernames, 1):
username = artist['username']
artist_name = artist['artist_name']
# Randomize delay for this DM (90-180 seconds)
client.delay_between_dms = random.randint(90, 180)
print(f"[{i}/{len(usernames)}] {artist_name} (@{username})...", end=' ', flush=True)
try:
success, msg = client.send_dm(username, message)
if success:
sent_count += 1
print("[+] Sent")
else:
# Check if it's a rate limit
if "rate limit" in msg.lower() or "wait" in msg.lower():
print(f"[!] Rate limited")
print(f"\n[!] Rate limit reached. Stopping.")
print(f"[*] Progress: {sent_count}/{len(usernames)} sent before rate limit")
break
else:
failed_count += 1
print(f"[!] Failed: {msg}")
except Exception as e:
failed_count += 1
print(f"[!] Error: {str(e)}")
continue
# Summary
print("\n" + "=" * 60)
print("SUMMARY")
print("=" * 60)
print(f"Total artists: {len(usernames)}")
print(f"Successfully sent: {sent_count}")
print(f"Failed: {failed_count}")
print(f"Remaining: {len(usernames) - sent_count - failed_count}")
print("=" * 60)
if __name__ == '__main__':
csv_file = 'baybeats_artists_first_170.csv'
message_file = 'message_template.txt'
send_bulk_from_csv(csv_file, message_file)