【问题标题】:I keep on getting this error, can't find what I'm doing wrong我不断收到此错误,找不到我做错了什么
【发布时间】:2021-11-28 20:25:56
【问题描述】:

这是该错误的代码行:

if msg.startswith("!del"):
   encouragements = []
  if "encouragements" in db.keys():
    index = int(msg.split("!del",1)[1])
    delete_encouragement(index)
    encouragements = db["encouragements"]
  await message.channel.send(encouragements)

这是我不断收到的错误:

Ignoring exception in on_message
    Traceback (most recent call last):
      File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
        await coro(*args, **kwargs)
      File "main.py", line 69, in on_message
        index = int(msg.split("!del", 1)[1])
    IndexError: list index out of range

每次我尝试运行 !del 命令时都会收到错误消息。

【问题讨论】:

  • 您能否修复代码示例的缩进以完全匹配您正在使用的代码?

标签: python python-3.x discord.py bots


【解决方案1】:

这是一个基本的 Python 错误。请查看split() 和序列索引上的文档。

如果您将discord.Client 对象用于您的机器人,您可能需要查看commands.Bot 对象。

【讨论】:

    【解决方案2】:

    当 msg 被拆分但结果仅包含一个元素时,可能会发生异常“IndexError: list index out of range”。代码试图获取第二个元素,但只存在一个元素。请参阅以下示例:

    msg="!del"
    print('one',msg.split("!del",1))
    
    msg="something"
    print('two',msg.split("!del",1))
    
    msg="something"
    print('three', msg.split("!del",1)[1])
    

    输出:

    one ['', '']
    two ['something']
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-13-4193103020d6> in <module>
          6 
          7 msg="something"
    ----> 8 print('three',msg.split("!del",1)[1])
          9 
         10 
    
    IndexError: list index out of range
    

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 2011-04-30
      • 2018-12-03
      • 2021-11-06
      • 2017-09-29
      相关资源
      最近更新 更多