Discord.py 使用 sqlite3 设置自定义公会前缀

时间:2021-04-25 13:42:35

标签: python discord.py

我正在用 Python 和 sqlite3 制作一个 Discord 机器人。它基本上是一个多用途的机器人,可以用于很多事情。它的功能之一是公会的自定义前缀 - 但是,机器人似乎没有响应我发送的新前缀。这是我的代码:

@bot.group(invoke_without_command=True)
async def prefix(ctx):
    await ctx.send("**Prefix command configuration:**\n\nSet new prefix: `j!prefix new <prefix>`")

实际的命令:

@prefix.command()
async def new(ctx, new_pr):
    if ctx.message.author.guild_permissions.manage_messages:
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT prefix FROM main WHERE guild_id = {ctx.guild.id}")
        prefix = cursor.fetchone()
        if prefix is None:
            sql = ("INSERT INTO main(guild_id, prefix) VALUES(?,?)")
            val = (ctx.guild.id, new_pr)
            prefixsetem = discord.Embed(title=f"<:Success:835190431758549043> **{ctx.guild.name}**'s prefix set to `{new_pr}`", description=f"Set by **{ctx.author}**", color=0x03fc45)
            await ctx.send(embed=prefixsetem)
        elif prefix is not None:
            sql = ("UPDATE main SET prefix = ? WHERE guild_id = ?")
            val = (new_pr, ctx.guild.id)
            prefixsetem = discord.Embed(title=f"<:Success:835190431758549043> **{ctx.guild.name}**'s prefix updated to `{new_pr}`", description=f"Updated by **{ctx.author}**", color=0x03fc45)
            await ctx.send(embed=prefixsetem)
        cursor.execute(sql, val)
        db.commit()
        cursor.close()
        db.close()

我的 bot = commands.Bot:

bot = commands.Bot(command_prefix=prefix, intents=intents, help_command=PrettyHelp(active_time=120, color=0xf5b642, ending_note="j! help <command> for information about a command - select reactions to move to next pages or to delete this message", show_index=False, page_left="⏪", page_right="⏩", remove="?"))

(prefix是我之前在代码中设置的一个变量,叫做prefix="j!")

机器人似乎根本不响应新前缀;但是,前缀看起来已经正确存储在我的 SQLite3 数据库(称为“main”)中。我在这里做错了什么,也许是调用 bot = commands.Bot 的部分?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以通过函数获取每个公会的前缀。

def get_prefix(bot, message):
    db = sqlite3.connect("main.sqlite")
    cur = db.cursor()
    cur.execute("SELECT prefix FROM main WHERE guild_id = ?", (message.guild.id))
    prefix = cur.fetchone()
    if len(prefix):
        prefix = prefix[0]
    else:
        prefix = "!" #return default prefix if guild not saved in database.
    db.close()
    return prefix

而不是commands.Bot

bot = commands.Bot(command_prefix=get_prefix, ...)
相关问题