Repository navigation
Expand file tree
/
Copy pathload_bot_stable.py
More file actions
354 lines (300 loc) · 15 KB
/
Copy pathload_bot_stable.py
File metadata and controls
354 lines (300 loc) · 15 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
from telegram import Update, InputFile
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import random
import datetime
import asyncio
import nest_asyncio
# R U L E S
# -> event name: no spaces
# -> prize name: at least 1 space
# Apply nest_asyncio to handle already-running event loop
nest_asyncio.apply()
# Database to store eligible users and users who submitted proof
eligible_users = set()
users_submitted_proof = {}
giveaway_end_time = None
giveaway_event_name = None
giveaway_prize = None
admin_chat_id = 598430947 # Set the admin chat ID here
# Handler to start the bot and explain rules
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message:
if giveaway_prize and giveaway_end_time:
rules = (
f"Привет! 🤗 Это чат-бот для гива от @vitaly.ph\n"
f"Выполни задание и получи возможность выиграть {giveaway_prize} 🎁.\n"
f"Гив закончится {giveaway_end_time.strftime('%Y-%m-%d %H:%M')}.\n"
"Вот что нужно сделать:\n"
"1. Сделай репост ХХХ к себе в стори и подпишись на меня.\n"
"2. Отправь боту скриншот с твоей стори.\n"
"3. Как только мы убедимся что все правильно, ты попоадешь в список претендентов на приз.\n\n"
"Удачи! 🤞 (Победитель будет вытянут рандомно)"
)
else:
rules = (
"Привет! 🤗 Это чат-бот для гива от @vitaly.ph\n"
"В данный момент гив не проводится ✋.\n"
"Следи за апдейтами в инстаграме!."
)
await update.message.reply_text(rules)
# Admin command to create a new giveaway
async def new_giveaway(update: Update, context: ContextTypes.DEFAULT_TYPE):
global eligible_users, users_submitted_proof, giveaway_end_time, giveaway_event_name, giveaway_prize
if giveaway_end_time and datetime.datetime.now() < giveaway_end_time:
await update.message.reply_text("An event is already ongoing. Please finish the current event before starting a new one.")
return
if update.message:
args = context.args
print(f"Received args: {args}") # Debug print to check the arguments
if len(args) < 5:
await update.message.reply_text("Usage: /new_giveaway <event_name> <prize> <end_date YYYY-MM-DD> <end_time HH:MM>")
return
giveaway_event_name = args[0]
prize_and_date = " ".join(args[1:])
prize_end_date_split = prize_and_date.rsplit(' ', 2)
if len(prize_end_date_split) != 3:
await update.message.reply_text("Invalid format. Use: /new_giveaway <event_name> <prize> <end_date YYYY-MM-DD> <end_time HH:MM>")
return
giveaway_prize = prize_end_date_split[0]
datetime_str = f"{prize_end_date_split[1]} {prize_end_date_split[2]}"
try:
giveaway_end_time = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
await update.message.reply_text("Invalid datetime format. Use YYYY-MM-DD HH:MM.")
return
eligible_users.clear()
users_submitted_proof.clear()
await update.message.reply_text(f"New giveaway created: {giveaway_event_name} for {giveaway_prize}, ending at {giveaway_end_time}")
# Start the task to check for giveaway end time
context.application.create_task(check_giveaway_end(context))
# Asynchronous task to check for giveaway end time
async def check_giveaway_end(context: ContextTypes.DEFAULT_TYPE):
global giveaway_end_time
while True:
if giveaway_end_time and datetime.datetime.now() >= giveaway_end_time:
await notify_giveaway_end(context)
break
await asyncio.sleep(60) # Check every minute
# Notify admin and users that the giveaway is over
async def notify_giveaway_end(context: ContextTypes.DEFAULT_TYPE):
global giveaway_end_time
# Check if there are any eligible verified users
if eligible_users:
winner_id = random.choice(list(eligible_users))
eligible_users.clear() # Reset for the next giveaway
# Notify the winner
await context.bot.send_message(
chat_id=winner_id,
text="Congratulations! You have won the giveaway!"
)
# Notify the admin with the winner and user list
if admin_chat_id:
user_list = "\n".join(f"User ID: {user_id}, IG Handle: {data['ig_handle']}, Verified: {data['verified']}" for user_id, data in users_submitted_proof.items())
await context.bot.send_message(
admin_chat_id,
text=f"The giveaway is over with {len(users_submitted_proof)} participants.\nParticipants:\n{user_list}\n\nThe winner is User ID: {winner_id}"
)
# Notify all users
for user_id in users_submitted_proof:
await context.bot.send_message(
chat_id=user_id,
text="The giveaway is over. Thank you for participating!"
)
else:
# Notify the admin that there are no eligible verified users
if admin_chat_id:
user_list = "\n".join(f"User ID: {user_id}, IG Handle: {data['ig_handle']}, Verified: {data['verified']}" for user_id, data in users_submitted_proof.items())
await context.bot.send_message(
admin_chat_id,
text=f"The giveaway is over with {len(users_submitted_proof)} participants.\nParticipants:\n{user_list}\n\nThere are no eligible verified users. Please verify users and draw the winner."
)
# Notify all users to standby for the results
for user_id in users_submitted_proof:
await context.bot.send_message(
chat_id=user_id,
text="The giveaway is over. Standby for the results."
)
# Reset giveaway end time
giveaway_end_time = None
# Handler to process user-uploaded files
async def receive_proof(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message and (update.message.photo or update.message.document):
user_id = update.message.from_user.id
username = update.message.from_user.username
# Save proof for manual verification
file = update.message.photo[-1] if update.message.photo else update.message.document
file_id = file.file_id
new_file = await context.bot.get_file(file_id)
file_path = f"proof_{user_id}.jpg"
await new_file.download_to_drive(file_path)
# Store file link in user data
context.user_data['file_link'] = new_file.file_path
# Ask for Instagram handle
await update.message.reply_text("Please send your Instagram handle.")
context.user_data['awaiting_ig_handle'] = True
else:
if update.message:
await update.message.reply_text(
"Please send a valid screenshot as proof."
)
# Handler to receive Instagram handle
async def receive_ig_handle(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data.get('awaiting_ig_handle'):
user_id = update.message.from_user.id
ig_handle = update.message.text
# Add user ID and Instagram handle to the set of users who submitted proof
users_submitted_proof[user_id] = {'ig_handle': ig_handle, 'verified': False}
context.user_data['awaiting_ig_handle'] = False
# Notify user of manual verification
await update.message.reply_text(
"Thank you! Your proof and Instagram handle have been received and will be manually verified."
)
# Notify admin for manual check
if admin_chat_id:
file_link = context.user_data.get('file_link')
await context.bot.send_message(
admin_chat_id, f"New proof submitted by @{ig_handle} (ID: {user_id}). File link: {file_link}"
)
# Admin command to verify a user
async def verify_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message:
args = context.args
if len(args) != 1:
await update.message.reply_text("Usage: /verify <user_id>")
return
user_id = args[0]
try:
user_id = int(user_id)
eligible_users.add(user_id)
if user_id in users_submitted_proof:
users_submitted_proof[user_id]['verified'] = True
await update.message.reply_text(f"User {user_id} has been added to the draw.")
# Notify user of verification
await context.bot.send_message(
chat_id=user_id,
text="Your entry has been verified and you are now eligible for the prize!"
)
except ValueError:
await update.message.reply_text("Invalid user ID.")
# Command to set giveaway end time
async def set_end_time(update: Update, context: ContextTypes.DEFAULT_TYPE):
global giveaway_end_time
if update.message:
args = context.args
print(f"Received args: {args}") # Debug print to check the arguments
if len(args) != 2:
await update.message.reply_text("Usage: /set_end_time <YYYY-MM-DD HH:MM>")
return
try:
datetime_str = f"{args[0]} {args[1]}"
giveaway_end_time = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
await update.message.reply_text(
f"Giveaway end time set to {giveaway_end_time.strftime('%Y-%m-%d %H:%M')}"
)
except ValueError:
await update.message.reply_text("Invalid datetime format. Use YYYY-MM-DD HH:MM.")
# Command to draw a winner
async def draw_winner(update: Update, context: ContextTypes.DEFAULT_TYPE):
global giveaway_end_time
if update.message:
if giveaway_end_time:
await update.message.reply_text("The giveaway is not over yet.")
return
if not eligible_users:
await update.message.reply_text("No eligible participants for the draw.")
return
winner_id = random.choice(list(eligible_users))
eligible_users.clear() # Reset for the next giveaway
await update.message.reply_text(f"Congratulations! The winner is User ID: {winner_id}")
# Notify the winner
await context.bot.send_message(
chat_id=winner_id,
text="Congratulations! You have won the giveaway!"
)
# Notify the admin
if admin_chat_id:
user_list = "\n".join(f"User ID: {user_id}, IG Handle: {data['ig_handle']}, Verified: {data['verified']}" for user_id, data in users_submitted_proof.items())
await context.bot.send_message(
admin_chat_id,
text=f"The giveaway is over with {len(users_submitted_proof)} participants.\nParticipants:\n{user_list}\n\nThe winner is User ID: {winner_id}"
)
# Notify all users
for user_id in users_submitted_proof:
await context.bot.send_message(
chat_id=user_id,
text="The giveaway is over. Thank you for participating!"
)
# Command to manually finish the event
async def finish_event(update: Update, context: ContextTypes.DEFAULT_TYPE):
global giveaway_end_time
if update.message:
if not eligible_users:
await update.message.reply_text("No eligible participants for the draw.")
return
winner_id = random.choice(list(eligible_users))
eligible_users.clear() # Reset for the next giveaway
await update.message.reply_text(f"Congratulations! The winner is User ID: {winner_id}")
# Notify the winner
await context.bot.send_message(
chat_id=winner_id,
text="Congratulations! You have won the giveaway!"
)
# Notify the admin
if admin_chat_id:
user_list = "\n".join(f"User ID: {user_id}, IG Handle: {data['ig_handle']}, Verified: {data['verified']}" for user_id, data in users_submitted_proof.items())
await context.bot.send_message(
admin_chat_id,
text=f"The giveaway is over with {len(users_submitted_proof)} participants.\nParticipants:\n{user_list}\n\nThe winner is User ID: {winner_id}"
)
# Notify all users
for user_id in users_submitted_proof:
await context.bot.send_message(
chat_id=user_id,
text="The giveaway is over. Thank you for participating!"
)
# Command to list all users who submitted proof
async def list_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message:
if users_submitted_proof:
user_list = "\n".join(f"User ID: {user_id}, IG Handle: {data['ig_handle']}, Verified: {data['verified']}" for user_id, data in users_submitted_proof.items())
await update.message.reply_text(f"Users who submitted proof:\n{user_list}")
else:
await update.message.reply_text("No users have submitted proof yet.")
# Error handler
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(
chat_id=admin_chat_id,
text=f"An error occurred: {context.error}"
)
# Main function to run the bot
async def main():
global admin_chat_id
TOKEN = "7134307129:AAG90N3JMwWBJBIaPD6FUb4_vGcCJnkJ2Co"
admin_chat_id = 598430947 # Replace with the actual admin chat ID
app = Application.builder().token(TOKEN).build()
# Add handlers
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("new_giveaway", new_giveaway)) # Add the new giveaway command handler
app.add_handler(MessageHandler(filters.PHOTO | filters.Document.ALL, receive_proof))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, receive_ig_handle)) # Add handler for receiving IG handle
app.add_handler(CommandHandler("verify", verify_user))
app.add_handler(CommandHandler("set_end_time", set_end_time))
app.add_handler(CommandHandler("draw_winner", draw_winner))
app.add_handler(CommandHandler("finish_event", finish_event)) # Add the new finish event command handler
app.add_handler(CommandHandler("list_users", list_users)) # Add the new command handler
# Error handling
app.add_error_handler(error_handler)
# Run the bot
print("Bot is running...")
await app.run_polling()
if __name__ == "__main__":
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
except RuntimeError as e:
# Handle already-running event loop
if str(e) == "This event loop is already running":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
else:
raise