【问题标题】:is there a way to delete a message that has a specific word with a discord bot if the word is in the middle of a sentence?如果单词在句子的中间,有没有办法删除带有不和谐机器人的特定单词的消息?
【发布时间】:2021-11-04 17:00:46
【问题描述】:

我试过了:

https://i.stack.imgur.com/9JEWm.png

我也试过了

https://i.stack.imgur.com/2nhLz.png

但它给了我一个警告

【问题讨论】:

  • 欢迎来到 Stack Overflow!请在问题中包含相关代码和错误/警告作为格式化文本。有关如何提问的提示和信息,请参阅How to Ask 及其链接资源。

标签: python discord.py


【解决方案1】:

尝试创建一个 on_message 事件:

@client.event
async def on_message(message):

    # replace the 123 for whatever you want:
    if '123' in message.content: 
        await message.delete()
        await message.channel.send("You can't say that!")

    # you can do this how many times you want
    if '321' in message.content: 
        await message.delete()
        await message.channel.send("You can't say that!")

【讨论】:

    【解决方案2】:

    首先,添加您的代码而不是它的屏幕截图。

    但它给了我一个警告

    如果你说什么是“警告”总是有帮助的,但我猜它表示你没有为 startswith() 提供参数。

    您错误地使用了startswith():为了检查一个字符串是否以另一个字符串开头,您应该将另一个字符串作为参数传递给startswith(),而不是这样做startswith() == "123" 这毫无意义。您正在将 boolstring 进行比较...

    # Instead of
    >>> "something".startswith() === "so"  # ?
    False
    
    # Do
    >>> "something".startswith("so")
    True
    

    要检查某物是否在中间某处,请结合in 运算符并检查它是否不在与startswith() 的开头。您应该能够自己解决这个问题 - 我不会为您编写代码。

    【讨论】:

      【解决方案3】:

      尝试这样做

      b_words = ["Cats", "Dogs"]
      @bot.event
      async def on_message(message):
          if b_words in message:
              await message.channel.purge(limit=1)
          await ctx.send("Mind your language!")
          return
      

      这将检查消息中是否有坏词。如果有,那么它将删除该消息并发送警告。

      根据您在问题中提供的代码,它不会检查单词是否在句子中间。它只会检查句子是否以它开头。

      编辑

      b_words = ["Cats", "Dogs"]
      @bot.event
      async def on_message(message):
          for word in b_words:
              if word.lower() in message.content: #.lower() for making it case insensitive
                  await message.delete()
                  await message.channel.send("Mind your language!")
                  return
          await bot.process_commands(message)
      

      以上代码由我更新测试,不会有错误。

      【讨论】:

      • 没有。这永远行不通,你不能这样做list in string。您需要使用 any() 语句来做到这一点,您的回答实际上会引发类型错误。 if any(word in message for word in b_words) 是您在这里尝试的正确方法。
      猜你喜欢
      • 2021-09-26
      • 2020-12-18
      • 2020-01-15
      • 2021-07-27
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2015-01-20
      相关资源
      最近更新 更多