Files
.gitignore
bot.py
requirements.txt
Code
3 777
bot.py
import discord
import requests
import json
import os
import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta
import time
from urllib.parse import urlencode
print("🚀 STARTING BOT...")
# Load config
try:
with open('config.json', 'r') as f:
config = json.load(f)
BOT_TOKEN = config['token']
CLIENT_ID = config['id']
CLIENT_SECRET = config['secret']
MAIN_SERVER = 1437381878310109185 # Your main server ID
print(f"✅ Config loaded")
print(f"🔑 Token: {BOT_TOKEN[:20]}...")
print(f"🆔 Client ID: {CLIENT_ID}")
print(f"🔒 Secret: {CLIENT_SECRET[:8]}...")
print(f"🏠 Main Server: {MAIN_SERVER}")
except Exception as e:
print(f"❌ Config error: {e}")
exit(1)
# Create bot
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=['!', '?'], intents=intents)
bot.remove_command("help")
# Store server join times
server_join_times = {}
@bot.event
async def on_ready():
print(f'🎯 Bot is ready: {bot.user}')
print(f'📋 Loaded commands: {[command.name for command in bot.commands]}')
# Initialize server join times
for guild in bot.guilds:
if guild.id != MAIN_SERVER:
server_join_times[guild.id] = datetime.now()
print(f"📝 Tracking server: {guild.name} ({guild.id})")
# Start the cleanup task
check_server_ages.start()
@tasks.loop(hours=24) # Run once per day
async def check_server_ages():
"""Check servers and leave if they're older than 14 days (except main server)"""
print("🔍 Checking server ages...")
for guild in bot.guilds:
if guild.id == MAIN_SERVER:
continue # Never leave main server
guild_id = guild.id
guild_name = guild.name
guild_age = None
# Calculate age
if guild_id in server_join_times:
join_time = server_join_times[guild_id]
guild_age = datetime.now() - join_time
else:
# If we don't have a join time, assume we joined now
server_join_times[guild_id] = datetime.now()
guild_age = timedelta(0)
if guild_age >= timedelta(days=14):
try:
print(f"🚪 Leaving server {guild_name} ({guild_id}) - Age: {guild_age.days} days")
await guild.leave()
# Send notification to main server
main_guild = bot.get_guild(MAIN_SERVER)
if main_guild:
# Find first text channel bot can send to
for channel in main_guild.text_channels:
if channel.permissions_for(main_guild.me).send_messages:
embed = discord.Embed(
title="🚪 Bot Left Server",
description=f"**Server:** {guild_name}\n**ID:** {guild_id}\n**Reason:** Server age ({guild_age.days} days) exceeded 14 days",
color=0xED4245,
timestamp=datetime.now()
)
await channel.send(embed=embed)
break
# Remove from tracking
if guild_id in server_join_times:
del server_join_times[guild_id]
except Exception as e:
print(f"❌ Error leaving server {guild_name}: {e}")
else:
print(f"✅ Server {guild_name} is {guild_age.days} days old - OK")
@bot.event
async def on_guild_join(guild):
"""Track when bot joins a new server"""
if guild.id != MAIN_SERVER:
server_join_times[guild.id] = datetime.now()
print(f"📝 Bot joined new server: {guild.name} ({guild.id})")
# Send notification to main server
main_guild = bot.get_guild(MAIN_SERVER)
if main_guild:
for channel in main_guild.text_channels:
if channel.permissions_for(main_guild.me).send_messages:
embed = discord.Embed(
title="🏠 Bot Joined Server",
description=f"**Server:** {guild.name}\n**ID:** {guild.id}\n**Members:** {guild.member_count}\n**Will leave after:** 14 days",
color=0x57F287,
timestamp=datetime.now()
)
await channel.send(embed=embed)
break
@bot.event
async def on_guild_remove(guild):
"""Remove server from tracking when bot leaves"""
if guild.id in server_join_times:
del server_join_times[guild.id]
print(f"🗑️ Removed tracking for server: {guild.name} ({guild.id})")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(f"❌ Command not found. Use `!help` to see available commands.")
else:
print(f"❌ Command error: {error}")
def refresh_access_token(refresh_token):
"""Refresh an expired access token"""
try:
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
response = requests.post('https://discord.com/api/v10/oauth2/token', data=data)
if response.status_code == 200:
return response.json()
else:
print(f"❌ Token refresh failed: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"❌ Token refresh error: {e}")
return None
def get_valid_token(user_id, access_token, refresh_token):
"""Get a valid access token, refreshing if needed"""
# First test if current token works
headers = {'Authorization': f'Bearer {access_token}'}
test_response = requests.get('https://discord.com/api/v10/users/@me', headers=headers)
if test_response.status_code == 200:
return access_token # Token is still valid
# Token is invalid, try to refresh
print(f"🔄 Token expired for user {user_id}, refreshing...")
new_tokens = refresh_access_token(refresh_token)
if new_tokens:
# Update the token in auths.txt
update_token_in_file(user_id, new_tokens['access_token'], new_tokens['refresh_token'])
return new_tokens['access_token']
else:
print(f"❌ Failed to refresh token for user {user_id}")
return None
def update_token_in_file(user_id, new_access_token, new_refresh_token):
"""Update tokens in auths.txt file"""
try:
if not os.path.exists('auths.txt'):
return False
with open('auths.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
updated = False
new_lines = []
for line in lines:
line = line.strip()
if not line:
continue
parts = line.split(',')