简体   繁体   中英

How to integrate on_message with sqlite3 in discord.py?

I made an on_message event that gives you role whenever you mention 3 people in a specific channel , Now I am trying to integrate it with database so it can be used on multiple guilds.

What I've write:

class ScrimsCog(commands.Cog, name='Scrims-Commands') :

        def __init__(self,bot):
            self.bot = bot
    
        @commands.Cog.listener()
        async def on_message(self,message):
            db = sqlite3.connect('main.sqlite')
            cursor = db.cursor()
            cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {message.guild.id}")
            result =  cursor.fetchone()
            if result is None:
                return
            else:
                cursor.execute(f"SELECT role FROM main WHERE guild_id = {message.guild.id}")
                if not channel.id == channel_id:
                    return
                if len(message.mentions) >= 3:
                    await message.add_reaction(emoji="<a:tick:748476262640779276>")
                role = discord.utils.get(message.guild.roles, name=role)
                user = message.author
                await user.add_roles(role)
            await self.bot.process_commands(message)
            

        
        
        @commands.group(invoke_without_command=True)
        async def scrimsmod(self,ctx):
            await ctx.send('Available Setup Commands: \nscrimsmod channel <#channel>\nscrimsmod role  <message>')
        @scrimsmod.command()
        async def channel(self, ctx, channel:discord.TextChannel):
            if ctx.message.author.guild_permissions.manage_messages:
                db = sqlite3.connect('main.sqlite')
                cursor = db.cursor()
                cursor.execute(f"SELECT channel_id FROM main WHERE guild_id = {ctx.guild.id}")
                result =  cursor.fetchone()
                if result is None:
                    sql = ("INSERT INTO main(guild_id, channel_id) VALUES(?,?)")
                    val = (ctx.guild.id, channel.id)
                    await ctx.send(f" Default Registration Channel has been set to {channel.mention}")
                elif result is not None:
                    sql = ("UPDATE main SET channel_id = ? WHERE guild_id = ?")
                    val = (channel.id, ctx.guild.id)
                    await ctx.send(f"Default Registration Channel has been updated to {channel.mention}")
                cursor.execute(sql, val)
                db.commit()
                cursor.close()
                db.close()

        @scrimsmod.command()
        async def role(self, ctx,role: discord.Role):
            if ctx.message.author.guild_permissions.manage_messages:
                db = sqlite3.connect('main.sqlite')
                cursor = db.cursor()
                cursor.execute(f"SELECT role FROM main WHERE guild_id = {ctx.guild.id}")
                result =  cursor.fetchone()
                if result is None:
                    sql = ("INSERT INTO main(guild_id, role) VALUES(?,?)")
                    val = (ctx.guild.id, role)
                    await ctx.send(f"Default role to give on correct registration have been set to `{role}`")
                elif result is not None:
                    sql = ("UPDATE main SET role = ? WHERE guild_id = ?")
                    val = (role, ctx.guild.id)
                    await ctx.send(f"Default role to give on correct registration have been updated to  `{role}`")
                cursor.execute(sql, val)
                db.commit()
                cursor.close()
                db.close()
    

def setup(bot):
    bot.add_cog(ScrimsCog(bot))
    print("Scrims cog is loaded!")

From now I think the problem is with on_message part, the channel.id , channel-id , role are undefined but even if I define them it still doesn't work.

f-string 可能会导致问题,试试这个..

cursor.execute("SELECT channel_id FROM main WHERE guild_id = ?", [message.guild.id])

At first, if you connect to the database under the on_message event, this this reduces the efficiency of your bot. And for the other problems, you have to change the commands parameters like these

async def channel(self, ctx, channel): , async def role(self, ctx,role):

instead of these role: discord.Role channel: discord.TextChannel .

Then, when you want to call the channel or the role, you must use discord.utils.get ,

for channels:

await ctx.send(f"Default Registration Channel has been updated to {discord.utils.get(ctx.guild.text_channels, name=channel).mention}")

for roles:

await ctx.send(f"Default role to give on correct registration have been updated to {discord.utils.get(ctx.guild.roles, name=role)}")

So when the users using the role or channel commands, they must write the exact channel.

And when you comparing the channel id with the database, you can also use discord.utils.get like this:

channel_in_database = discord.utils.get(ctx.guild.text_channels, name="in here, you need to connect to the database and take the channel name for this guild.")

then, if not channel_in_database.id == ctx.channel.id: , or maybe you can(I'm not 100% sure that will work) take the channel name from database for that guild and do:

if "channel name from the database" == ctx.channel.name

If one of these raises any problem or if you still have unanswered problems, just comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM