【问题标题】:Discord.py and SQL - Comparing between 2 tables in the same database fileDiscord.py 和 SQL - 比较同一数据库文件中的 2 个表
【发布时间】:2021-07-25 09:19:23
【问题描述】:

所以我有两个表,Servers 和 Strikes。在服务器表中,我有一个最大罢工值。我想将用户的攻击次数与服务器表中指定的最大攻击次数进行比较。我试过这个:

@commands.command(name='strike', pass_ctx= True)
@commands.has_permissions(manage_messages=True)

async def strike(self, ctx, member : discord.Member):
    
    first_strike = 1
    
    
    cursor = await self.client.db.cursor()
    await cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
    result = await cursor.fetchone()
    
    if result == None:
        
        cursor = await self.client.db.cursor()
            
        sql = f"INSERT INTO Strikes(Guild_ID, User_ID, Strikes_Have) VALUES({ctx.guild.id}, {member.id}, {first_strike})"
            
    
    else:
        
        cursor = await self.client.db.cursor()
            
        sql = f"UPDATE Strikes SET Strikes_Have = Strikes_Have + 1 where Guild_ID = {ctx.guild.id} AND User_ID = {member.id}"
        
        if result["Strikes_Have"] == result["MAX_STRIKES"]:
            await ctx.message.channel.send(f"{member} has the max amount of stirkes specified by the server")
            
            
    await cursor.execute(sql)
    await self.client.db.commit()
    await cursor.close()
            
    await ctx.message.channel.send(f"Striked {member}")`

但是得到了这个错误:

Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/pi/EndorCore/cogs/Mod.py", line 225, in strike
    if result["Strikes_Have"] == result["MAX_STRIKES"]:
IndexError: No item with that key

【问题讨论】:

    标签: python sqlite discord.py


    【解决方案1】:

    您当前收到的错误消息是由于您尝试访问罢工表中不存在的数据列引起的。 要获得最大罢工值,您需要查询该表并获取数字,然后将两者进行比较。 例如:

    cursor.execute(f"SELECT Strikes_Have FROM Strikes WHERE Guild_ID = {ctx.guild.id} AND User_ID = {member.id}")
    user_result = cursor.fetchone()
    
    cursor.execute(f"SELECT MAX_STRIKES FROM Servers WHERE Guild_ID = {ctx.guild.id}")
    server_result = cursor.fetchone()
    
    if user_result["Strikes_Have"] == server_result['MAX_STRIKES']:
        print("User has max strikes")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多