【问题标题】:Trying to use SQL and discord.py to make a warn command that can show how many times a user has been warned尝试使用 SQL 和 discord.py 制作一个警告命令,该命令可以显示用户被警告了多少次
【发布时间】:2021-06-11 01:01:21
【问题描述】:

这是我目前的代码

 @commands.command()
    @commands.has_permissions(manage_messages=True) 
    async def warn(self,ctx, user: discord.Member, *, reason=None):
        warn2= discord.Embed(title="Warning",description=(f'{user.mention} You are being warned for: {reason}'), color=0xEEA1FF)
        await ctx.send(embed=warn2)
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT warn_counter FROM warned_info WHERE user = {user.id}")
        num=cursor.fetchone()[0]
        print(num)
        if num is not None:
            cursor.execute(f"UPDATE warned_info  SET warn_counter = {num + 1} WHERE user = {user.id} ")
        db.commit()
        cursor.close()

当我警告用户(之前已经警告过)时,它会将警告数量添加到 sql 代码中,但如果我尝试警告尚未被警告的用户,它将不会添加用户并添加警告数量

this is an image of my sqlite table

【问题讨论】:

    标签: python sqlite discord.py


    【解决方案1】:

    问题是 SQL 无法更新不存在的记录。被警告的用户已经有记录,所以你可以更新它。我会在if num is not None 中添加一条 else 语句,为尚未收到警告的人创建记录,如下所示:

    if num is not None:
        cursor.execute(f"UPDATE warned_info  SET warn_counter = {num + 1} WHERE user = {user.id} ")
    else:
        cursor.execute(f"INSERT INTO warned_info (user, warn_counter) VALUES ({user.id},{1})")
    

    现在如果用户存在,他们的警告计数器会增加,否则它会创建一个警告计数器为 1 的记录。

    【讨论】:

    • 相反,如果我将用户添加到表中并将成员加入时的警告编号设置为 0,那会起作用吗?
    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2022-12-10
    • 2020-03-31
    • 2021-10-20
    相关资源
    最近更新 更多