首页 > 解决方案 > Discord.py 数据库 NameError 'conn' 未使用 asyncpg 定义

问题描述

我正在为关卡系统编写我的第一个不和谐机器人,并且一直停留在数据库中。我最初使用 aiosqlite 并将其托管在 replit 上,它运行良好,直到我注意到部分数据只是被随机删除。所以我尝试使用 postgres,但它不断出现

NameError: name 'conn' is not defined

我尝试使用大象SQL,以及 Heroku 免费数据库。真的不知道我能做些什么来让它运行,除了数据库问题之外,其他一切似乎都很好。

这是代码的连接部分:

async def initialize():
    await bot.wait_until_ready()
    conn = await asyncpg.connect(DATABASE_URL)
    await conn.execute('''CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, study_time int, PRIMARY KEY (guild_id, user_id))''')


@bot.event
async def on_ready():
    print(bot.user.name + " is online.")


@bot.command()
async def studying(ctx, start_hr: int, start_min: int, stop_hr: int, stop_min: int, member: discord.Member=None):
  if member is None: member = ctx.author
  async with conn.execute('''INSERT OR IGNORE INTO guildData (guild_id, user_id, study_time) VALUES ((?, ?, ?)''', (ctx.guild.id, ctx.author.id, 0)) as cursor:

我究竟做错了什么?谢谢!

标签: pythonpostgresqldiscorddiscord.py

解决方案


推荐阅读