discordbot/cogs/fetch_user_cog.py
2025-06-05 21:31:06 -06:00

61 lines
2.0 KiB
Python

import discord
from discord.ext import commands
from discord import app_commands
class FetchUserCog(commands.Cog, name="FetchUser"):
"""Cog providing a command to fetch a user by ID."""
def __init__(self, bot: commands.Bot):
self.bot = bot
async def _create_user_embed(self, user: discord.User) -> discord.Embed:
"""Create an embed showing basic information about a user."""
username = (
f"{user.name}#{user.discriminator}"
if user.discriminator != "0"
else user.name
)
embed = discord.Embed(title="User Information", color=discord.Color.blue())
embed.add_field(name="Username", value=username, inline=False)
embed.add_field(name="User ID", value=str(user.id), inline=False)
embed.add_field(name="Bot Account", value=str(user.bot), inline=False)
embed.add_field(
name="Created",
value=user.created_at.strftime("%Y-%m-%d %H:%M UTC"),
inline=False,
)
if user.avatar:
embed.set_thumbnail(url=user.avatar.url)
return embed
async def _fetch_user_and_send(self, sendable, user_id: int):
try:
user = await self.bot.fetch_user(user_id)
except discord.NotFound:
await sendable("❌ User not found.")
return
except discord.HTTPException as e:
await sendable(f"Failed to fetch user: {e}")
return
embed = await self._create_user_embed(user)
await sendable(embed=embed)
@commands.hybrid_command(
name="fetchuser", description="Fetch a user by ID and show info."
)
async def fetchuser(self, ctx: commands.Context, user_id: str):
"""Fetch a Discord user by ID."""
try:
user_id_int = int(user_id)
except ValueError:
await ctx.send("❌ Invalid user ID provided.")
return
await self._fetch_user_and_send(ctx.send, user_id_int)
async def setup(bot: commands.Bot):
await bot.add_cog(FetchUserCog(bot))