Files
bot.py
requirements.txt
Code
2 293
bot.py
import discord
from discord.ext import commands
import os
import asyncio
from dotenv import load_dotenv
from datetime import datetime
sent_dms = []
load_dotenv()
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
active_vc = None
@bot.event
async def on_ready():
print(f'{bot.user} is ready!')
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="over Ironwood"))
@bot.event
async def on_voice_state_update(member, before, after):
global active_vc
# User joined a voice channel
if after.channel and before.channel != after.channel:
# Bot isn't in any VC yet, join
if active_vc is None or not active_vc:
try:
vc = await after.channel.connect()
active_vc = vc
print(f"Joined VC: {after.channel.name}")
except Exception as e:
print(f"Failed to join VC: {e}")
# Bot is in a different VC, move to this one
elif active_vc and active_vc.channel != after.channel:
try:
await active_vc.move_to(after.channel)
print(f"Moved to VC: {after.channel.name}")
except Exception as e:
print(f"Failed to move VC: {e}")
# User left VC - check if voice channel is now empty
if before.channel and after.channel != before.channel:
if active_vc and active_vc.channel == before.channel:
members_in_channel = [m for m in before.channel.members if not m.bot]
if len(members_in_channel) == 0:
try:
await active_vc.disconnect()
active_vc = None
print(f"Left VC: {before.channel.name} (empty)")
except Exception as e:
print(f"Failed to disconnect: {e}")
@bot.event
async def on_message(message):
if message.author.bot:
return
content_lower = message.content.lower()
for word in BANNED_WORDS:
if word in content_lower:
member = message.author
try:
await message.delete()
await message.channel.send(f"{member.mention} Watch your language!", delete_after=3)
except:
pass
# If user is in a voice channel, mute them temporarily
if member.voice and member.voice.channel:
try:
await member.edit(mute=True)
await asyncio.sleep(30)
await member.edit(mute=False)
except:
pass
break
await bot.process_commands(message)
@bot.command()
async def rank(ctx, *, username: str = None):
"""Assign the Ranked role to a user by their Discord username."""
if username is None:
await ctx.send("Usage: `!rank <username>`")
return
member = discord.utils.get(ctx.guild.members, name=username)
if member is None:
member = discord.utils.find(
lambda m: m.display_name == username or str(m) == username,
ctx.guild.members
)
if member is None:
await ctx.send(f"Could not find user `{username}` in this server.")
return
role = discord.utils.get(ctx.guild.roles, name="Ranked")
if role is None:
try:
role = await ctx.guild.create_role(name="Ranked", color=discord.Color.green())
except discord.Forbidden:
await ctx.send("I don't have permission to create roles. Please create a 'Ranked' role manually.")
return
try:
await member.add_roles(role)
await ctx.send(f"Ranked {member.mention} with the `{role.name}` role!")
except discord.Forbidden:
await ctx.send("I don't have permission to assign roles to that user.")
except Exception as e:
await ctx.send(f"An error occurred: {e}")
@bot.command()
async def dm(ctx, action: str = None, *, message: str = None):
"""Send a plain-text DM to every member in the server. Admin only."""
if action is None or action.lower() != "all" or message is None:
await ctx.send("Usage: `!dm all <message>`")
return
if not ctx.author.guild_permissions.administrator:
await ctx.send("Only administrators can use this command.")
return
if not ctx.guild:
await ctx.send("This command can only be used in a server.")
return
status_msg = await ctx.send("Sending DMs...")
success = 0
failed = 0
total = 0
for member in ctx.guild.members:
if member.bot:
continue
total += 1
try:
msg = await member.send(message)
sent_dms.append(msg)
success += 1
await asyncio.sleep(1)
except discord.Forbidden:
failed += 1
except discord.HTTPException as e:
failed += 1
if e.status == 429:
await asyncio.sleep(5)
else:
await asyncio.sleep(1)
await status_msg.edit(content=f"DM broadcast complete! Sent: {success}/{total}, Failed: {failed}")
@bot.command()
@commands.has_permissions(administrator=True)
async def deleteallmessages(ctx):
"""Delete all DMs the bot sent this session."""
if not sent_dms:
await ctx.send("No DMs to delete.")
return
status = await ctx.send(f"Deleting {len(sent_dms)} DM(s)...")
deleted = 0
failed = 0
for msg in sent_dms:
try:
await msg.delete()
deleted += 1
await asyncio.sleep(0.5)
except (discord.Forbidden, discord.HTTPException, AttributeError):
failed += 1
sent_dms.clear()
await status.edit(content=f"Deleted {deleted} DM(s), failed: {failed}")
class SupportView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Open Support Ticket", style=discord.ButtonStyle.blurple, emoji="🎫")
async def open_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
modal = SupportModal()
await interaction.response.send_modal(modal)
class SupportModal(discord.ui.Modal, title="Support Request"):
username = discord.ui.TextInput(
label="In-Game Username",
placeholder="Your Minecraft username...",