【问题标题】:Discord bot repeating the command but not an event in discord.pyDiscord bot 重复命令但不是 discord.py 中的事件
【发布时间】:2021-08-22 11:46:55
【问题描述】:

我想问一些问题。我遇到了一些问题。我想为我的机器人添加一些新功能,例如脏话,以便使服务器更干净。我完成了我的代码并尝试给出 的命令! dc 问候(!dc 是我的 command_prefix 顺便说一句)。我的机器人发送了 7 次 “大家好” 消息。这 7 次与 中脏话的数量相同“Badwords.txt”。通过查看这些,重复问题与此文件处理代码(或与 idk 无关)有关。有趣的是,当我在服务器的聊天框中写脏话时,机器人只发送一个 "请永远不要使用这个词” 消息。那么我怎样才能防止机器人不重复多次呢?谢谢

import discord
from discord.ext import commands


intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)


client = commands.Bot(command_prefix="!dc ", intents=intents)

#Below command gets repeated 7 times everytime.That number is same as the number of swear words in "Badwords.txt"
@client.command(aliases=["sayHi"]) 
async def greetings(ctx):
    await ctx.send('Hi everyone')

#My purpose in the below codes is countering profanity

with open("Badwords.txt", "r", encoding="utf-8") as f:
    word = f.read()
    badwords = word.split(",")  

#In the below event,bot sends message only 1 time for 1 message 
@client.event
async def on_message(message):
    msg = message.content
    for x in badwords:
        if x in msg:
            await message.delete()
            await message.channel.send("Please do not use this word ever")
        else:
            await client.process_commands(message) 
client.run(Token)    
        

【问题讨论】:

  • 当到达 else 部分时,您正在处理每个循环上的命令。你应该在外部循环。
  • @ŁukaszKwieciński 谢谢它的工作:)

标签: discord.py


【解决方案1】:

我会将await client.process_commands(message)else 语句中删除。我还在 on message 事件中移动了with open,因此发送的所有消息都会打开文件以检查消息是否包含坏词。

import discord
from discord.ext import commands


intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)


client = commands.Bot(command_prefix="!dc ", intents=intents)

@client.command(aliases=["sayHi"]) 
async def greetings(ctx):
    await ctx.send('Hi everyone')

@client.event
async def on_message(message):
    msg = message.content
    with open("Badwords.txt", "r", encoding="utf-8") as f:
        word = f.read()
        badwords = word.split(",") 
    for x in badwords:
        if x in msg:
            await message.delete()
            await message.channel.send("Please do not use this word ever")
        else:
            return
    await client.process_commands(message)
client.run(Token)

await client.process_commands(message) 已从 else 语句中删除,因为使用您当前的代码,机器人只会在消息不包含坏词时处理命令。但是我们需要它在每次发送消息时处理命令。

【讨论】:

  • 感谢您的回答。感谢您的帮助。
  • @hARASİVa 我很高兴它对你有用!如果对您有帮助,请将此答案标记为正确。
猜你喜欢
  • 2020-08-16
  • 2021-04-16
  • 2020-09-24
  • 1970-01-01
  • 2021-01-02
  • 2020-12-20
  • 2020-01-09
  • 2021-09-23
  • 2021-10-23
相关资源
最近更新 更多