我正在练习python编程。试图为“坏词”创建过滤器我遇到了一个问题。我的代码中有@bot.event,它将所有消息从服务器复制到另一个通道。所以,它不起作用。虽然当我分别运行这两个@bot.event 时,它们工作正常。但它们一起冲突。它可以与什么连接?
import discord
from discord.ext import commands
TOKEN = 'censored'
badWord = ['bad1', 'bad2','Bad1','Bad2']
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f"Bot App1 is ready") #a message about the bot's readiness, output to the console
@bot.event
async def on_message(message):
if message.content in badWord:
pass
print(f"{message.author}: Bad word is detected")
else:
if message.author == bot.user:
return
print(message.author,message.content)
channel = bot. get_channel(861546679676567594)
await channel.send('{}: {}'.format(message.author, message.content)) #the bot reads all messages written on the server and copies them to a special chat
@bot.event
async def on_message(message):
msg_content = message.content.lower()
if any(word in msg_content for word in badWord):
await message.delete()
await message.channel.send(f"{message.author.mention} Bad word is deleted.")
print('Bad word is deleted',message.author)
bot.run(TOKEN)
也许问题在于@bot.event 是一个装饰器,并且您的两个装饰器都针对同一个对象。第一次出现将起作用,例如 if elif 构造。另外,函数调用相同,这不是很好。我建议您将它们组合起来或在第一个函数的末尾创建对第二个函数的引用
当你第二次声明一个函数时
on_message,第一个“消失”,它被一个新的替换。此外,discord.py 中有一个内部限制,不允许创建两个相同类型的事件侦听器。改用:@bot.listen()_@bot.event