Update main.py
Browse files
main.py
CHANGED
|
@@ -2,71 +2,42 @@ import discord
|
|
| 2 |
from discord.ext import commands, tasks
|
| 3 |
import os
|
| 4 |
import asyncio
|
| 5 |
-
import threading
|
| 6 |
-
import logging
|
| 7 |
-
import time
|
| 8 |
from datetime import datetime
|
| 9 |
-
|
| 10 |
-
import requests
|
| 11 |
|
| 12 |
-
#
|
| 13 |
logging.basicConfig(
|
| 14 |
level=logging.INFO,
|
| 15 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 16 |
)
|
| 17 |
logger = logging.getLogger('discord_bot')
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
app = Flask(__name__)
|
| 21 |
-
|
| 22 |
-
@app.route('/')
|
| 23 |
-
def home():
|
| 24 |
-
return {
|
| 25 |
-
"status": "online",
|
| 26 |
-
"bot": bot.user.name if bot.is_ready() else "starting",
|
| 27 |
-
"servers": len(bot.guilds) if bot.is_ready() else 0,
|
| 28 |
-
"timestamp": datetime.now().isoformat()
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
@app.route('/health')
|
| 32 |
-
def health():
|
| 33 |
-
return {"status": "healthy", "bot_ready": bot.is_ready()}
|
| 34 |
-
|
| 35 |
-
def run_flask():
|
| 36 |
-
port = int(os.environ.get("PORT", 7860))
|
| 37 |
-
app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
|
| 38 |
-
|
| 39 |
-
# ==================== BOT CONFIGURATION ====================
|
| 40 |
TOKEN = os.getenv('DISCORD_TOKEN')
|
| 41 |
if not TOKEN:
|
| 42 |
-
logger.error("❌ DISCORD_TOKEN not found!")
|
| 43 |
raise ValueError("DISCORD_TOKEN environment variable is required!")
|
| 44 |
|
| 45 |
# Bot intents
|
| 46 |
intents = discord.Intents.default()
|
| 47 |
-
intents.message_content = True
|
| 48 |
intents.members = True
|
| 49 |
intents.presences = True
|
| 50 |
-
intents.guilds = True
|
| 51 |
-
intents.messages = True
|
| 52 |
-
intents.reactions = True
|
| 53 |
|
|
|
|
| 54 |
bot = commands.Bot(
|
| 55 |
command_prefix='!',
|
| 56 |
intents=intents,
|
| 57 |
-
help_command=None,
|
| 58 |
case_insensitive=True
|
| 59 |
)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
start_time = datetime.now()
|
| 63 |
-
|
| 64 |
-
# ==================== EVENTS ====================
|
| 65 |
@bot.event
|
| 66 |
async def on_ready():
|
| 67 |
-
logger.info(f'
|
| 68 |
-
logger.info(f'
|
| 69 |
|
|
|
|
| 70 |
await bot.change_presence(
|
| 71 |
activity=discord.Activity(
|
| 72 |
type=discord.ActivityType.watching,
|
|
@@ -75,41 +46,52 @@ async def on_ready():
|
|
| 75 |
status=discord.Status.online
|
| 76 |
)
|
| 77 |
|
|
|
|
| 78 |
status_update.start()
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
logger.info("🔄 Session resumed")
|
| 91 |
|
|
|
|
| 92 |
@bot.event
|
| 93 |
async def on_guild_join(guild):
|
| 94 |
-
logger.info(f'
|
| 95 |
|
|
|
|
| 96 |
@bot.event
|
| 97 |
async def on_guild_remove(guild):
|
| 98 |
-
logger.info(f'
|
| 99 |
|
|
|
|
| 100 |
@bot.event
|
| 101 |
-
async def
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
# ==================== COMMANDS ====================
|
|
|
|
|
|
|
| 105 |
@bot.command(name='help', aliases=['h', 'commands'])
|
| 106 |
async def help_command(ctx, command_name: str = None):
|
| 107 |
"""Show help information"""
|
| 108 |
if command_name:
|
|
|
|
| 109 |
command = bot.get_command(command_name)
|
| 110 |
if command:
|
| 111 |
embed = discord.Embed(
|
| 112 |
-
title=f"
|
| 113 |
description=command.help or "No description available",
|
| 114 |
color=discord.Color.blue()
|
| 115 |
)
|
|
@@ -126,15 +108,17 @@ async def help_command(ctx, command_name: str = None):
|
|
| 126 |
)
|
| 127 |
await ctx.send(embed=embed)
|
| 128 |
else:
|
| 129 |
-
await ctx.send(f"
|
| 130 |
else:
|
|
|
|
| 131 |
embed = discord.Embed(
|
| 132 |
-
title="
|
| 133 |
description="Here are all available commands:",
|
| 134 |
color=discord.Color.blue(),
|
| 135 |
timestamp=datetime.now()
|
| 136 |
)
|
| 137 |
|
|
|
|
| 138 |
categories = {
|
| 139 |
"General": ['help', 'ping', 'info', 'serverinfo', 'userinfo'],
|
| 140 |
"Fun": ['say', 'embed', 'poll', '8ball', 'coinflip'],
|
|
@@ -149,7 +133,7 @@ async def help_command(ctx, command_name: str = None):
|
|
| 149 |
valid_cmds.append(f"`!{cmd.name}`")
|
| 150 |
if valid_cmds:
|
| 151 |
embed.add_field(
|
| 152 |
-
name=f"
|
| 153 |
value=" | ".join(valid_cmds),
|
| 154 |
inline=False
|
| 155 |
)
|
|
@@ -157,25 +141,27 @@ async def help_command(ctx, command_name: str = None):
|
|
| 157 |
embed.set_footer(text=f"Use !help <command> for more details | Prefix: !")
|
| 158 |
await ctx.send(embed=embed)
|
| 159 |
|
|
|
|
| 160 |
@bot.command(name='ping', aliases=['latency'])
|
| 161 |
async def ping_command(ctx):
|
| 162 |
"""Check bot latency"""
|
| 163 |
latency = round(bot.latency * 1000)
|
| 164 |
|
| 165 |
embed = discord.Embed(
|
| 166 |
-
title="
|
| 167 |
-
description=f"**Latency:** `{latency}ms`",
|
| 168 |
color=discord.Color.green() if latency < 200 else discord.Color.orange() if latency < 500 else discord.Color.red()
|
| 169 |
)
|
| 170 |
embed.set_footer(text=f"Requested by {ctx.author.name}")
|
| 171 |
await ctx.send(embed=embed)
|
| 172 |
|
|
|
|
| 173 |
@bot.command(name='info', aliases=['botinfo', 'about'])
|
| 174 |
async def info_command(ctx):
|
| 175 |
"""Show bot information"""
|
| 176 |
embed = discord.Embed(
|
| 177 |
-
title="
|
| 178 |
-
description="A Discord bot powered by discord.py
|
| 179 |
color=discord.Color.blue(),
|
| 180 |
timestamp=datetime.now()
|
| 181 |
)
|
|
@@ -184,21 +170,24 @@ async def info_command(ctx):
|
|
| 184 |
embed.add_field(name="Bot ID", value=bot.user.id, inline=True)
|
| 185 |
embed.add_field(name="Servers", value=len(bot.guilds), inline=True)
|
| 186 |
embed.add_field(name="Users", value=sum(g.member_count for g in bot.guilds), inline=True)
|
| 187 |
-
embed.add_field(name="Library", value="discord.py
|
|
|
|
|
|
|
| 188 |
embed.add_field(name="Uptime", value=get_uptime(), inline=True)
|
| 189 |
|
| 190 |
embed.set_thumbnail(url=bot.user.avatar.url if bot.user.avatar else bot.user.default_avatar.url)
|
| 191 |
-
embed.set_footer(text="
|
| 192 |
|
| 193 |
await ctx.send(embed=embed)
|
| 194 |
|
|
|
|
| 195 |
@bot.command(name='serverinfo', aliases=['server', 'guildinfo'])
|
| 196 |
async def serverinfo_command(ctx):
|
| 197 |
"""Show server information"""
|
| 198 |
guild = ctx.guild
|
| 199 |
|
| 200 |
embed = discord.Embed(
|
| 201 |
-
title=f"
|
| 202 |
color=discord.Color.blue(),
|
| 203 |
timestamp=datetime.now()
|
| 204 |
)
|
|
@@ -209,19 +198,21 @@ async def serverinfo_command(ctx):
|
|
| 209 |
embed.add_field(name="Channels", value=f"{len(guild.text_channels)} Text | {len(guild.voice_channels)} Voice", inline=True)
|
| 210 |
embed.add_field(name="Roles", value=len(guild.roles), inline=True)
|
| 211 |
embed.add_field(name="Created", value=guild.created_at.strftime("%Y-%m-%d"), inline=True)
|
|
|
|
| 212 |
|
| 213 |
if guild.icon:
|
| 214 |
embed.set_thumbnail(url=guild.icon.url)
|
| 215 |
|
| 216 |
await ctx.send(embed=embed)
|
| 217 |
|
|
|
|
| 218 |
@bot.command(name='userinfo', aliases=['whois', 'profile'])
|
| 219 |
async def userinfo_command(ctx, member: discord.Member = None):
|
| 220 |
"""Show user information"""
|
| 221 |
member = member or ctx.author
|
| 222 |
|
| 223 |
embed = discord.Embed(
|
| 224 |
-
title=f"
|
| 225 |
color=member.color if member.color != discord.Color.default() else discord.Color.blue(),
|
| 226 |
timestamp=datetime.now()
|
| 227 |
)
|
|
@@ -229,40 +220,46 @@ async def userinfo_command(ctx, member: discord.Member = None):
|
|
| 229 |
embed.add_field(name="Username", value=member.name, inline=True)
|
| 230 |
embed.add_field(name="Display Name", value=member.display_name, inline=True)
|
| 231 |
embed.add_field(name="ID", value=member.id, inline=True)
|
| 232 |
-
embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d") if member.joined_at else "Unknown", inline=True)
|
| 233 |
-
embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d"), inline=True)
|
| 234 |
embed.add_field(name="Status", value=str(member.status).title(), inline=True)
|
| 235 |
embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)
|
|
|
|
| 236 |
|
| 237 |
roles = [role.mention for role in member.roles if role != ctx.guild.default_role]
|
| 238 |
if roles:
|
| 239 |
embed.add_field(name=f"Roles ({len(roles)})", value=" ".join(roles[:10]) + ("..." if len(roles) > 10 else ""), inline=False)
|
| 240 |
|
| 241 |
embed.set_thumbnail(url=member.avatar.url if member.avatar else member.default_avatar.url)
|
|
|
|
|
|
|
| 242 |
await ctx.send(embed=embed)
|
| 243 |
|
|
|
|
| 244 |
@bot.command(name='avatar', aliases=['av', 'pfp'])
|
| 245 |
async def avatar_command(ctx, member: discord.Member = None):
|
| 246 |
"""Show user's avatar"""
|
| 247 |
member = member or ctx.author
|
| 248 |
-
avatar_url = member.avatar.url if member.avatar else member.default_avatar.url
|
| 249 |
|
| 250 |
embed = discord.Embed(
|
| 251 |
-
title=f"
|
| 252 |
color=discord.Color.blue()
|
| 253 |
)
|
|
|
|
|
|
|
| 254 |
embed.set_image(url=avatar_url)
|
|
|
|
|
|
|
| 255 |
await ctx.send(embed=embed)
|
| 256 |
|
|
|
|
| 257 |
@bot.command(name='say', aliases=['echo'])
|
| 258 |
async def say_command(ctx, *, message: str):
|
| 259 |
"""Make the bot say something"""
|
| 260 |
-
|
| 261 |
-
await ctx.message.delete()
|
| 262 |
-
except:
|
| 263 |
-
pass
|
| 264 |
await ctx.send(message)
|
| 265 |
|
|
|
|
| 266 |
@bot.command(name='embed', aliases=['em'])
|
| 267 |
async def embed_command(ctx, *, message: str):
|
| 268 |
"""Create a custom embed"""
|
|
@@ -274,11 +271,12 @@ async def embed_command(ctx, *, message: str):
|
|
| 274 |
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
|
| 275 |
await ctx.send(embed=embed)
|
| 276 |
|
|
|
|
| 277 |
@bot.command(name='poll', aliases=['vote'])
|
| 278 |
async def poll_command(ctx, *, question: str):
|
| 279 |
"""Create a poll"""
|
| 280 |
embed = discord.Embed(
|
| 281 |
-
title="
|
| 282 |
description=question,
|
| 283 |
color=discord.Color.blue(),
|
| 284 |
timestamp=datetime.now()
|
|
@@ -286,111 +284,148 @@ async def poll_command(ctx, *, question: str):
|
|
| 286 |
embed.set_footer(text=f"Poll by {ctx.author.name}")
|
| 287 |
|
| 288 |
poll_message = await ctx.send(embed=embed)
|
| 289 |
-
await poll_message.add_reaction("
|
| 290 |
-
await poll_message.add_reaction("
|
| 291 |
-
await poll_message.add_reaction("
|
| 292 |
|
|
|
|
| 293 |
@bot.command(name='8ball', aliases=['magic8ball', 'ask'])
|
| 294 |
async def eightball_command(ctx, *, question: str):
|
| 295 |
"""Ask the magic 8-ball"""
|
| 296 |
import random
|
|
|
|
| 297 |
responses = [
|
| 298 |
-
"
|
| 299 |
-
"
|
| 300 |
-
"
|
| 301 |
-
"
|
| 302 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
]
|
| 304 |
|
| 305 |
-
embed = discord.Embed(
|
|
|
|
|
|
|
|
|
|
| 306 |
embed.add_field(name="Question", value=question, inline=False)
|
| 307 |
embed.add_field(name="Answer", value=random.choice(responses), inline=False)
|
|
|
|
| 308 |
await ctx.send(embed=embed)
|
| 309 |
|
|
|
|
| 310 |
@bot.command(name='coinflip', aliases=['flip', 'coin'])
|
| 311 |
async def coinflip_command(ctx):
|
| 312 |
"""Flip a coin"""
|
| 313 |
import random
|
| 314 |
-
|
|
|
|
|
|
|
| 315 |
|
| 316 |
embed = discord.Embed(
|
| 317 |
-
title="
|
| 318 |
description=f"**Result:** {result}",
|
| 319 |
color=discord.Color.gold()
|
| 320 |
)
|
|
|
|
| 321 |
await ctx.send(embed=embed)
|
| 322 |
|
|
|
|
| 323 |
@bot.command(name='invite', aliases=['addbot'])
|
| 324 |
async def invite_command(ctx):
|
| 325 |
"""Get bot invite link"""
|
| 326 |
permissions = discord.Permissions(
|
| 327 |
-
send_messages=True,
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
)
|
| 331 |
|
| 332 |
invite_url = discord.utils.oauth_url(bot.user.id, permissions=permissions)
|
| 333 |
|
| 334 |
embed = discord.Embed(
|
| 335 |
-
title="
|
| 336 |
description=f"[Click here to invite me!]({invite_url})",
|
| 337 |
color=discord.Color.green()
|
| 338 |
)
|
|
|
|
|
|
|
| 339 |
await ctx.send(embed=embed)
|
| 340 |
|
|
|
|
| 341 |
@bot.command(name='clear', aliases=['purge', 'clean'])
|
| 342 |
@commands.has_permissions(manage_messages=True)
|
| 343 |
async def clear_command(ctx, amount: int = 5):
|
| 344 |
-
"""Clear messages"""
|
| 345 |
if amount < 1 or amount > 100:
|
| 346 |
-
await ctx.send("
|
| 347 |
return
|
| 348 |
|
| 349 |
deleted = await ctx.channel.purge(limit=amount + 1)
|
| 350 |
embed = discord.Embed(
|
| 351 |
-
description=f"
|
| 352 |
color=discord.Color.green()
|
| 353 |
)
|
| 354 |
msg = await ctx.send(embed=embed)
|
| 355 |
await asyncio.sleep(3)
|
| 356 |
await msg.delete()
|
| 357 |
|
|
|
|
| 358 |
@bot.command(name='uptime', aliases=['up'])
|
| 359 |
async def uptime_command(ctx):
|
| 360 |
"""Show bot uptime"""
|
| 361 |
embed = discord.Embed(
|
| 362 |
-
title="
|
| 363 |
description=get_uptime(),
|
| 364 |
color=discord.Color.blue()
|
| 365 |
)
|
| 366 |
await ctx.send(embed=embed)
|
| 367 |
|
| 368 |
-
#
|
| 369 |
@bot.event
|
| 370 |
async def on_command_error(ctx, error):
|
| 371 |
if isinstance(error, commands.CommandNotFound):
|
| 372 |
-
return
|
| 373 |
|
| 374 |
elif isinstance(error, commands.MissingRequiredArgument):
|
| 375 |
embed = discord.Embed(
|
| 376 |
-
title="
|
| 377 |
-
description=f"Missing: `{error.param.name}`\nUse `!help {ctx.command.name}` for usage.",
|
| 378 |
color=discord.Color.red()
|
| 379 |
)
|
| 380 |
await ctx.send(embed=embed)
|
| 381 |
|
| 382 |
elif isinstance(error, commands.MissingPermissions):
|
| 383 |
embed = discord.Embed(
|
| 384 |
-
title="
|
| 385 |
-
description=f"You need
|
| 386 |
color=discord.Color.red()
|
| 387 |
)
|
| 388 |
await ctx.send(embed=embed)
|
| 389 |
|
| 390 |
elif isinstance(error, commands.MemberNotFound):
|
| 391 |
embed = discord.Embed(
|
| 392 |
-
title="
|
| 393 |
-
description="
|
| 394 |
color=discord.Color.red()
|
| 395 |
)
|
| 396 |
await ctx.send(embed=embed)
|
|
@@ -398,25 +433,15 @@ async def on_command_error(ctx, error):
|
|
| 398 |
else:
|
| 399 |
logger.error(f"Command error: {error}")
|
| 400 |
embed = discord.Embed(
|
| 401 |
-
title="
|
| 402 |
-
description="An error occurred. Please try again.",
|
| 403 |
color=discord.Color.red()
|
| 404 |
)
|
| 405 |
await ctx.send(embed=embed)
|
| 406 |
|
| 407 |
-
#
|
| 408 |
-
|
| 409 |
-
async def status_update():
|
| 410 |
-
if bot.is_ready():
|
| 411 |
-
await bot.change_presence(
|
| 412 |
-
activity=discord.Activity(
|
| 413 |
-
type=discord.ActivityType.watching,
|
| 414 |
-
name=f"{len(bot.guilds)} servers | !help"
|
| 415 |
-
),
|
| 416 |
-
status=discord.Status.online
|
| 417 |
-
)
|
| 418 |
|
| 419 |
-
# ==================== HELPER FUNCTIONS ====================
|
| 420 |
def get_uptime():
|
| 421 |
delta = datetime.now() - start_time
|
| 422 |
days = delta.days
|
|
@@ -424,39 +449,20 @@ def get_uptime():
|
|
| 424 |
minutes, seconds = divmod(remainder, 60)
|
| 425 |
|
| 426 |
parts = []
|
| 427 |
-
if days > 0:
|
| 428 |
-
|
| 429 |
-
if
|
|
|
|
|
|
|
|
|
|
| 430 |
parts.append(f"{seconds}s")
|
| 431 |
|
| 432 |
return " ".join(parts)
|
| 433 |
|
| 434 |
-
#
|
| 435 |
-
|
| 436 |
-
# Start Flask web server in background thread
|
| 437 |
-
flask_thread = threading.Thread(target=run_flask, daemon=True)
|
| 438 |
-
flask_thread.start()
|
| 439 |
-
logger.info("🌐 Flask web server started on port 7860")
|
| 440 |
-
|
| 441 |
-
# Keep-alive ping
|
| 442 |
-
def keep_alive():
|
| 443 |
-
while True:
|
| 444 |
-
try:
|
| 445 |
-
requests.get("http://localhost:7860/health", timeout=5)
|
| 446 |
-
except:
|
| 447 |
-
pass
|
| 448 |
-
time.sleep(300)
|
| 449 |
-
|
| 450 |
-
keep_alive_thread = threading.Thread(target=keep_alive, daemon=True)
|
| 451 |
-
keep_alive_thread.start()
|
| 452 |
-
|
| 453 |
-
# Run Discord bot
|
| 454 |
-
logger.info("🤖 Starting Discord bot...")
|
| 455 |
try:
|
| 456 |
-
bot.run(TOKEN
|
| 457 |
except Exception as e:
|
| 458 |
-
logger.error(f"
|
| 459 |
-
raise
|
| 460 |
-
|
| 461 |
-
if __name__ == "__main__":
|
| 462 |
-
main()
|
|
|
|
| 2 |
from discord.ext import commands, tasks
|
| 3 |
import os
|
| 4 |
import asyncio
|
|
|
|
|
|
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
+
import logging
|
|
|
|
| 7 |
|
| 8 |
+
# Setup logging
|
| 9 |
logging.basicConfig(
|
| 10 |
level=logging.INFO,
|
| 11 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 12 |
)
|
| 13 |
logger = logging.getLogger('discord_bot')
|
| 14 |
|
| 15 |
+
# Bot configuration
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
TOKEN = os.getenv('DISCORD_TOKEN')
|
| 17 |
if not TOKEN:
|
|
|
|
| 18 |
raise ValueError("DISCORD_TOKEN environment variable is required!")
|
| 19 |
|
| 20 |
# Bot intents
|
| 21 |
intents = discord.Intents.default()
|
| 22 |
+
intents.message_content = True # Required for reading message content
|
| 23 |
intents.members = True
|
| 24 |
intents.presences = True
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# Create bot instance
|
| 27 |
bot = commands.Bot(
|
| 28 |
command_prefix='!',
|
| 29 |
intents=intents,
|
| 30 |
+
help_command=None, # Custom help command
|
| 31 |
case_insensitive=True
|
| 32 |
)
|
| 33 |
|
| 34 |
+
# Event: Bot ready
|
|
|
|
|
|
|
|
|
|
| 35 |
@bot.event
|
| 36 |
async def on_ready():
|
| 37 |
+
logger.info(f'✅ Bot logged in as {bot.user.name} ({bot.user.id})')
|
| 38 |
+
logger.info(f'🌠Connected to {len(bot.guilds)} guilds')
|
| 39 |
|
| 40 |
+
# Set bot status
|
| 41 |
await bot.change_presence(
|
| 42 |
activity=discord.Activity(
|
| 43 |
type=discord.ActivityType.watching,
|
|
|
|
| 46 |
status=discord.Status.online
|
| 47 |
)
|
| 48 |
|
| 49 |
+
# Start background tasks
|
| 50 |
status_update.start()
|
| 51 |
|
| 52 |
+
# Background task: Update status every 5 minutes
|
| 53 |
+
@tasks.loop(minutes=5)
|
| 54 |
+
async def status_update():
|
| 55 |
+
await bot.change_presence(
|
| 56 |
+
activity=discord.Activity(
|
| 57 |
+
type=discord.ActivityType.watching,
|
| 58 |
+
name=f"{len(bot.guilds)} servers | !help"
|
| 59 |
+
),
|
| 60 |
+
status=discord.Status.online
|
| 61 |
+
)
|
|
|
|
| 62 |
|
| 63 |
+
# Event: When bot joins a new guild
|
| 64 |
@bot.event
|
| 65 |
async def on_guild_join(guild):
|
| 66 |
+
logger.info(f'âž• Joined guild: {guild.name} ({guild.id})')
|
| 67 |
|
| 68 |
+
# Event: When bot leaves a guild
|
| 69 |
@bot.event
|
| 70 |
async def on_guild_remove(guild):
|
| 71 |
+
logger.info(f'âž– Left guild: {guild.name} ({guild.id})')
|
| 72 |
|
| 73 |
+
# Event: Handle messages (for non-command messages)
|
| 74 |
@bot.event
|
| 75 |
+
async def on_message(message):
|
| 76 |
+
# Ignore bot messages
|
| 77 |
+
if message.author.bot:
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
# Process commands
|
| 81 |
+
await bot.process_commands(message)
|
| 82 |
|
| 83 |
# ==================== COMMANDS ====================
|
| 84 |
+
|
| 85 |
+
# Help Command
|
| 86 |
@bot.command(name='help', aliases=['h', 'commands'])
|
| 87 |
async def help_command(ctx, command_name: str = None):
|
| 88 |
"""Show help information"""
|
| 89 |
if command_name:
|
| 90 |
+
# Show specific command help
|
| 91 |
command = bot.get_command(command_name)
|
| 92 |
if command:
|
| 93 |
embed = discord.Embed(
|
| 94 |
+
title=f"📖 Help: !{command.name}",
|
| 95 |
description=command.help or "No description available",
|
| 96 |
color=discord.Color.blue()
|
| 97 |
)
|
|
|
|
| 108 |
)
|
| 109 |
await ctx.send(embed=embed)
|
| 110 |
else:
|
| 111 |
+
await ctx.send(f"⌠Command `!{command_name}` not found!")
|
| 112 |
else:
|
| 113 |
+
# Show all commands
|
| 114 |
embed = discord.Embed(
|
| 115 |
+
title="🤖 Bot Commands",
|
| 116 |
description="Here are all available commands:",
|
| 117 |
color=discord.Color.blue(),
|
| 118 |
timestamp=datetime.now()
|
| 119 |
)
|
| 120 |
|
| 121 |
+
# Categorize commands
|
| 122 |
categories = {
|
| 123 |
"General": ['help', 'ping', 'info', 'serverinfo', 'userinfo'],
|
| 124 |
"Fun": ['say', 'embed', 'poll', '8ball', 'coinflip'],
|
|
|
|
| 133 |
valid_cmds.append(f"`!{cmd.name}`")
|
| 134 |
if valid_cmds:
|
| 135 |
embed.add_field(
|
| 136 |
+
name=f"📠{category}",
|
| 137 |
value=" | ".join(valid_cmds),
|
| 138 |
inline=False
|
| 139 |
)
|
|
|
|
| 141 |
embed.set_footer(text=f"Use !help <command> for more details | Prefix: !")
|
| 142 |
await ctx.send(embed=embed)
|
| 143 |
|
| 144 |
+
# Ping Command
|
| 145 |
@bot.command(name='ping', aliases=['latency'])
|
| 146 |
async def ping_command(ctx):
|
| 147 |
"""Check bot latency"""
|
| 148 |
latency = round(bot.latency * 1000)
|
| 149 |
|
| 150 |
embed = discord.Embed(
|
| 151 |
+
title="📠Pong!",
|
| 152 |
+
description=f"**Latency:** `{latency}ms`\n**API Latency:** `{round(bot.latency * 1000)}ms`",
|
| 153 |
color=discord.Color.green() if latency < 200 else discord.Color.orange() if latency < 500 else discord.Color.red()
|
| 154 |
)
|
| 155 |
embed.set_footer(text=f"Requested by {ctx.author.name}")
|
| 156 |
await ctx.send(embed=embed)
|
| 157 |
|
| 158 |
+
# Info Command
|
| 159 |
@bot.command(name='info', aliases=['botinfo', 'about'])
|
| 160 |
async def info_command(ctx):
|
| 161 |
"""Show bot information"""
|
| 162 |
embed = discord.Embed(
|
| 163 |
+
title="🤖 Bot Information",
|
| 164 |
+
description="A Discord bot powered by discord.py",
|
| 165 |
color=discord.Color.blue(),
|
| 166 |
timestamp=datetime.now()
|
| 167 |
)
|
|
|
|
| 170 |
embed.add_field(name="Bot ID", value=bot.user.id, inline=True)
|
| 171 |
embed.add_field(name="Servers", value=len(bot.guilds), inline=True)
|
| 172 |
embed.add_field(name="Users", value=sum(g.member_count for g in bot.guilds), inline=True)
|
| 173 |
+
embed.add_field(name="Library", value="discord.py", inline=True)
|
| 174 |
+
embed.add_field(name="Python Version", value="3.10+", inline=True)
|
| 175 |
+
embed.add_field(name="Created", value=bot.user.created_at.strftime("%Y-%m-%d"), inline=True)
|
| 176 |
embed.add_field(name="Uptime", value=get_uptime(), inline=True)
|
| 177 |
|
| 178 |
embed.set_thumbnail(url=bot.user.avatar.url if bot.user.avatar else bot.user.default_avatar.url)
|
| 179 |
+
embed.set_footer(text="Made with â¤ï¸ using discord.py")
|
| 180 |
|
| 181 |
await ctx.send(embed=embed)
|
| 182 |
|
| 183 |
+
# Server Info Command
|
| 184 |
@bot.command(name='serverinfo', aliases=['server', 'guildinfo'])
|
| 185 |
async def serverinfo_command(ctx):
|
| 186 |
"""Show server information"""
|
| 187 |
guild = ctx.guild
|
| 188 |
|
| 189 |
embed = discord.Embed(
|
| 190 |
+
title=f"📊 {guild.name} Server Info",
|
| 191 |
color=discord.Color.blue(),
|
| 192 |
timestamp=datetime.now()
|
| 193 |
)
|
|
|
|
| 198 |
embed.add_field(name="Channels", value=f"{len(guild.text_channels)} Text | {len(guild.voice_channels)} Voice", inline=True)
|
| 199 |
embed.add_field(name="Roles", value=len(guild.roles), inline=True)
|
| 200 |
embed.add_field(name="Created", value=guild.created_at.strftime("%Y-%m-%d"), inline=True)
|
| 201 |
+
embed.add_field(name="Boost Level", value=f"Level {guild.premium_tier} ({guild.premium_subscription_count} boosts)", inline=True)
|
| 202 |
|
| 203 |
if guild.icon:
|
| 204 |
embed.set_thumbnail(url=guild.icon.url)
|
| 205 |
|
| 206 |
await ctx.send(embed=embed)
|
| 207 |
|
| 208 |
+
# User Info Command
|
| 209 |
@bot.command(name='userinfo', aliases=['whois', 'profile'])
|
| 210 |
async def userinfo_command(ctx, member: discord.Member = None):
|
| 211 |
"""Show user information"""
|
| 212 |
member = member or ctx.author
|
| 213 |
|
| 214 |
embed = discord.Embed(
|
| 215 |
+
title=f"👤 {member.name}'s Profile",
|
| 216 |
color=member.color if member.color != discord.Color.default() else discord.Color.blue(),
|
| 217 |
timestamp=datetime.now()
|
| 218 |
)
|
|
|
|
| 220 |
embed.add_field(name="Username", value=member.name, inline=True)
|
| 221 |
embed.add_field(name="Display Name", value=member.display_name, inline=True)
|
| 222 |
embed.add_field(name="ID", value=member.id, inline=True)
|
| 223 |
+
embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d %H:%M") if member.joined_at else "Unknown", inline=True)
|
| 224 |
+
embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d %H:%M"), inline=True)
|
| 225 |
embed.add_field(name="Status", value=str(member.status).title(), inline=True)
|
| 226 |
embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)
|
| 227 |
+
embed.add_field(name="Bot?", value="Yes" if member.bot else "No", inline=True)
|
| 228 |
|
| 229 |
roles = [role.mention for role in member.roles if role != ctx.guild.default_role]
|
| 230 |
if roles:
|
| 231 |
embed.add_field(name=f"Roles ({len(roles)})", value=" ".join(roles[:10]) + ("..." if len(roles) > 10 else ""), inline=False)
|
| 232 |
|
| 233 |
embed.set_thumbnail(url=member.avatar.url if member.avatar else member.default_avatar.url)
|
| 234 |
+
embed.set_footer(text=f"Requested by {ctx.author.name}")
|
| 235 |
+
|
| 236 |
await ctx.send(embed=embed)
|
| 237 |
|
| 238 |
+
# Avatar Command
|
| 239 |
@bot.command(name='avatar', aliases=['av', 'pfp'])
|
| 240 |
async def avatar_command(ctx, member: discord.Member = None):
|
| 241 |
"""Show user's avatar"""
|
| 242 |
member = member or ctx.author
|
|
|
|
| 243 |
|
| 244 |
embed = discord.Embed(
|
| 245 |
+
title=f"ðŸ–¼ï¸ {member.name}'s Avatar",
|
| 246 |
color=discord.Color.blue()
|
| 247 |
)
|
| 248 |
+
|
| 249 |
+
avatar_url = member.avatar.url if member.avatar else member.default_avatar.url
|
| 250 |
embed.set_image(url=avatar_url)
|
| 251 |
+
embed.add_field(name="Links", value=f"[PNG]({member.avatar.url if member.avatar else member.default_avatar.url}) | [WEBP]({member.avatar.url if member.avatar else member.default_avatar.url})", inline=False)
|
| 252 |
+
|
| 253 |
await ctx.send(embed=embed)
|
| 254 |
|
| 255 |
+
# Say Command
|
| 256 |
@bot.command(name='say', aliases=['echo'])
|
| 257 |
async def say_command(ctx, *, message: str):
|
| 258 |
"""Make the bot say something"""
|
| 259 |
+
await ctx.message.delete()
|
|
|
|
|
|
|
|
|
|
| 260 |
await ctx.send(message)
|
| 261 |
|
| 262 |
+
# Embed Command
|
| 263 |
@bot.command(name='embed', aliases=['em'])
|
| 264 |
async def embed_command(ctx, *, message: str):
|
| 265 |
"""Create a custom embed"""
|
|
|
|
| 271 |
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar.url if ctx.author.avatar else ctx.author.default_avatar.url)
|
| 272 |
await ctx.send(embed=embed)
|
| 273 |
|
| 274 |
+
# Poll Command
|
| 275 |
@bot.command(name='poll', aliases=['vote'])
|
| 276 |
async def poll_command(ctx, *, question: str):
|
| 277 |
"""Create a poll"""
|
| 278 |
embed = discord.Embed(
|
| 279 |
+
title="📊 Poll",
|
| 280 |
description=question,
|
| 281 |
color=discord.Color.blue(),
|
| 282 |
timestamp=datetime.now()
|
|
|
|
| 284 |
embed.set_footer(text=f"Poll by {ctx.author.name}")
|
| 285 |
|
| 286 |
poll_message = await ctx.send(embed=embed)
|
| 287 |
+
await poll_message.add_reaction("ðŸ‘")
|
| 288 |
+
await poll_message.add_reaction("👎")
|
| 289 |
+
await poll_message.add_reaction("🤷")
|
| 290 |
|
| 291 |
+
# 8Ball Command
|
| 292 |
@bot.command(name='8ball', aliases=['magic8ball', 'ask'])
|
| 293 |
async def eightball_command(ctx, *, question: str):
|
| 294 |
"""Ask the magic 8-ball"""
|
| 295 |
import random
|
| 296 |
+
|
| 297 |
responses = [
|
| 298 |
+
"🎱 It is certain.",
|
| 299 |
+
"🎱 It is decidedly so.",
|
| 300 |
+
"🎱 Without a doubt.",
|
| 301 |
+
"🎱 Yes definitely.",
|
| 302 |
+
"🎱 You may rely on it.",
|
| 303 |
+
"🎱 As I see it, yes.",
|
| 304 |
+
"🎱 Most likely.",
|
| 305 |
+
"🎱 Outlook good.",
|
| 306 |
+
"🎱 Yes.",
|
| 307 |
+
"🎱 Signs point to yes.",
|
| 308 |
+
"🎱 Reply hazy, try again.",
|
| 309 |
+
"🎱 Ask again later.",
|
| 310 |
+
"🎱 Better not tell you now.",
|
| 311 |
+
"🎱 Cannot predict now.",
|
| 312 |
+
"🎱 Concentrate and ask again.",
|
| 313 |
+
"🎱 Don't count on it.",
|
| 314 |
+
"🎱 My reply is no.",
|
| 315 |
+
"🎱 My sources say no.",
|
| 316 |
+
"🎱 Outlook not so good.",
|
| 317 |
+
"🎱 Very doubtful."
|
| 318 |
]
|
| 319 |
|
| 320 |
+
embed = discord.Embed(
|
| 321 |
+
title="🎱 Magic 8-Ball",
|
| 322 |
+
color=discord.Color.purple()
|
| 323 |
+
)
|
| 324 |
embed.add_field(name="Question", value=question, inline=False)
|
| 325 |
embed.add_field(name="Answer", value=random.choice(responses), inline=False)
|
| 326 |
+
|
| 327 |
await ctx.send(embed=embed)
|
| 328 |
|
| 329 |
+
# Coin Flip Command
|
| 330 |
@bot.command(name='coinflip', aliases=['flip', 'coin'])
|
| 331 |
async def coinflip_command(ctx):
|
| 332 |
"""Flip a coin"""
|
| 333 |
import random
|
| 334 |
+
|
| 335 |
+
result = random.choice(["Heads", "Tails"])
|
| 336 |
+
emoji = "🪙" if result == "Heads" else "🪙"
|
| 337 |
|
| 338 |
embed = discord.Embed(
|
| 339 |
+
title=f"{emoji} Coin Flip",
|
| 340 |
description=f"**Result:** {result}",
|
| 341 |
color=discord.Color.gold()
|
| 342 |
)
|
| 343 |
+
|
| 344 |
await ctx.send(embed=embed)
|
| 345 |
|
| 346 |
+
# Invite Command
|
| 347 |
@bot.command(name='invite', aliases=['addbot'])
|
| 348 |
async def invite_command(ctx):
|
| 349 |
"""Get bot invite link"""
|
| 350 |
permissions = discord.Permissions(
|
| 351 |
+
send_messages=True,
|
| 352 |
+
embed_links=True,
|
| 353 |
+
read_messages=True,
|
| 354 |
+
read_message_history=True,
|
| 355 |
+
add_reactions=True,
|
| 356 |
+
use_external_emojis=True,
|
| 357 |
+
attach_files=True,
|
| 358 |
+
manage_messages=True,
|
| 359 |
+
connect=True,
|
| 360 |
+
speak=True
|
| 361 |
)
|
| 362 |
|
| 363 |
invite_url = discord.utils.oauth_url(bot.user.id, permissions=permissions)
|
| 364 |
|
| 365 |
embed = discord.Embed(
|
| 366 |
+
title="🔗 Invite Bot",
|
| 367 |
description=f"[Click here to invite me!]({invite_url})",
|
| 368 |
color=discord.Color.green()
|
| 369 |
)
|
| 370 |
+
embed.add_field(name="Bot ID", value=bot.user.id, inline=False)
|
| 371 |
+
|
| 372 |
await ctx.send(embed=embed)
|
| 373 |
|
| 374 |
+
# Clear Command
|
| 375 |
@bot.command(name='clear', aliases=['purge', 'clean'])
|
| 376 |
@commands.has_permissions(manage_messages=True)
|
| 377 |
async def clear_command(ctx, amount: int = 5):
|
| 378 |
+
"""Clear messages (requires Manage Messages permission)"""
|
| 379 |
if amount < 1 or amount > 100:
|
| 380 |
+
await ctx.send("⌠Please specify a number between 1 and 100!")
|
| 381 |
return
|
| 382 |
|
| 383 |
deleted = await ctx.channel.purge(limit=amount + 1)
|
| 384 |
embed = discord.Embed(
|
| 385 |
+
description=f"ðŸ—‘ï¸ Deleted {len(deleted) - 1} messages!",
|
| 386 |
color=discord.Color.green()
|
| 387 |
)
|
| 388 |
msg = await ctx.send(embed=embed)
|
| 389 |
await asyncio.sleep(3)
|
| 390 |
await msg.delete()
|
| 391 |
|
| 392 |
+
# Uptime Command
|
| 393 |
@bot.command(name='uptime', aliases=['up'])
|
| 394 |
async def uptime_command(ctx):
|
| 395 |
"""Show bot uptime"""
|
| 396 |
embed = discord.Embed(
|
| 397 |
+
title="â±ï¸ Bot Uptime",
|
| 398 |
description=get_uptime(),
|
| 399 |
color=discord.Color.blue()
|
| 400 |
)
|
| 401 |
await ctx.send(embed=embed)
|
| 402 |
|
| 403 |
+
# Error Handler
|
| 404 |
@bot.event
|
| 405 |
async def on_command_error(ctx, error):
|
| 406 |
if isinstance(error, commands.CommandNotFound):
|
| 407 |
+
return # Ignore unknown commands
|
| 408 |
|
| 409 |
elif isinstance(error, commands.MissingRequiredArgument):
|
| 410 |
embed = discord.Embed(
|
| 411 |
+
title="⌠Missing Argument",
|
| 412 |
+
description=f"Missing required argument: `{error.param.name}`\nUse `!help {ctx.command.name}` for usage info.",
|
| 413 |
color=discord.Color.red()
|
| 414 |
)
|
| 415 |
await ctx.send(embed=embed)
|
| 416 |
|
| 417 |
elif isinstance(error, commands.MissingPermissions):
|
| 418 |
embed = discord.Embed(
|
| 419 |
+
title="⌠Missing Permissions",
|
| 420 |
+
description=f"You need `{', '.join(error.missing_permissions)}` permission to use this command.",
|
| 421 |
color=discord.Color.red()
|
| 422 |
)
|
| 423 |
await ctx.send(embed=embed)
|
| 424 |
|
| 425 |
elif isinstance(error, commands.MemberNotFound):
|
| 426 |
embed = discord.Embed(
|
| 427 |
+
title="⌠User Not Found",
|
| 428 |
+
description="The specified user was not found.",
|
| 429 |
color=discord.Color.red()
|
| 430 |
)
|
| 431 |
await ctx.send(embed=embed)
|
|
|
|
| 433 |
else:
|
| 434 |
logger.error(f"Command error: {error}")
|
| 435 |
embed = discord.Embed(
|
| 436 |
+
title="⌠Error",
|
| 437 |
+
description="An unexpected error occurred. Please try again later.",
|
| 438 |
color=discord.Color.red()
|
| 439 |
)
|
| 440 |
await ctx.send(embed=embed)
|
| 441 |
|
| 442 |
+
# Helper function: Get uptime
|
| 443 |
+
start_time = datetime.now()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
|
|
|
| 445 |
def get_uptime():
|
| 446 |
delta = datetime.now() - start_time
|
| 447 |
days = delta.days
|
|
|
|
| 449 |
minutes, seconds = divmod(remainder, 60)
|
| 450 |
|
| 451 |
parts = []
|
| 452 |
+
if days > 0:
|
| 453 |
+
parts.append(f"{days}d")
|
| 454 |
+
if hours > 0:
|
| 455 |
+
parts.append(f"{hours}h")
|
| 456 |
+
if minutes > 0:
|
| 457 |
+
parts.append(f"{minutes}m")
|
| 458 |
parts.append(f"{seconds}s")
|
| 459 |
|
| 460 |
return " ".join(parts)
|
| 461 |
|
| 462 |
+
# Run the bot
|
| 463 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
try:
|
| 465 |
+
bot.run(TOKEN)
|
| 466 |
except Exception as e:
|
| 467 |
+
logger.error(f"Failed to start bot: {e}")
|
| 468 |
+
raise
|
|
|
|
|
|
|
|
|