开发Discord邀请管理器遇TypeError:协程不支持异步上下文管理器
问题解决:Discord机器人邀请管理器on_member_join事件报错
错误原因
- 错误使用异步上下文管理器:
cursor.execute()是协程函数,调用后返回协程对象,而非支持async with的异步上下文管理器,因此不能用async with cursor.execute(...) as cursor这种写法。 - SQL参数格式错误:
(member.guild.id)不是元组(缺少末尾逗号),会导致SQL执行时参数不匹配,正确的元组写法是(member.guild.id,)。
修正步骤
- 移除
async with包裹cursor.execute(),改用await执行SQL语句。 - 修正SQL参数的元组格式,添加末尾逗号。
- 直接使用原
cursor对象进行结果遍历,无需重新赋值。
修正后的完整代码
# Member Join Event @commands.Cog.listener() async def on_member_join(self, member): async with aiosqlite.connect(self.DB) as db: async with db.cursor() as cursor: invites = await member.guild.invites() # 简化日期判断逻辑 today = datetime.today() account_age_days = (today - member.created_at.date()).days # 修正SQL执行方式和参数格式 await cursor.execute("SELECT id, uses FROM invites WHERE guild_id = ?", (member.guild.id,)) async for invite_id, old_uses in cursor: for invite in invites: if invite.id == invite_id and invite.uses - old_uses > 0: if account_age_days >= 7: print(invite.id) await cursor.execute("UPDATE invites SET uses = uses + 1 WHERE guild_id = ? AND id = ?", (invite.guild.id, invite.id)) await cursor.execute("INSERT OR IGNORE INTO joined (guild_id, inviter_id, joiner_id) VALUES (?,?,?)", (invite.guild.id, invite.inviter.id, member.id)) await cursor.execute("UPDATE totals SET normal = normal + 1 WHERE guild_id = ? AND inviter_id = ?", (invite.guild.id, invite.inviter.id)) else: await cursor.execute("UPDATE totals SET normal = normal + 1, fake = fake + 1 WHERE guild_id = ? and inviter_id = ?", (invite.guild.id, invite.inviter.id)) return await db.commit()
额外优化说明
- 简化了账号创建日期的判断逻辑,直接计算日期差,避免字符串拆分和多变量赋值,更简洁易读。
- 确保所有SQL执行语句都使用
await调用,符合aiosqlite的异步操作规范。
内容的提问来源于stack exchange,提问作者MrZCookie
相关产品推荐
相关产品推荐

