Discord Bot in Python: Sharing variables between functions

Hey everyone! I’m new to Python and Discord bots. I’m trying to make a bot that can toggle a switch on and off. The problem is I can’t figure out how to share the switch state between different functions. Here’s a simplified version of my code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')

switch_state = False

@bot.command()
async def flip_switch(ctx):
    global switch_state
    switch_state = not switch_state
    await ctx.send(f'Switch is now {"on" if switch_state else "off"}')

@bot.event
async def on_message(message):
    if message.author.id == 12345 and switch_state:
        await message.channel.send('Switch is on and user 12345 said something')
    await bot.process_commands(message)

bot.run('YOUR_TOKEN_HERE')

I’m not sure if this is the best way to do it. Should I use a database instead? Or is there a better way to share data between bot functions? Any help would be awesome!

I’ve been down this road before, mate. Global variables can be a quick fix, but they’ll bite you in the long run. Trust me, I learned the hard way.

For your switch state, I’d recommend using a simple key-value store like Redis. It’s lightweight, fast, and perfect for this kind of thing. Plus, it’ll save your state even if your bot crashes or restarts.

Here’s a rough idea:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

@bot.command()
async def flip_switch(ctx):
    current_state = r.get('switch_state')
    new_state = not current_state
    r.set('switch_state', new_state)
    await ctx.send(f'Switch is now {\"on\" if new_state else \"off\"}')

This approach scales well and keeps your code clean. Give it a shot and see how it works for you.

Your current implementation using a global variable is functional for a small-scale bot. However, as your project expands, you might want to explore more robust solutions. Consider implementing a class-based structure to encapsulate bot functionality and state. This approach provides better organization and easier maintenance. For persistent data storage across bot restarts, a lightweight database like SQLite could be beneficial. It’s also worth looking into Discord.py’s built-in features for state management, such as the bot’s custom attributes or context variables, which might suit your needs without adding unnecessary complexity.

hey man, ur approach looks decent for a simple bot. global vars work but aren’t ideal for bigger projects. as your bot grows, consider using a class or even sqlite for state management. for now, ur code should do the trick. happy coding!