如何使discord.py机器人程序过滤某些单词/短语? [英] How do I make a discord.py bot filter certain words/phrases?
问题描述
现在,我有
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import os
bot = Bot(command_prefix="?")
with open("bad-words.txt") as file: # bad-words.txt contains one blacklisted phrase per line
bad_words = [bad_word.strip().lower() for bad_word in file.readlines()]
@bot.event
async def on_message(message):
message_content = message.content.strip().lower()
async for bad_word in bad_words:
if bad_word in message:
await bot.send_message(message.channel, "{}, your message has been censored.".format(message.author.mention))
await bot.delete_message(message)
bot.run(os.getenv("TOKEN"))
我有这个Python代码,但是它不起作用。我不知道为什么,因为我无法查看错误。目标是让Discord bot每次在 bad-words.txt
(包含一个列入黑名单的短语)的文件中包含列入黑名单的单词或短语时删除一条消息。每行。该机器人可以运行,但不执行任何操作。谢谢您的帮助。
I have this Python code, and it doesn't work. I do not know why, because I am unable to view the errors. The goal is to have the Discord bot delete a message whenever it contains a blacklisted word or phrase that is in bad-words.txt
, which is a file that contains one blacklisted phrase per line. The bot runs, but does not do anything. Thank you for your help.
推荐答案
由于您可能要等待搜索完成,因此可以更改 async for
到常规的 for
,如Patrick Haugh所述:
Since you probably want to wait for the search to finish, you could just change the async for
to a regular for
as mentioned by Patrick Haugh:
for bad_word in bad_words:
if bad_word in message:
await bot.send_message(message.channel, "{}, your message has been censored.".format(message.author.mention))
await bot.delete_message(message)
在Python 3中, any()
方法可用于进一步简化此操作:
However, in Python 3, the any()
method can be used to simplify this further:
if any(bad_word in message for bad_word in bad_words):
await bot.send_message(message.channel, "{}, your message has been censored.".format(message.author.mention))
await bot.delete_message(message)
这篇关于如何使discord.py机器人程序过滤某些单词/短语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!