如何在discord.py中将on_message与sqlite3集成?

时间:2020-08-29 08:59:15

标签: python sqlite discord discord.py

我创建了一个on_message事件,每当您在特定频道中提到3个人时,该事件便会赋予您角色,现在我正尝试将其与数据库集成,以便可以在多个行会上使用。

我写的是

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!")

从现在开始,我认为问题出在on_message部分,channel.idchannel-idrole尚未定义,但是即使我定义了它们也仍然无法使用

2 个答案:

答案 0 :(得分:0)

f字符串可能会引起问题,请尝试此操作。

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

答案 1 :(得分:0)

首先,如果您在on_message事件下连接到数据库,这将降低机器人的效率。对于其他问题,您必须像这样更改命令参数

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

代替这些role: discord.Role channel: discord.TextChannel

然后,当您要呼叫频道或角色时,必须使用discord.utils.get

对于渠道:

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

对于角色:

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

因此,当用户使用rolechannel命令时,他们必须编写确切的频道。

当您将频道ID与数据库进行比较时,您也可以像这样使用discord.utils.get

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.")

然后if not channel_in_database.id == ctx.channel.id:,或者您可以(我不确定100%会行得通)从该行会的数据库中获取频道名称,然后执行以下操作:

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

如果其中之一引起任何问题,或者您仍然有未解决的问题,请发表评论