-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.py
More file actions
649 lines (493 loc) · 19.4 KB
/
main.py
File metadata and controls
649 lines (493 loc) · 19.4 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import json
import datetime
import threading
import pytz
import telebot
from telebot import types
import random
import snscrape.modules.twitter as sntwitter
from tqdm import tqdm
import schedule
import time
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot_token = '6285308929:AAFHF1mwb83XXt2MJhTzosY17d-m1nVqHMo'
# File path for storing data
enabled_groups_file = 'enabled_groups.json'
influencers_file = 'influencers.json'
templates_file = 'templates.json'
message_ids_file = 'message_ids.json'
admins_file = 'admins.json'
bot = telebot.TeleBot(bot_token)
def twitter_scraper():
with open('influencers.json', 'r') as json_file:
usernames = json.load(json_file)
n_tweets = 20
time_limit = datetime.datetime.now(
pytz.utc) - datetime.timedelta(minutes=5)
all_tweets_data = {}
for username in usernames:
tweets_data = []
scraper = sntwitter.TwitterUserScraper(username)
for i, tweet in tqdm(enumerate(scraper.get_items()), total=n_tweets):
if tweet.date.replace(tzinfo=pytz.UTC) < time_limit:
break
data = {
"id": tweet.id,
"url": tweet.url,
"username": username
}
tweets_data.append(data)
if i + 1 >= n_tweets:
break
obj_data = {
"tweets": tweets_data
}
all_tweets_data[username] = tweets_data
with open('tweets-data.json', "w") as json_file:
json.dump(all_tweets_data, json_file)
# Send Tweets
if not all_tweets_data: # Check if no tweets are available for any username
print("No tweets available.")
return
print("Preparing Tweets...........")
with open('tweets-data.json', 'r') as file:
data = json.load(file)
with open('advertisement.json', 'r', encoding='utf-8-sig') as ads_file:
ads_data = json.loads(ads_file.read())
random_ad = random.choice(ads_data["adsList"])
templates = load_templates()
enabled_groups = load_enabled_groups()
for chat_id, group_info in enabled_groups.items():
chat_id_str = str(chat_id)
if chat_id_str in templates:
template_text = templates[chat_id_str]["template_text"]
else:
template_text = ""
if group_info.get("enabled", False):
ad_message = f"Ad: [{random_ad['text']}]({random_ad['link']})"
title = "🚀 Let's Raid these new tweets\n\n"
message = ""
for name, profiles in data.items():
for profile in profiles:
if 'id' in profile and 'username' in profile:
url = "https://twitter.com/intent/tweet?text=" + \
str(template_text) + "&in_reply_to=" + \
str(profile['id'])
username = profile['username']
message += f"[{username}]({url}) || "
message = message.rstrip(" || ")
# Empty Message
if not message:
print("No tweets available.")
continue
combined_message = title + message + '\n\n' + ad_message
print(combined_message)
print("Sending Tweets...........")
send_message_with_link(chat_id, combined_message)
else:
print(f"Group {chat_id} is disabled. Skipping...")
print("---------------Tweets Sent! --------------")
def load_enabled_groups():
try:
with open(enabled_groups_file, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_enabled_groups(enabled_groups):
with open(enabled_groups_file, 'w') as file:
json.dump(enabled_groups, file)
def load_influencers():
try:
with open(influencers_file, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_influencers(influencers):
with open(influencers_file, 'w') as file:
json.dump(influencers, file)
def load_templates():
try:
with open(templates_file, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_templates(templates):
with open(templates_file, 'w') as file:
json.dump(templates, file)
def load_admins():
try:
with open('admins.json', 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return {}
admins = load_admins()
def load_selected_group():
try:
with open('selected_groups.json', 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return {}
selected_groups = load_selected_group()
def save_admins(admins):
with open('admins.json', 'w') as file:
json.dump(admins, file)
def is_group_admin(message: telebot.types.Message):
user_id = message.from_user.id
chat_member = bot.get_chat_member(message.chat.id, user_id)
name = chat_member.user.username
print(name)
if chat_member.status in ['administrator', 'creator']:
return True
@bot.message_handler(commands=['enable'])
def enable_bot_messages(message: telebot.types.Message):
if message.chat.type == 'private':
username = message.from_user.username
group = selected_groups.get(username)
enabled_groups = load_enabled_groups()
if group:
group_id = group['group_id']
if group_id in enabled_groups:
enabled_groups[group_id]['enabled'] = True
else:
enabled_groups[group_id] = {
'name': group['group_name'],
'enabled': True
}
with open('enabled_groups.json', 'w') as file:
json.dump(enabled_groups, file)
bot.send_message(
message.chat.id,
'Bot messages enabled for the selected group.'
)
else:
bot.send_message(
message.chat.id,
'No group selected. Use the /start command to select a group first.'
)
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
admins = load_admins()
chat_id = str(message.chat.id)
admin_username = message.from_user.username
print(chat_id)
if admin_username not in admins:
admins[admin_username] = {}
if chat_id not in admins[admin_username]:
admins[admin_username][chat_id] = {
'group_name': message.chat.title, # Store the group name
'group_id': chat_id
}
save_admins(admins)
chat_id = message.chat.id
enabled_groups = load_enabled_groups()
enabled_groups[str(chat_id)] = {
'name': message.chat.title, # Store the group name
'enabled': True
}
save_enabled_groups(enabled_groups)
bot.reply_to(message, "Bot messages enabled.")
@bot.message_handler(commands=['disable'])
def disable_bot_messages(message: telebot.types.Message):
if message.chat.type == 'private':
username = message.from_user.username
group = selected_groups.get(username)
enabled_groups = load_enabled_groups()
if group:
group_id = group['group_id']
if group_id in enabled_groups:
enabled_groups[group_id]['enabled'] = False
else:
enabled_groups[group_id] = {
'name': group['group_name'],
'enabled': False
}
with open('enabled_groups.json', 'w') as file:
json.dump(enabled_groups, file)
bot.send_message(
message.chat.id,
'Bot messages disabled for the selected group.'
)
else:
bot.send_message(
message.chat.id,
'No group selected. Use the /start command to select a group first.'
)
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
chat_id = message.chat.id
enabled_groups = load_enabled_groups()
enabled_groups[str(chat_id)] = {
'name': message.chat.title, # Store the group name
'enabled': False
}
save_enabled_groups(enabled_groups)
bot.reply_to(message, "Bot messages disabled.")
@bot.message_handler(commands=['add_influencer'])
def add_influencer(message: telebot.types.Message):
selected_groups = load_selected_group()
username = message.from_user.username
if message.chat.type == 'private':
group = selected_groups.get(username)
if not group:
bot.reply_to(message, "No group selected. Use the /start command to select a group first.")
return
chat_id = group['group_id']
influencer_name = ' '.join(message.text.split()[1:]).strip()
if influencer_name:
influencers = load_influencers()
if influencer_name in influencers:
bot.reply_to(message, f"Influencer '{influencer_name}' already exists.")
else:
influencers.append(influencer_name)
save_influencers(influencers)
bot.reply_to(message, f"Influencer '{influencer_name}' added successfully. ✅")
else:
bot.reply_to(message, "Please provide the name of the influencer.")
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
influencer_name = ' '.join(message.text.split()[1:]).strip()
if influencer_name:
influencers = load_influencers()
if influencer_name in influencers:
bot.reply_to(message, f"Influencer '{influencer_name}' already exists.")
else:
influencers.append(influencer_name)
save_influencers(influencers)
bot.reply_to(message, f"Influencer '{influencer_name}' added successfully. ✅")
else:
bot.reply_to(message, "Please provide the name of the influencer.")
@bot.message_handler(commands=['view_influencers'])
def view_influencers(message: telebot.types.Message):
selected_groups = load_selected_group()
username = message.from_user.username
if message.chat.type == 'private':
group = selected_groups.get(username)
if not group:
bot.reply_to(message, "No group selected. Use the /start command to select a group first.")
return
chat_id = group['group_id']
influencers = load_influencers()
if influencers:
influencers_list = '\n'.join(influencers)
bot.reply_to(message, f"List of influencers:\n{influencers_list}")
else:
bot.reply_to(message, "No influencers found.")
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
influencers = load_influencers()
if influencers:
influencers_list = '\n'.join(influencers)
bot.reply_to(message, f"List of influencers:\n{influencers_list}")
else:
bot.reply_to(message, "No influencers found.")
@bot.message_handler(commands=['set_template'])
def set_template(message: telebot.types.Message):
selected_groups = load_selected_group()
username = message.from_user.username
if message.chat.type == 'private':
group = selected_groups.get(username)
if not group:
bot.reply_to(message, "No group selected. Use the /start command to select a group first.")
return
chat_id = group['group_id']
template_text = ' '.join(message.text.split()[1:])
chat = bot.get_chat(chat_id)
group_name = chat.title if chat.title else "Unknown Group"
if template_text:
templates = load_templates()
templates[chat_id] = {
"group_name": group_name,
"username": username,
"template_text": template_text
}
save_templates(templates)
bot.reply_to(message, "Template set successfully for the selected group.")
else:
templates = load_templates()
templates[chat_id] = {
"group_name": group_name,
"username": username,
"template_text": ""
}
save_templates(templates)
bot.reply_to(message, "Empty template set Success for the selected group!.")
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
chat_id = str(message.chat.id)
username = message.from_user.username
template_text = ' '.join(message.text.split()[1:])
if template_text:
templates = load_templates()
templates[chat_id] = {
"group_name": message.chat.title,
"username": username,
"template_text": template_text
}
save_templates(templates)
bot.reply_to(message, "Template set successfully.")
else:
templates = load_templates()
templates[chat_id] = {
"group_name": message.chat.title,
"username": username,
"template_text": ""
}
save_templates(templates)
bot.reply_to(message, "Empty template set Success!.")
@bot.message_handler(commands=['view_templates'])
def view_templates(message: telebot.types.Message):
selected_groups = load_selected_group()
username = message.from_user.username
if message.chat.type == 'private':
group = selected_groups.get(username)
if not group:
bot.reply_to(message, "No group selected. Use the /start command to select a group first.")
return
chat_id = group['group_id']
templates = load_templates()
template_data = None
for newid, data in templates.items():
group_name = data.get("group_name")
if newid == chat_id or group_name == message.chat.title:
template_data = data
break
if template_data:
template_text = template_data.get("template_text")
bot.reply_to(message, f"Template:\n{template_text}")
else:
bot.reply_to(message, "No template found for this group.")
else:
if not is_group_admin(message):
bot.reply_to(message, "You are not an admin.")
return
username = message.from_user.username
chat_id = str(message.chat.id)
print(chat_id)
templates = load_templates()
template_data = None
for newid, data in templates.items():
group_name = data.get("group_name")
if newid == chat_id or group_name == message.chat.title:
template_data = data
break
if template_data:
template_text = template_data.get("template_text")
bot.reply_to(message, f"Template:\n{template_text}")
else:
bot.reply_to(message, "No template found for this group.")
def send_message_with_link(chat_id, message):
message_id = get_saved_message_id(chat_id)
if message_id:
# Delete the previous message
bot.delete_message(chat_id, message_id)
# Send the new message
sent_message = bot.send_message(
chat_id, message, parse_mode='Markdown', disable_web_page_preview=True)
# Retrieve the message ID
message_id = sent_message.message_id
# Save the message ID for future use
save_message_id(chat_id, message_id)
return message_id
def delete_previous_message(chat_id):
# Retrieve the saved message ID
message_id = get_saved_message_id(chat_id)
if message_id:
# Delete the previous message
bot.delete_message(chat_id, message_id)
def save_message_id(chat_id, message_id):
# Load the existing message IDs from JSON
message_ids = load_message_ids()
# Update the message ID for the chat ID
message_ids[str(chat_id)] = message_id
# Save the updated message IDs to JSON
save_message_ids(message_ids)
def get_saved_message_id(chat_id):
# Load the existing message IDs from JSON
message_ids = load_message_ids()
# Retrieve the message ID for the chat ID
return message_ids.get(str(chat_id))
def load_message_ids():
try:
with open(message_ids_file, 'r') as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_message_ids(message_ids):
with open(message_ids_file, 'w') as file:
json.dump(message_ids, file)
# Function to run the Twitter scraper repeatedly
def run_twitter_scraper():
schedule.every(5).minutes.do(twitter_scraper)
while True:
schedule.run_pending()
time.sleep(1)
# Handle the '/start' command
@bot.message_handler(commands=['start'])
def handle_start_command(message):
username = message.from_user.username
if message.chat.type == 'private':
if username in admins:
admin_details = admins[username]
# Create a keyboard markup to display the available groups
markup = telebot.types.ReplyKeyboardMarkup(row_width=1, one_time_keyboard=True)
for group_id, group_details in admin_details.items():
if group_id != 'group_name' and group_id != 'group_id':
group_name = group_details['group_name']
markup.add(telebot.types.KeyboardButton(group_name))
bot.send_message(
message.chat.id,
'Select a group:',
reply_markup=markup
)
else:
bot.send_message(
message.chat.id,
'You are not authorized to use this bot.'
)
# Handle group selection
@bot.message_handler(func=lambda message: message.chat.type == 'private')
def handle_group_selection(message):
username = message.from_user.username
selected_group_name = message.text
if username in admins:
admin_groups = admins[username]
selected_group = None
for group_id, group_details in admin_groups.items():
if group_details['group_name'] == selected_group_name:
selected_group = {
'group_name': group_details['group_name'],
'group_id': group_id
}
break
if selected_group:
selected_groups[username] = selected_group
with open('selected_groups.json', 'w') as file:
json.dump(selected_groups, file)
bot.send_message(
message.chat.id,
f'Success! Selected group: {selected_group["group_name"]}'
)
else:
bot.send_message(
message.chat.id,
'Invalid group selection.'
)
else:
bot.send_message(
message.chat.id,
'You are not authorized to use this bot.'
)
# Create a thread for running the Twitter scraper
twitter_thread = threading.Thread(target=run_twitter_scraper)
twitter_thread.start()
bot.polling(none_stop=True, timeout=123)