python - TypeError : tuple indices must be integers or slices, 命令中不是 str

标签 python python-3.x discord.py

嗨,我收到此错误:TypeError:元组索引必须是整数或切片,而不是命令中的 str 在此命令上,我有点不确定这里出了问题。这是我正在使用的代码:

@checks.can_embed()
@commands.command(name="botinfo")
async def botinfo(self, ctx: UKGCtx):
    """Shows advanced information about the bot."""
    char_count = 0
    deaths_count = 0
    levels_count = 0
    with closing(userDatabase.cursor()) as c:
        c.execute("SELECT COUNT(*) as count FROM chars")
        result = c.fetchone()
        if result is not None:
            char_count = result["count"]
        c.execute("SELECT COUNT(*) as count FROM char_deaths")
        result = c.fetchone()
        if result is not None:
            deaths_count = result["count"]
        c.execute("SELECT COUNT(*) as count FROM char_levelups")
        result = c.fetchone()
        if result is not None:
            levels_count = result["count"]

最佳答案

fetchone返回一个序列(在本例中是一个元组)或None,而不是字典。

如果您希望它返回字典,您可以替换 Connection.row_factory就像文档中的这个示例一样:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

关于python - TypeError : tuple indices must be integers or slices, 命令中不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593121/

相关文章:

python - 如何使用 isinstance 测试所有可能的整数类型

python - 我无法列出 Raspberry Pi 附近的 BLE 设备(python、btmgmt)

python - Postgres 咨询锁不起作用

python - 如何在Python中找到矩阵最大数的索引?

python - 尝试更改机器人的状态

python - 谷歌应用程序引擎,Django : Tables are not made in Google cloud SQL after deployment

python-3.x - 如何在aws Glue中将json写回s3?

python - 使用 subprocess.call 从 Python 中调用 awk 时出现问题

python - 有没有办法检查 Discord 上的 message.content 是否包含文件?

Python 获取特定角色的所有成员列表