【发布时间】:2021-11-04 17:00:46
【问题描述】:
【问题讨论】:
-
欢迎来到 Stack Overflow!请在问题中包含相关代码和错误/警告作为格式化文本。有关如何提问的提示和信息,请参阅How to Ask 及其链接资源。
标签: python discord.py
【问题讨论】:
标签: python discord.py
尝试创建一个 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!")
【讨论】:
首先,添加您的代码而不是它的屏幕截图。
但它给了我一个警告
如果你说什么是“警告”总是有帮助的,但我猜它表示你没有为 startswith() 提供参数。
您错误地使用了startswith():为了检查一个字符串是否以另一个字符串开头,您应该将另一个字符串作为参数传递给startswith(),而不是这样做startswith() == "123" 这毫无意义。您正在将 bool 与 string 进行比较...
# Instead of
>>> "something".startswith() === "so" # ?
False
# Do
>>> "something".startswith("so")
True
要检查某物是否在中间某处,请结合in 运算符并检查它是否不在与startswith() 的开头。您应该能够自己解决这个问题 - 我不会为您编写代码。
【讨论】:
尝试这样做
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) 是您在这里尝试的正确方法。