Karan Adhikari commited on
Commit
bd22308
·
unverified ·
1 Parent(s): 97d25f1

Delete Backend/pyrofork/subscription_plugins directory

Browse files
Backend/pyrofork/subscription_plugins/start.py DELETED
@@ -1,98 +0,0 @@
1
- from pyrogram import filters, Client, enums
2
- from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
3
- from Backend.config import Telegram
4
- from Backend import db
5
- from datetime import datetime
6
-
7
- print("DEBUG: Subscription Bot start.py PLUGIN LOADED SUCCESSFULLY!")
8
-
9
- @Client.on_message(filters.command('start'), group=10)
10
- async def send_start_message(client: Client, message: Message):
11
- try:
12
- user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
13
- print(f"DEBUG: Subscription Bot received /start command from {user_id}")
14
-
15
- base_url = Telegram.BASE_URL
16
- addon_url = f"{base_url}/stremio/manifest.json"
17
-
18
- # If subscriptions are NOT enabled
19
- if not Telegram.SUBSCRIPTION:
20
- # Generate or fetch API token for free user
21
- user_name = (message.from_user.first_name or message.from_user.username or f"User {user_id}") if message.from_user else f"Chat {user_id}"
22
- try:
23
- # Ensure user gets a token
24
- token_doc = await db.add_api_token(name=user_name, user_id=user_id)
25
- token_str = token_doc.get("token")
26
- addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
27
- except Exception as e:
28
- print(f"DEBUG: Error ensuring token for free user: {e}")
29
-
30
- await message.reply_text(
31
- '🎉 <b>Welcome to the Telegram Stremio Media Server!</b>\n\n'
32
- 'Here is your personal Stremio Addon link:\n\n'
33
- '🎬 <b>Stremio Addon — Install Link:</b>\n'
34
- f'<code>{addon_url}</code>\n\n'
35
- 'Tap the link above → <b>Install</b> in Stremio to start watching!',
36
- quote=True,
37
- parse_mode=enums.ParseMode.HTML
38
- )
39
- return
40
-
41
- # Subscription logic (When SUBSCRIPTION=True)
42
- user = await db.get_user(user_id)
43
- now = datetime.utcnow()
44
-
45
- # Check if user has an active subscription
46
- is_active = False
47
- if user and user.get("subscription_status") == "active":
48
- if user.get("subscription_expiry") and user.get("subscription_expiry") > now:
49
- is_active = True
50
- else:
51
- await db.mark_user_expired(user_id)
52
-
53
- if not is_active:
54
- plans = await db.get_subscription_plans()
55
- if not plans:
56
- return await message.reply_text(
57
- '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
58
- 'Currently, no subscription plans are set up. Please contact the administrator.',
59
- quote=True,
60
- parse_mode=enums.ParseMode.HTML
61
- )
62
-
63
- keyboard_buttons = []
64
- for plan in plans:
65
- keyboard_buttons.append([InlineKeyboardButton(f"{plan['days']} Days - ₹{plan['price']}", callback_data=f"plan_{plan['_id']}")])
66
-
67
- keyboard = InlineKeyboardMarkup(keyboard_buttons)
68
-
69
- return await message.reply_text(
70
- '<b>Welcome to the Telegram Stremio Private Group!</b>\n\n'
71
- 'Access to the Stremio Addon requires an active subscription.\n'
72
- 'Please select a subscription plan below to continue:',
73
- reply_markup=keyboard,
74
- quote=True,
75
- parse_mode=enums.ParseMode.HTML
76
- )
77
-
78
- # User is active, fetch their token
79
- all_tokens = await db.get_all_api_tokens()
80
- token_doc = next((t for t in all_tokens if t.get("user_id") == user_id), None)
81
-
82
- if token_doc and "token" in token_doc:
83
- token_str = token_doc["token"]
84
- addon_url = f"{base_url}/stremio/{token_str}/manifest.json"
85
-
86
- await message.reply_text(
87
- '🎉 <b>Welcome back to the Telegram Stremio Subscription Manager!</b>\n\n'
88
- 'Your subscription is active. Here is your personal addon link:\n\n'
89
- '🎬 <b>Stremio Addon — Install Link:</b>\n'
90
- f'<code>{addon_url}</code>\n\n'
91
- 'Tap the link above → <b>Install</b> in Stremio to start watching!',
92
- quote=True,
93
- parse_mode=enums.ParseMode.HTML
94
- )
95
-
96
- except Exception as e:
97
- await message.reply_text(f"⚠️ Error: {e}")
98
- print(f"Error in Subscription Bot /start handler: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Backend/pyrofork/subscription_plugins/subscription.py DELETED
@@ -1,377 +0,0 @@
1
- from pyrogram import Client, filters
2
- from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
3
- from Backend.config import Telegram
4
- from Backend import db
5
- from datetime import datetime, timedelta
6
- import asyncio
7
-
8
- from bson.objectid import ObjectId
9
-
10
- @Client.on_callback_query(filters.regex(r"^plan_([a-fA-F0-9]{24})$"))
11
- async def plan_selection(client: Client, callback_query: CallbackQuery):
12
- if not Telegram.SUBSCRIPTION:
13
- return await callback_query.answer("Subscriptions are not enabled.", show_alert=True)
14
-
15
- plan_id = callback_query.matches[0].group(1)
16
-
17
- plans = await db.get_subscription_plans()
18
- plan = next((p for p in plans if p["_id"] == plan_id), None)
19
-
20
- if not plan:
21
- return await callback_query.answer("Invalid plan.", show_alert=True)
22
-
23
- duration = plan["days"]
24
- await callback_query.answer()
25
-
26
- user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
27
- first_name = callback_query.from_user.first_name if callback_query.from_user else callback_query.message.chat.title
28
- username = callback_query.from_user.username if callback_query.from_user else callback_query.message.chat.username
29
-
30
- # Store initial user interaction if needed
31
- await db.update_user_interaction(user_id, first_name, username)
32
-
33
- # Calculate expiry
34
- user = await db.get_user(user_id)
35
- now = datetime.utcnow()
36
- current_expiry = user.get("subscription_expiry") if user else None
37
-
38
- if current_expiry and current_expiry > now:
39
- new_expiry = current_expiry + timedelta(days=int(duration))
40
- else:
41
- new_expiry = now + timedelta(days=int(duration))
42
-
43
- expiry_str = new_expiry.strftime("%Y-%m-%d %H:%M UTC")
44
-
45
- text = (
46
- f"<b>✅ Plan Selected: {plan['days']} Days</b>\n\n"
47
- f"<b>💰 Price:</b> ₹{plan['price']}\n"
48
- f"<b>📅 Expiry (if approved now):</b> {expiry_str}\n\n"
49
- f"<b>📋 Payment Instructions:</b>\n"
50
- f"1. Pay ₹{plan['price']} to the admin.\n"
51
- f"2. <b>Send your payment screenshot directly here (in this chat)</b>.\n"
52
- f" The admin will review and activate your subscription."
53
- )
54
-
55
- # Set pending payment state (price stored for admin display)
56
- await db.set_pending_payment(user_id, int(duration), 0, price=plan.get("price", 0))
57
-
58
- # Add cancel button
59
- keyboard = InlineKeyboardMarkup([
60
- [InlineKeyboardButton("❌ Cancel", callback_data="cancel_payment")]
61
- ])
62
-
63
- dm_sent = False
64
- try:
65
- msg = await client.send_message(
66
- chat_id=user_id,
67
- text=text,
68
- reply_markup=keyboard,
69
- )
70
- dm_sent = True
71
-
72
- async def delete_msg(message):
73
- await asyncio.sleep(120)
74
- try:
75
- await message.delete()
76
- except Exception:
77
- pass
78
-
79
- asyncio.create_task(delete_msg(msg))
80
- except Exception as e:
81
- print(f"Could not DM user {user_id}: {e}")
82
-
83
- if dm_sent:
84
- await callback_query.answer("✅ Check your DM for payment instructions!", show_alert=True)
85
- else:
86
- # Fallback: reply in current chat if DM fails (user hasn't started bot)
87
- fallback_msg = await callback_query.message.reply_text(
88
- text + "\n\n⚠️ <i>Please start a DM with the bot first by clicking its username, then send your screenshot there.</i>",
89
- reply_markup=keyboard,
90
- quote=True,
91
- )
92
- await callback_query.answer()
93
-
94
- async def delete_msg(message):
95
- await asyncio.sleep(120)
96
- try:
97
- await message.delete()
98
- except Exception:
99
- pass
100
-
101
- asyncio.create_task(delete_msg(fallback_msg))
102
-
103
- @Client.on_callback_query(filters.regex(r"^cancel_payment$"))
104
- async def cancel_payment_handler(client: Client, callback_query: CallbackQuery):
105
- user_id = callback_query.from_user.id if callback_query.from_user else callback_query.message.chat.id
106
-
107
- # Remove pending payment
108
- await db.reject_payment(user_id)
109
-
110
- await callback_query.answer("Payment process cancelled.", show_alert=True)
111
- try:
112
- await callback_query.message.delete()
113
- except Exception:
114
- pass
115
-
116
-
117
- @Client.on_message(filters.photo & filters.private)
118
- async def handle_payment_screenshot(client: Client, message: Message):
119
- if not Telegram.SUBSCRIPTION:
120
- return
121
-
122
- # Safely resolve sender ID
123
- sender_id = (message.from_user.id if message.from_user else None) \
124
- or (message.sender_chat.id if message.sender_chat else None) \
125
- or message.chat.id
126
-
127
- try:
128
- print(f"DEBUG: handle_payment_screenshot triggered by {sender_id}")
129
- # Check if user has a pending payment request
130
- user = await db.get_user(sender_id)
131
- print(f"DEBUG: user from DB = {user}")
132
- if not user or "pending_payment" not in user:
133
- # No active payment flow - tell the user what to do
134
- print(f"DEBUG: No pending_payment found for {sender_id}")
135
- await message.reply_text(
136
- "ℹ️ We received your photo, but you don't have an active payment request.\n\n"
137
- "Please use /start to select a subscription plan first, then send your payment screenshot.",
138
- quote=True
139
- )
140
- return
141
-
142
- pending = user["pending_payment"]
143
- duration = pending.get("duration", "?")
144
- price = pending.get("price", "?")
145
-
146
- # --- Admin notification ---
147
- keyboard = InlineKeyboardMarkup([
148
- [
149
- InlineKeyboardButton("✅ Approve", callback_data=f"approve_{sender_id}"),
150
- InlineKeyboardButton("❌ Reject", callback_data=f"reject_{sender_id}")
151
- ]
152
- ])
153
-
154
- user_mention = message.from_user.mention if message.from_user else f"User {sender_id}"
155
- username_str = f"@{message.from_user.username}" if (message.from_user and message.from_user.username) else "N/A"
156
-
157
- admin_text = (
158
- f"<b>💰 New Payment Screenshot Received</b>\n\n"
159
- f"<b>👤 User:</b> {user_mention}\n"
160
- f"<b>🆔 User ID:</b> <code>{sender_id}</code>\n"
161
- f"<b>🔗 Username:</b> {username_str}\n\n"
162
- f"<b>📦 Plan Details:</b>\n"
163
- f" • Duration: <b>{duration} days</b>\n"
164
- f" • Price: <b>₹{price}</b>\n\n"
165
- f"Please review the screenshot above and approve or reject."
166
- )
167
-
168
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
169
- admin_messages = []
170
- for approver_id in approver_ids:
171
- try:
172
- sent = await message.copy(approver_id, caption=admin_text, reply_markup=keyboard)
173
- admin_messages.append({"chat_id": approver_id, "message_id": sent.id})
174
- except Exception as e:
175
- print(f"Failed to forward screenshot to approver {approver_id}: {e}")
176
-
177
- # Update pending state with screenshot message ID + all admin message IDs
178
- await db.set_pending_payment(sender_id, duration, message.id, price=price,
179
- admin_messages=admin_messages)
180
-
181
- if admin_messages:
182
- await message.reply_text(
183
- "✅ <b>Screenshot Received!</b>\n\n"
184
- "Your payment screenshot has been forwarded to the admin for review.\n"
185
- "You will be notified once it's approved. Thank you! 🙏",
186
- quote=True
187
- )
188
- else:
189
- await message.reply_text(
190
- "⚠️ Your screenshot was received but we could not reach the admin. "
191
- "Please contact the admin directly.",
192
- quote=True
193
- )
194
-
195
- except Exception as e:
196
- print(f"Error in handle_payment_screenshot: {e}")
197
- await message.reply_text(
198
- f"⚠️ Something went wrong while processing your screenshot. Please try again or contact the admin.\n\nError: {e}",
199
- quote=True
200
- )
201
-
202
-
203
- @Client.on_callback_query(filters.regex(r"^(approve|reject)_(\d+)$"))
204
- async def admin_review(client: Client, callback_query: CallbackQuery):
205
- approver_ids = Telegram.APPROVER_IDS if Telegram.APPROVER_IDS else [Telegram.OWNER_ID]
206
- if callback_query.from_user.id not in approver_ids:
207
- return await callback_query.answer("You are not authorized to perform this action.", show_alert=True)
208
-
209
- action = callback_query.matches[0].group(1)
210
- target_user_id = int(callback_query.matches[0].group(2))
211
- acting_admin = callback_query.from_user
212
- admin_name = acting_admin.first_name or acting_admin.username or f"Admin {acting_admin.id}"
213
-
214
- # Fetch admin_messages BEFORE any DB write (approve/reject unsets pending_payment)
215
- user_pre = await db.get_user(target_user_id)
216
- if not user_pre or "pending_payment" not in user_pre:
217
- return await callback_query.answer("This request has already been processed.", show_alert=True)
218
-
219
- admin_messages = user_pre["pending_payment"].get("admin_messages", [])
220
-
221
- if action == "approve":
222
- user_data = await db.approve_payment(target_user_id)
223
- if user_data:
224
- # Generate or retrieve existing API token for this user
225
- try:
226
- user_obj = await db.get_user(target_user_id)
227
- user_name = (user_obj.get("first_name") or user_obj.get("username") or str(target_user_id)) if user_obj else str(target_user_id)
228
- token_doc = await db.add_api_token(name=user_name, user_id=target_user_id)
229
- token_str = token_doc.get("token")
230
- addon_url = f"{Telegram.BASE_URL}/stremio/{token_str}/manifest.json"
231
- except Exception as te:
232
- token_str = None
233
- addon_url = None
234
-
235
- # Generate invite link for the group
236
- try:
237
- invite_link = await client.create_chat_invite_link(
238
- chat_id=Telegram.SUBSCRIPTION_GROUP_ID,
239
- member_limit=1,
240
- expire_date=datetime.utcnow() + timedelta(days=1)
241
- )
242
- invite_text = f"\n\n🔗 <b>Group Invite:</b> {invite_link.invite_link}"
243
- except Exception:
244
- invite_text = ""
245
-
246
- expiry_str = user_data["subscription_expiry"].strftime("%Y-%m-%d")
247
-
248
- # Build confirmation message for user
249
- success_text = (
250
- f"🎉 <b>Payment Approved!</b>\n\n"
251
- f"Your subscription is now active until <b>{expiry_str}</b>."
252
- f"{invite_text}"
253
- )
254
- if addon_url:
255
- success_text += (
256
- f"\n\n🎬 <b>Stremio Addon — Install Link:</b>\n"
257
- f"<code>{addon_url}</code>\n\n"
258
- f"Tap the link above → <b>Install</b> in Stremio to start watching!"
259
- )
260
-
261
- await client.send_message(target_user_id, success_text)
262
-
263
- # Determine how to format the user/payment info
264
- duration = user_pre["pending_payment"].get("duration", "?")
265
- price = user_pre["pending_payment"].get("price", "?")
266
-
267
- try:
268
- target_user = await client.get_users(target_user_id)
269
- user_mention = target_user.mention
270
- username_str = f"@{target_user.username}" if target_user.username else "N/A"
271
- except Exception:
272
- user_mention = f"User {target_user_id}"
273
- username_str = "N/A"
274
-
275
- info_text = (
276
- f"👤 <b>User:</b> {user_mention}\n"
277
- f"🆔 <b>User ID:</b> <code>{target_user_id}</code>\n"
278
- f"🔗 <b>Username:</b> {username_str}\n\n"
279
- f"📦 <b>Plan:</b> {duration} days (₹{price})"
280
- )
281
-
282
- # Update acting admin's message
283
- status_caption = f"✅ <b>Approved by {admin_name}</b>\n\n{info_text}"
284
- await callback_query.message.edit_caption(status_caption)
285
-
286
- # Update all OTHER admins' copies
287
- acting_msg_id = callback_query.message.id
288
- for am in admin_messages:
289
- if am["message_id"] == acting_msg_id:
290
- continue
291
- try:
292
- await client.edit_message_caption(
293
- chat_id=am["chat_id"],
294
- message_id=am["message_id"],
295
- caption=status_caption
296
- )
297
- except Exception:
298
- pass
299
- else:
300
- await callback_query.answer("Could not approve — no pending payment found.", show_alert=True)
301
-
302
- elif action == "reject":
303
- success = await db.reject_payment(target_user_id)
304
- if success:
305
- await client.send_message(
306
- target_user_id,
307
- "❌ <b>Payment Rejected</b>\n\nYour recent payment submission was rejected by the admin. Please contact the admin or try submitting again."
308
- )
309
-
310
- # Determine how to format the user/payment info
311
- duration = user_pre["pending_payment"].get("duration", "?")
312
- price = user_pre["pending_payment"].get("price", "?")
313
-
314
- try:
315
- target_user = await client.get_users(target_user_id)
316
- user_mention = target_user.mention
317
- username_str = f"@{target_user.username}" if target_user.username else "N/A"
318
- except Exception:
319
- user_mention = f"User {target_user_id}"
320
- username_str = "N/A"
321
-
322
- info_text = (
323
- f"👤 <b>User:</b> {user_mention}\n"
324
- f"🆔 <b>User ID:</b> <code>{target_user_id}</code>\n"
325
- f"🔗 <b>Username:</b> {username_str}\n\n"
326
- f"📦 <b>Plan:</b> {duration} days (₹{price})"
327
- )
328
-
329
- # Update acting admin's message
330
- status_caption = f"❌ <b>Rejected by {admin_name}</b>\n\n{info_text}"
331
- await callback_query.message.edit_caption(status_caption)
332
-
333
- # Update all OTHER admins' copies
334
- acting_msg_id = callback_query.message.id
335
- for am in admin_messages:
336
- if am["message_id"] == acting_msg_id:
337
- continue
338
- try:
339
- await client.edit_message_caption(
340
- chat_id=am["chat_id"],
341
- message_id=am["message_id"],
342
- caption=status_caption
343
- )
344
- except Exception:
345
- pass
346
- else:
347
- await callback_query.answer("Could not reject — no pending payment found.", show_alert=True)
348
-
349
-
350
- @Client.on_message(filters.command("status"))
351
- async def check_status(client: Client, message: Message):
352
- if not Telegram.SUBSCRIPTION:
353
- return
354
-
355
- user_id = (message.from_user.id if message.from_user else None) or (message.sender_chat.id if message.sender_chat else None) or message.chat.id
356
-
357
- user = await db.get_user(user_id)
358
- if not user or user.get("subscription_status") != "active":
359
- return await message.reply_text("You do not have an active subscription.")
360
-
361
- expiry = user.get("subscription_expiry")
362
- if not expiry:
363
- return await message.reply_text("Error retrieving expiry date.")
364
-
365
- now = datetime.utcnow()
366
- if now > expiry:
367
- return await message.reply_text("Your subscription has expired.")
368
-
369
- remaining = expiry - now
370
- days = remaining.days
371
- hours = remaining.seconds // 3600
372
-
373
- await message.reply_text(
374
- f"<b>Subscription Status:</b> Active ✅\n"
375
- f"<b>Expiry Date:</b> {expiry.strftime('%Y-%m-%d %H:%M UTC')}\n"
376
- f"<b>Time Remaining:</b> {days} days and {hours} hours"
377
- )