-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
466 lines (388 loc) · 16.8 KB
/
Copy pathmain.py
File metadata and controls
466 lines (388 loc) · 16.8 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
import asyncio
import discord
from discord.ext import commands, tasks
import os
import sys
import json # Imports me add kar lena
import secrets
from datetime import datetime, timedelta, timezone
import aiohttp
from dotenv import load_dotenv
# Helpers & Database import
import database as db
import utils
import keep_alive
from telemetry import log_exception, send_activity_log, send_master_log
from utils.branding_view import create_branding_view, install_global_branding_enforcer
# Load environment variables
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
# Bot Setup
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.presences = True
async def _dynamic_prefix(bot_instance: commands.Bot, message: discord.Message):
user_id = getattr(getattr(message, "author", None), "id", 0)
guild = getattr(message, "guild", None)
guild_id = getattr(guild, "id", None)
prefixes = await db.get_effective_prefixes(user_id=user_id, guild_id=guild_id)
# Allow guild owner to use no-prefix commands (empty prefix)
try:
if guild and getattr(message.author, "id", None) == getattr(guild, "owner_id", None):
prefixes = [""] + prefixes
except Exception:
pass
return commands.when_mentioned_or(*prefixes)(bot_instance, message)
# 1. Default mentions rule set kar diya: Everyone/Here BLOCK, Users ALLOWED, Roles BLOCK (default)
default_mentions = discord.AllowedMentions(everyone=False, users=True, roles=False)
# 2. 'allowed_mentions' ko bot me pass kar diya (Main Brain Fix)
bot = commands.Bot(
command_prefix=_dynamic_prefix,
intents=intents,
help_command=None,
allowed_mentions=default_mentions
)
install_global_branding_enforcer()
keep_alive.register_bot(bot)
# Store start time for uptime tracking
# Store start time for uptime tracking
bot.start_time = datetime.now()
# RAM Buffer (6k members ke liye memory store)
message_buffer = {}
def _dashboard_telemetry_bridge(payload: dict):
async def _send():
await send_activity_log(
bot,
activity_type=payload.get("activity_type", "Dashboard Activity"),
details=payload.get("details", "Dashboard event recorded."),
module=payload.get("module", "Web Dashboard"),
guild=None,
user=None,
jump_url=payload.get("path"),
fields=[
("Endpoint", str(payload.get("path", "Unknown")), True),
("Method", str(payload.get("method", "Unknown")), True),
("Source IP", str(payload.get("ip", "Unknown")), True),
*list(payload.get("fields", [])),
],
)
try:
if bot.loop and bot.loop.is_running():
asyncio.run_coroutine_threadsafe(_send(), bot.loop)
except Exception:
pass
keep_alive.register_telemetry_handler(_dashboard_telemetry_bridge)
KEEPALIVE_URL = "https://deepdey.onrender.com/"
# =========================================================
# QLYNK Production™ Custom Rich Activity Setup
# =========================================================
async def set_qlynk_activity():
# 1. Real-time Uptime (Hours:Minutes:Seconds) calculate karna
uptime_str = "00:00:00"
if getattr(bot, "start_time", None):
delta = datetime.now() - bot.start_time
total_seconds = max(0, int(delta.total_seconds()))
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
uptime_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
# 2. Real-time Ping (ms me)
ping_ms = round(bot.latency * 1000)
# 3. Timestamps
start_time = int(datetime(2026, 5, 11, 0, 0, 0, tzinfo=timezone.utc).timestamp())
end_time = int(datetime(2027, 7, 31, 23, 59, 59, tzinfo=timezone.utc).timestamp())
# 4. Custom Activity Configuration
qlynk_activity = discord.Activity(
type=discord.ActivityType.listening, # <-- Yahan "playing" ki jagah "listening" kar diya hai
name="QLYNK Production™",
# Ping aur Uptime yahan bold subtitle me sabse mast dikhega!
details=f"Deep Dey | ⚡ {ping_ms}ms • ⏱️ {uptime_str} 🔥",
state="Made with QLYNK Production™ | Visit: deepdey.vercel.app",
timestamps={
"start": start_time,
"end": end_time
},
assets={
"large_image": "https://i.postimg.cc/wxt21K5p/4391825b57ea3aa2e658f2e2534f81cb.webp",
"large_text": f"Deep Dey - QLYNK Production™ ({ping_ms}ms)"
}
)
await bot.change_presence(
status=discord.Status.dnd, # <-- 🔴 Ye Red (Do Not Disturb) dikhayega!
activity=qlynk_activity
)
@bot.event
async def on_ready():
print(f"✅ Logged in as {bot.user} | Ready to track!")
# Ye rha tera QLYNK Production™ wala rich status activation! 🔥
await set_qlynk_activity()
# Load Cogs (Setup Commands + Music Engine + Game Engine)
for extension in (
"cogs.setup_commands",
"cogs.music_commands",
"cogs.game_commands",
"cogs.utility_commands",
"cogs.productivity_commands",
"cogs.proxy",
"cogs.management_commands", # <-- NAYA COG YAHAN ADD KIYA HAI
"cogs.ticket_commands",
):
try:
await bot.load_extension(extension)
print(f"✅ Loaded extension: {extension}")
except Exception as e:
print(f"❌ Error loading {extension}: {e}")
try:
# sync() list return karta hai, usko variable me store kar lo
synced_commands = await bot.tree.sync()
# Total count print karo
print(f"✅ Successfully synced {len(synced_commands)} slash commands!")
# Ek-ek karke saare commands terminal me print karo
print("📋 Loaded Commands List:")
for cmd in synced_commands:
print(f" ➡️ /{cmd.name}")
except Exception as e:
print(f"❌ Error syncing slash commands: {e}")
# Saare background tasks ek hi baar start karo
if not leaderboard_loop.is_running():
leaderboard_loop.start()
if not update_api_stats.is_running():
update_api_stats.start()
if not flush_buffer.is_running():
flush_buffer.start()
if not crypto_keepalive.is_running():
crypto_keepalive.start()
@bot.event
async def on_app_command_completion(interaction: discord.Interaction, command):
qualified_name = command.qualified_name.lower()
await send_activity_log(
bot,
activity_type="Command Usage",
details=f"Slash command `/{qualified_name}` executed.",
module="Commands",
guild=interaction.guild,
user=interaction.user,
jump_url=interaction.channel.jump_url if isinstance(interaction.channel, discord.TextChannel) else None,
fields=[("Command", f"/{qualified_name}", True)],
)
@bot.event
async def on_voice_state_update(member: discord.Member, before: discord.VoiceState, after: discord.VoiceState):
if member.bot:
return
if before.channel is None and after.channel is not None:
await send_activity_log(
bot,
activity_type="Voice Channel Join",
details=f"User joined voice channel {after.channel.name}.",
module="Voice",
guild=member.guild,
user=member,
fields=[("Voice Channel", after.channel.name, True)],
)
@bot.event
async def on_message(message):
# Bot ke apne messages aur DMs ignore karo
if message.author.bot or not message.guild:
return
g_id = message.guild.id
u_id = message.author.id
# RAM mein store karo (Memory Dictionary)
if g_id not in message_buffer:
message_buffer[g_id] = {}
# Count badhao
message_buffer[g_id][u_id] = message_buffer[g_id].get(u_id, 0) + 1
await bot.process_commands(message)
async def _tree_on_error(interaction: discord.Interaction, error: Exception):
user_message = "An unexpected error occurred while running this command."
try:
if interaction.response.is_done():
await interaction.followup.send(user_message, ephemeral=True)
else:
await interaction.response.send_message(user_message, ephemeral=True)
except Exception:
pass
cmd_name = interaction.command.qualified_name if interaction.command else "unknown"
context = (
f"Command: /{cmd_name} | User: {interaction.user} ({interaction.user.id}) | "
f"Guild: {interaction.guild_id} | Channel: {interaction.channel_id}"
)
await log_exception(
bot,
title="Slash Command Error",
error=error,
context=context,
)
bot.tree.on_error = _tree_on_error
@tasks.loop(minutes=1)
async def update_api_stats():
uptime_seconds = 0
if getattr(bot, "start_time", None):
try:
uptime_seconds = max(0, int((datetime.now() - bot.start_time).total_seconds()))
except Exception:
uptime_seconds = 0
stats_data = {
"servers": len(bot.guilds),
"users": sum(int(g.member_count or 0) for g in bot.guilds),
"ping": round(bot.latency * 1000),
"uptime_seconds": uptime_seconds,
}
with open('stats.json', 'w') as f:
json.dump(stats_data, f)
@tasks.loop(seconds=300)
async def crypto_keepalive():
interval = secrets.choice(range(300, 601))
crypto_keepalive.change_interval(seconds=interval)
try:
timeout = aiohttp.ClientTimeout(total=20)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(KEEPALIVE_URL) as response:
if 200 <= response.status < 400:
await send_master_log(
bot,
title="Crypto Keep-Alive Ping",
description="Successful self-ping to keep Render host awake.",
fields=[
("Target", KEEPALIVE_URL, False),
("HTTP Status", str(response.status), True),
("Sleep Interval", f"{interval}s", True),
],
)
except Exception:
pass
@crypto_keepalive.before_loop
async def before_crypto_keepalive():
await bot.wait_until_ready()
crypto_keepalive.change_interval(seconds=secrets.choice(range(300, 601)))
@tasks.loop(minutes=2) # Har 2 minute me RAM se DB me bhejega
async def flush_buffer():
global message_buffer
if not message_buffer:
return
# Buffer ki copy banao aur main buffer clear karo
buffer_snapshot = message_buffer.copy()
message_buffer.clear()
# Bulk update DB
try:
await db.bulk_update_activity(buffer_snapshot)
print(f"✅ Flushed {len(buffer_snapshot)} guilds' data to MongoDB.")
except Exception as e:
print(f"❌ Error in bulk DB update: {e}")
# Agar error aaye, toh data wapas ram me bacha lo
for g_id, users in buffer_snapshot.items():
if g_id not in message_buffer:
message_buffer[g_id] = {}
for u_id, count in users.items():
message_buffer[g_id][u_id] = message_buffer[g_id].get(u_id, 0) + count
@tasks.loop(minutes=1)
async def leaderboard_loop():
now = datetime.now(timezone.utc)
# Saare guilds ki settings fetch karo
async for settings in db.settings_col.find({}):
guild_id = settings.get("guild_id")
guild = bot.get_guild(guild_id)
if not guild: continue
interval_days = max(1, int(settings.get("interval_days", 7) or 7))
last_reset = settings.get("last_reset_time")
pending_cycle_start = bool(settings.get("pending_cycle_start", False))
if last_reset and last_reset.tzinfo is None:
last_reset = last_reset.replace(tzinfo=timezone.utc)
# Agar last_reset None hai, toh abhi ka time set kardo (first run)
if not last_reset:
await db.settings_col.update_one({"guild_id": guild_id}, {"$set": {"last_reset_time": now, "pending_cycle_start": False}})
continue
# Future start ke liye pending flag set ho toh exact start pe cycle reset karo
if pending_cycle_start:
if now >= last_reset:
await db.reset_activity(guild_id)
await db.settings_col.update_one(
{"guild_id": guild_id},
{"$set": {"pending_cycle_start": False, "last_reset_time": last_reset}},
)
else:
continue
elif now < last_reset:
continue
# Check agar interval khatam ho gaya
due_time = last_reset + timedelta(days=interval_days)
if now >= due_time:
await process_leaderboard(guild, settings)
# Update last reset time
await db.settings_col.update_one(
{"guild_id": guild_id},
{"$set": {"last_reset_time": due_time, "last_result_time": now, "pending_cycle_start": False}},
)
async def process_leaderboard(guild: discord.Guild, settings: dict):
"""Automatically logs bhejta hai, role deta hai aur list post karta hai."""
announcement_channel = guild.get_channel(settings.get("announcement_channel_id"))
logs_channel = guild.get_channel(settings.get("logs_channel_id"))
role = guild.get_role(settings.get("reward_role_id"))
top_count = settings.get("top_count", 3)
if not announcement_channel: return
# 1. Pehle Logs Bhejo (Agar configured hai)
all_users_data = await db.get_all_users(guild.id)
if logs_channel:
last_reset = settings.get("last_reset_time")
if last_reset and last_reset.tzinfo is None:
last_reset = last_reset.replace(tzinfo=timezone.utc)
time_range = f"Since: <t:{int(last_reset.timestamp())}:F>" if last_reset else "All time"
# Paginated silent embeds + HTML/JSON files bhejne wala naya method call hoga
await utils.send_paginated_backup_logs(
logs_channel, guild, all_users_data, time_range, "Automatic Cycle Reset"
)
# 2. Top N Users Fetch Karo
top_users = await db.get_top_users(guild.id, top_count)
if not top_users:
await announcement_channel.send("Is period mein kisi ne chat nahi ki! Data reset kar raha hu.")
await db.reset_activity(guild.id)
return
# 3. Purane role members se role hatao
if role:
for member in role.members:
try:
await member.remove_roles(role)
except discord.Forbidden:
pass
# 4. Embed Banaiye
embed = discord.Embed(title="🏆 Server Activity Leaderboard", color=0x5865F2)
description = ""
medals = ["🥇", "🥈", "🥉"]
for rank, user_data in enumerate(top_users, start=1):
member = guild.get_member(user_data["user_id"])
medal = medals[rank-1] if rank <= 3 else f"#{rank}"
if member:
description += f"{medal} **{member.mention}** — {user_data['message_count']} messages\n"
# Naye winners ko role do
if role:
try:
await member.add_roles(role)
except discord.Forbidden:
pass
else:
description += f"{medal} **Left User ({user_data['user_id']})** — {user_data['message_count']} messages\n"
embed.description = description + "\n\nThank you to everyone who participated! If your name isn't here, don't be sad—keep chatting and try again next time! ❤️"
embed.set_footer(text="an app by deep", icon_url=bot.user.avatar.url if bot.user.avatar else None)
# 5. Buttons (Action Row)
view = create_branding_view()
# 6. Final Message bhejna
role_mention = role.mention if role else "Top Members"
# Custom message fetch karna (Jo tumne /setup message_edit me set kiya tha)
custom_msg = settings.get("custom_announcement")
if custom_msg:
# {role} aur {top_count} ko replace karna
content = custom_msg.replace("{role}", role_mention).replace("{top_count}", str(top_count))
else:
content = f"{role_mention} Here are the top {top_count} most active members for this period!"
# Ping Toggle check karna
ping_enabled = settings.get("ping_reward_role", True)
# Is specific message ke liye temporary permissions overide karna
allowed_mentions = discord.AllowedMentions(roles=ping_enabled, users=True, everyone=False)
# allowed_mentions pass karna zaroori hai
await announcement_channel.send(content=content, embed=embed, view=view, allowed_mentions=allowed_mentions)
# 7. Data Wipe for the new cycle
await db.reset_activity(guild.id)
# Start bot + Keep Alive
if __name__ == "__main__":
if os.getenv("SEPARATE_WEBSITE_PROCESS", "0") != "1":
keep_alive.keep_alive() # Starts the Flask server
bot.run(TOKEN)