discord.py使用message.content中的列表?

时间:2020-10-20 17:32:03

标签: python discord discord.py

@bot.event
async def on_message(message):
    wordfilter = ['badword', 'anotherone', 'and the last one']
    if wordfilter in message.content:
        await message.delete()

错误:

Traceback (most recent call last):
  File "C:path/client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:path/combot.py", line 34, in on_message
    if wordfilter in message.content:
TypeError: 'in <string>' requires string as left operand, not list

我想要一个带有大量单词的单词过滤器,所以id喜欢有一个列表,我可以在其中添加所有单词(甚至使用Discord的命令)。 但是我真的不知道如何使它工作。

1 个答案:

答案 0 :(得分:0)

您不能检查列表是否在字符串中,您输入的是错误的。您正在尝试做的是if message.content in wordfilter,但这也行不通。您需要获取消息中的每个单词,然后检查其中是否包含wordfilter,还需要从事件中创建wordfilter列表,这样就不会为该事件创建新列表每次都可以使您的代码更加优化。因此,您只需在一行中完成此操作即可:

wordfilter = ['badword', 'anotherone', 'and the last one']
@bot.event
async def on_message(message):
    [await message.delete() for word in message.content.split(' ') if word in wordfilter]

因此,它将把您的邮件内容从空格中分离出来,并检查单词过滤器中是否有一个单词。如果是,它将删除该消息。