【问题标题】:discord.py using Lists in message.content?discord.py 在 message.content 中使用列表?
【发布时间】:2020-10-20 17:32:03
【问题描述】:
@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

我想要一个单词过滤器,里面有很多单词,所以我希望有一个列表,我可以在其中添加我所有的单词(稍后甚至使用来自 Discord 的命令)。 但我真的不知道如何让它工作。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    你不能检查一个列表是否在一个字符串中,你做错了。你想要做的是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]
    

    因此,它会将您的消息内容与空格分开,并检查其中一个单词是否在 wordfilter 中。如果是,它将删除该消息。

    【讨论】:

    • 非常感谢。只是想让您知道我没有足够的声誉,请投票支持您的答案。这对我很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2021-01-13
    • 2021-01-12
    • 2022-12-10
    相关资源
    最近更新 更多