You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为基于SQLite的Discord警告命令添加警告次数统计?

解决Discord机器人警告次数统计问题

要实现用户警告次数的统计,只需在插入警告记录后,执行一条统计查询语句,获取该用户在当前服务器的警告总数即可。以下是修改后的完整代码:

import discord
from discord.ext import commands
import sqlite3

class warn(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def warn(self, ctx, member: discord.Member, reason=None):
        db = sqlite3.connect("warn.db")
        cursor = db.cursor()
        # 插入警告记录
        sql_insert = "INSERT INTO main (user_id, reason, guild) VALUES (?, ?, ?)"
        val_insert = (member.id, reason, ctx.guild.id)
        cursor.execute(sql_insert, val_insert)

        # 统计当前用户在该服务器的警告次数
        sql_count = "SELECT COUNT(*) FROM main WHERE user_id = ? AND guild = ?"
        cursor.execute(sql_count, (member.id, ctx.guild.id))
        warn_count = cursor.fetchone()[0]  # 获取查询结果中的计数

        em = discord.Embed(
            description=f"<:zztick:1067013663535411280> | warned **{member.mention}** for the reason: *{reason}*",
            color=0x2F3136
        )
        em.set_footer(text=f"warn no. {warn_count}")  # 替换为实际统计次数
        await ctx.send(embed=em)
        
        db.commit()
        db.close()

async def setup(bot):
    await bot.add_cog(warn(bot))

关键修改说明

  • 新增统计查询语句:通过COUNT(*)统计指定user_id和guild下的记录数,确保只统计当前服务器内该用户的警告次数
  • 使用cursor.fetchone()[0]获取统计结果,因为fetchone()返回的是元组,取第一个元素即为次数
  • 将统计结果嵌入到消息footer中,替换原占位符

内容的提问来源于stack exchange,提问作者ITACHI UCHIHA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:10:28