TypeError: must be str, not int Python Discord bot 创建嵌入的数组问题

时间:2021-03-08 22:35:22

标签: python discord discord.py

无法找出此代码的最后一行有什么问题(下面还有更多内容,只是想弄清楚为什么会出错!如果有人能提供帮助,将不胜感激。

试图在不和谐嵌入中创建多个字段。我觉得这是一个简单的解决方案,但我不知道我在哪里绊倒了。

代码完全可以等待 ctx.channel.send(answers) 而 answers 是一个函数数组。

    try:
        idCell = modsheet.find(str(idTag), in_column=1)
        
        #pull the entire row and put it as a string
        answers = modsheet.row_values(idCell.row)
        await ctx.channel.send(answers)

        answers.remove(answers[0])
        for y in answers:
            modAppEmbed.add_field(name="Q" + str(y) + " Answer: ", value=str(answers[y]))
        
        modchatchannel = bot.get_channel(814629441967357992)
        await modchatchannel.send(embed=modAppEmbed)

2021-03-08T22:48:29.646688+00:00 app[worker.1]: Ignoring exception in command modapp: 2021-03-08T22:48:29.647867+00:00 app[worker.1]: Traceback (most recent call last): 2021-03-08T22:48:29.647910+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 85, in wrapped 2021-03-08T22:48:29.647910+00:00 app[worker.1]: ret = await coro(*args, **kwargs) 2021-03-08T22:48:29.647910+00:00 app[worker.1]: File "bot.py", line 277, in modapp 2021-03-08T22:48:29.647911+00:00 app[worker.1]: modAppEmbed.add_field(name="Q" + str(y) + " Answer: ", value=answers[y]) 2021-03-08T22:48:29.647953+00:00 app[worker.1]: TypeError: list indices must be integers or slices, not str 2021-03-08T22:48:29.647954+00:00 app[worker.1]: 2021-03-08T22:48:29.647955+00:00 app[worker.1]: The above exception was the direct cause of the following exception: 2021-03-08T22:48:29.647955+00:00 app[worker.1]: 2021-03-08T22:48:29.647957+00:00 app[worker.1]: Traceback (most recent call last): 2021-03-08T22:48:29.648001+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 935, in invoke 2021-03-08T22:48:29.648001+00:00 app[worker.1]: await ctx.command.invoke(ctx) 2021-03-08T22:48:29.648001+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 863, in invoke 2021-03-08T22:48:29.648001+00:00 app[worker.1]: await injected(*ctx.args, **ctx.kwargs) 2021-03-08T22:48:29.648004+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 94, in wrapped 2021-03-08T22:48:29.648004+00:00 app[worker.1]: raise CommandInvokeError(exc) from exc 2021-03-08T22:48:29.648040+00:00 app[worker.1]: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:1)

假设 answers 是一个 str 数组,问题出在 for 循环中:

for y in answers:
    modAppEmbed.add_field(name="Q" + str(y) + " Answer: ", value=str(answers[y]))

在这种情况下,y 迭代器将指向元素本身,因此您将无法将其用作答案数组的索引。而是使用 y 本身,将循环调整为:

for y in answers:
    modAppEmbed.add_field(name="Q" + str(y) + " Answer: ", value=str(y))