不和谐:message.content.split

时间:2018-11-30 10:47:56

标签: python-3.x discord.py

此代码有问题。写完这段代码后,我收到此错误:

  File "bot.py", line 90, in on_message:
    if message.content.split("{}".format(blacklist))[1].strip():
IndexError: list index out of range

代码:   

blacklist = ['test1','test2']
if message.content.split("{}".format(blacklist))[1].strip():
    embed=discord.Embed(title=":no_entry_sign: Blacklisted", description="If you're an idiot at least stop flagging")
    embed.set_footer(text="If you'd like to appeal to be whitelisted please contact, Adryan#1677")
    await client.send_message(message.channel, embed=embed)
    await client.delete_message(message)

1 个答案:

答案 0 :(得分:0)

message.content.split("{}".format(blacklist))不能保证返回包含多个项目的列表。

"abc".split("d") # returns ['abc']
"abcd".split("d") # returns ['abc', '']
if "abc".split("d")[1]:
    print("foo") # will never be reached since Python IndexErrors on evaluating the if condition

由于您不确定列表中是否包含多个元素,因此立即转到索引1处,每当.split给您一个单项长列表时,您就会得到一个{{1} }。

如果您想测试IndexError是否实际返回的列表长于一项,则split最好为您服务。