databasediscordcommanddiscord.pyblacklist

I want to make a blacklist command that blocks an invite from a specific guild discord.py


I'm pretty new to all of this. I want to make a command that blocks user from sending a link from blacklisted guild. The command would look like this: !blacklist (guild id) reason This is the code so far

async def server_blacklist(ctx, guild_id: int,*,reason= "no reason provided"):
    guild = client.get_guild(guild_id)
    invitelink = await delete_invite(guild)

My 1st thought is that I need to store the guild ids somehow ( in .txt or .db ). But I don't know how.


Solution

  • My previous answer was unsatisfying, so here's a new one: If you wanna write to files, I suggest this page.

    And a more thorough explanation of the method of blacklisting a certain guild:

    The method I found that you could use for blacklisting just certain guilds is much simpler than I thought before, invite objects have a guild property, so you can easily check.

    A "simple" example of how to do what you want to do is:

    @client.command()
    async def server_blacklist(ctx, guild_id: int):  # Blacklisting command
        # To add a guild id to the file:
        with open("blacklisted guilds.txt", "a") as blacklistfile:  # Open file in append mode
            blacklistfile.write(f"{guild_id}\n")  # Add a new line with the guild id
    
    
    @client.event
    async def on_message(message):  # Event that triggers every time a message is sent
        if "discord.gg" in message.content:  # Check if message has "discord.gg"
            inviteid = message.content.split("discord.gg/")[1].split(" ")[0]  # Get the invite id from the link
            invite = await client.fetch_invite(inviteid)  # Get the invite object from the id
            guild_id = invite.guild.id  # Get the guild id
            # To retrieve the guild ids and check against another
            with open("blacklisted guilds.txt", "r") as blacklistfile:  # Open file in reading mode
                for idstring in blacklistfile.read().split("\n"):  # Start iterating through all the lines
                    if not idstring == "":  # Check if line has content
                        if int(idstring) == guild_id:  # Check if the id from the file is the same as guild_id
                            await message.delete()
                            await message.channel.send(f"{message.author.mention}! Don't send invites to that server here!")
                            break  # Stop the for loop, since we have already matched the guild id to a blacklisted one
    
        await client.process_commands(message)  # When using the on_message event and commands, remember to add this, so that the commands still work