我尝试使用 postgreSQL 为我的 Discord bot 设置自定义前缀,使用 python 作为前端

时间:2021-07-17 14:53:25

标签: python postgresql discord.py

DEFAULT_PREFIX = '>>'

async def get_prefix(bot, message):
    if not message.guild:
        return commands.when_mentioned_or(DEFAULT_PREFIX)(bot, message)
    prefix = await my_bot.db.fetchrow('SELECT prefix FROM guilds WHERE guild_id = $1', message.guild.id)
    if len(prefix) == 0:
        await my_bot.db.execute('INSERT INTO guilds (guild_id, prefix) VALUES ($1, $2)', message.guild.id, DEFAULT_PREFIX)
        prefix = DEFAULT_PREFIX
    else:
        prefix = prefix[0].get("prefix")
    return commands.when_mentioned_or(prefix)(bot, message)


intents = discord.Intents().all()
intents.members = True
my_bot = MyBot(command_prefix = get_prefix, case_insensitive = True, intents = intents)
my_bot.remove_command('help')


async def create_db_pool():
    my_bot.db = await asyncpg.create_pool(database = 'tutorial', user = 'postgres', password = 'SHOCKface123!@#')
    print('Connection succesfull')


@my_bot.command()
@commands.has_permissions(administrator = True)
async def chgprefix(ctx, *, new_prefix):
    await my_bot.db.execute('UPDATE guilds SET prefix = $1 WHERE guild_id = $2', new_prefix, ctx.guild.id)
    await ctx.send('changed prefix')

错误:

File "C:\Users\SBA3\Desktop\dasboard\print.py", line 39, in get_prefix
if len(prefix) == 0:
TypeError: object of type 'NoneType' has no len()

1 个答案:

答案 0 :(得分:0)

看起来您的查询 prefix = await my_bot.db.fetchrow('SELECT prefix FROM guilds WHERE guild_id = $1', message.guild.id) 正在选择一列(前缀),而不是整行。这意味着如果不存在具有该公会 ID 的行,它将返回 None,因为这样的列不存在。

尝试用 SELECT * FROM guilds ... 替换查询。