How to store server-specific settings for a Discord bot in Python?

I’m working on a Discord bot in Python and I want to add a feature to block certain types of links in chat. But I realized not all server owners might want this feature.

I’m wondering how to make this feature toggleable for each server and save those settings. Here’s what I’m thinking:

def check_links(message):
    if message.content.startswith('http'):
        # Check against a list of blocked domains
        return True
    return False

@bot.event
async def on_message(message):
    if check_links(message) and server_settings[message.guild.id]['block_links']:
        await message.delete()
        await message.channel.send('Links are not allowed here!')

But how do I set up server_settings to store each server’s preferences? And where should I save this data so it persists when the bot restarts? Any tips on implementing this kind of server-specific configuration would be super helpful!

I’ve tackled this issue before in my Discord bots. A simple yet effective solution is using JSON files to store server-specific settings. Here’s how I do it:

Create a ‘servers’ directory in your bot’s folder. For each server, make a JSON file named after its ID (e.g., ‘123456789.json’). In this file, store the server’s settings as key-value pairs.

When your bot processes a message, load the server’s JSON file, check the relevant setting, and act accordingly. If the file doesn’t exist, create it with default settings.

This approach is lightweight, easy to implement, and doesn’t require external databases. It’s served me well for smaller to medium-sized bots. Just remember to handle file I/O operations carefully to avoid performance issues with larger scales.

To manage server-specific settings, using a database such as SQLite or MongoDB is a practical approach. When the bot joins a server, add a new record with default preferences, and allow server administrators to change these options via commands. During message handling, retrieve the server’s settings from the database and verify whether features like link blocking are enabled. This method ensures that your bot retains its configuration even after a restart. In my experience, leveraging sqlite3 in Python provides a straightforward and reliable solution.

hey man, have u tried using a config file? its pretty easy to set up. just make a .ini or .yaml file for each server and store their settings there. when ur bot starts up, load the configs into memory. then u can access em quickly during runtime. works great for me, might be worth a shot for ur link blocking thing