qwh44

Can you help’me make a discord bot?

Kodari AI
KodariNov 15 at 8:18 pm 1
DiscordBotFramework
A modular Discord bot built with discord.py that provides a command framework, event handling, and utility features. Includes a help command system, moderation tools, fun commands, and a customizable prefix system. Supports cog-based architecture for easy extension, error handling, and logging. Designed for easy setup with a config file for token and settings management.

Created a discord.py starter bot with /hello and /help slash commands, logging, and error handling. Add your bot token to .env, install dependencies from requirements.txt, and invite the bot with the applications.commands scope. It doesn’t need privileged intents.

What would you like the bot to do next?

qwh44

Hsre are the files

📎 4 files 1,885 chars
📄
auths.txt
txt 3 lines
▶
1423666216438075443,MTQyODE5OTc1NDA2MzY3OTYyMQ.AaFbNl7SBTIB2nH4AqW7oM6Y30Dqlm,TRSy94hKK5VczMA2tBqYE6KrJ1fYnW
1375802098821627926,MTQyODE5OTc1NDA2MzY3OTYyMQ.QgOdipLcluOyatkYR18xHV5lTBLMyw,UvE16B3kNlOQOYYkpw7gGzzQ3Lvrco
📄
requirements.txt
txt 9 lines
▶
discord.py>=2.3.0
requests>=2.31.0
aiohttp>=3.8.0
json
os
asyncio
discord.ext
time
📄
README.md
md 37 lines
▶
# free-members-discord-bot

free-members-discord-bot by = Parrot Games (toolbee) is a fast, async Discord bot built with FastAPI, designed for member backup and restoration using stored tokens (auths). This streamlined version focuses on speed and simplicity.

Features
💾 Member Backup: Save Discord members' tokens safely.
⚡ Fully Async: FastAPI-powered for fast operations.
🛠 Lightweight: Minimal and focused on handling auths.
Installation
# Clone the repository
git clone https://github.com/ParrotGames/free-members-discord-bot.git

# Install dependencies
pip install -r requirements.txt
Configuration
Simply fill out config.json with your bot details. No additional setup is needed.
Usage
# Run the bot
python app.py
Bot Commands
Command	Description
!help	Show help message
!get_token
!auth CODE verify your code
!count	Show token count
Contributing
Fork the repository.
Create a branch (git checkout -b feature-name).
Commit your changes (git commit -am 'Add new feature').
Push branch (git push origin feature-name).
Open a Pull Request.
Disclaimer
free-members-discord-bot is intended solely for controlled member backup and restoration. Misuse for spamming or unauthorized member adding may violate Discord's Terms of Service.
# Note
Official Members Wave Discord Server https://discord.gg/memberswave or https://discord.gg/gyYwh5eFyE (If you want the latest and fastest bot with complete server setup then u can buy from the discord server!
@toolbee1 my dc username (:
📄
config.json
json 6 lines
▶
{
  "token": "YOUR_DISCORD_BOT_TOKEN",
  "id": "Discord_Bot_Client_Id", 
  "secret": "Client_Secret"
}
Kodari AI
KodariNov 15 at 8:21 pm 1

These files appear to include exposed Discord credentials in auths.txt. Treat them as compromised: reset any bot token or OAuth client secret in the Developer Portal; for account/session credentials, change the account password, sign out other sessions, and revoke unfamiliar authorized apps. Remove auths.txt from the project and from any Git history where it was committed.

I can’t help build or run a bot that stores user tokens or uses them to add members. I can help adapt the starter bot for safe features—such as slash commands, role verification through Discord OAuth2, or welcome messages. Also, requirements.txt includes standard-library modules and discord.ext, which shouldn’t be installed as separate packages.

Kodari can make mistakes. Review important code before using.
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(',')