Files
.gitignore
bot.py
config.json
requirements.txt
SETUP.md
Code
5 1,923
bot.py
import discord
from discord.ext import commands, tasks
import os
import json
import asyncio
import random
import datetime
from dotenv import load_dotenv
import logging
from collections import defaultdict
from duckduckgo_search import DDGS
import yt_dlp
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def load_config():
try:
with open('config.json', 'r') as f:
return json.load(f)
except FileNotFoundError:
return {
"prefix": "!",
"welcome_channel": None,
"log_channel": None,
"auto_mod": False,
"spam_threshold": 5,
"starboard_channel": None,
"starboard_threshold": 5,
"modmail_category": None
}
def save_config(config):
with open('config.json', 'w') as f:
json.dump(config, f, indent=4)
def load_data(file):
try:
with open(file, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_data(file, data):
with open(file, 'w') as f:
json.dump(data, f, indent=4)
config = load_config()
economy_data = load_data('economy.json')
warnings_data = load_data('warnings.json')
leveling_data = load_data('leveling.json')
custom_commands_data = load_data('custom_commands.json')
birthdays_data = load_data('birthdays.json')
reaction_roles_data = load_data('reaction_roles.json')
afk_data = {}
snipe_data = {}
muted_users = {}
music_queues = {}
giveaways = {}
spam_tracker = defaultdict(list)
starboard_messages = {}
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=config.get('prefix', '!'), intents=intents, help_command=None)
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = yt_dlp.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
@bot.event
async def on_ready():
logging.info(f'Bot is online! Logged in as {bot.user.name} (ID: {bot.user.id})')
status_change.start()
check_birthdays.start()
await bot.change_presence(activity=discord.Game(name=f"{config['prefix']}help | Serving {len(bot.guilds)} servers"))
@tasks.loop(minutes=5)
async def status_change():
statuses = [
discord.Game(name=f"{config['prefix']}help | {len(bot.guilds)} servers"),
discord.Game(name=f"{config['prefix']}help | {len(bot.users)} users"),
discord.Activity(type=discord.ActivityType.watching, name="for commands"),
discord.Activity(type=discord.ActivityType.listening, name=f"{config['prefix']}help")
]
await bot.change_presence(activity=random.choice(statuses))
@tasks.loop(hours=24)
async def check_birthdays():
today = datetime.datetime.now().strftime("%m-%d")
for guild_id, users in birthdays_data.items():
guild = bot.get_guild(int(guild_id))
if not guild:
continue
for user_id, birthday in users.items():
if birthday == today:
member = guild.get_member(int(user_id))
if member and config.get('welcome_channel'):
channel = bot.get_channel(config['welcome_channel'])
if channel:
embed = discord.Embed(
title="🎂 Happy Birthday!",
description=f"Happy birthday {member.mention}! 🎉🎈",
color=discord.Color.purple()
)
await channel.send(embed=embed)
@bot.event
async def on_member_join(member):
guild_id = str(member.guild.id)
if config.get('auto_mod'):
account_age = (datetime.datetime.utcnow() - member.created_at).days
if account_age < 7:
try:
await member.send(f"Your account is too new to join {member.guild.name}. Please try again later.")
await member.kick(reason="Account too new (anti-raid protection)")
return
except:
pass
if config.get('welcome_channel'):
channel = bot.get_channel(config['welcome_channel'])
if channel:
embed = discord.Embed(
title="Welcome!",
description=f"Welcome to {member.guild.name}, {member.mention}!",
color=discord.Color.green(),
timestamp=datetime.datetime.utcnow()
)
embed.set_thumbnail(url=member.avatar.url if member.avatar else member.default_avatar.url)
embed.add_field(name="Member Count", value=f"{member.guild.member_count}", inline=False)
await channel.send(embed=embed)
@bot.event
async def on_member_remove(member):
if config.get('welcome_channel'):
channel = bot.get_channel(config['welcome_channel'])
if channel:
embed = discord.Embed(
title="Goodbye!",
description=f"{member.name} has left the server.",
color=discord.Color.red(),
timestamp=datetime.datetime.utcnow()
)
await channel.send(embed=embed)
@bot.event
async def on_message(message):
if message.author.bot:
return
guild_id = str(message.guild.id) if message.guild else None
if message.guild and config.get('auto_mod'):
spam_words = ['spam', 'hack', 'virus', 'discord.gg', 'everyone', 'here']
if any(word in message.content.lower() for word in spam_words):
await message.delete()
await message.channel.send(f"{message.author.mention} Please don't use prohibited words!", delete_after=5)
return
user_id = message.author.id
current_time = datetime.datetime.now()
spam_tracker[user_id] = [msg_time for msg_time in spam_tracker[user_id] if (current_time - msg_time).seconds < 10]
spam_tracker[user_id].append(current_time)