首页 文章

如何限制discord bot在Python中打印的次数?

提问于
浏览
-1

我如何做到这一点,以便Python中的discord bot会暂停任何活动,如果它被多次调用,以阻止垃圾邮件 .

机器人在聊天中查找关键字,如果找到任何关键字,则打印出一条消息 . 如果这些关键字中的任何一个被垃圾邮件发送,那么机器人也会发送垃圾邮件 . 我想这样做,如果它在某个时间范围内响应了y次,它基本上会停止听这些单词的时间 .

你可以查看完整的代码here,这是相关的(忽略缩进) -

# list of words which triggers it
bannedWords = ["trade", "exchange", "tradeogre", "sell turtlecoin"]

# list of responses
wordlist = ["Heyo, please move to the server linked in #market-talk, we don't like it here.", 
        "If you could move to the server linked in #market-talk, that'd be great! We don't enjoy that here."]

@client.event 
async def on_ready():
    print("With me around, ain't gonna be no market talk!") 

@client.event
async def on_message(message):

# convert it to lower
low = message.content.lower()

#send only in general
if message.channel.id != "440496273762549762":
    return

# check if the author is the **logged in** bot, in which case doesnt do anything
if(message.author.id == client.user.id):
    return

# check if message incl. banned words. if so, spit a response
if any(word.lower() in message.content.lower() for word in bannedWords):
    await client.send_message(message.channel, message.author.mention + " " + random.choice(wordlist))

使用当前代码,任何人都可以垃圾邮件包含在禁止词中的单词,并且机器人会垃圾邮件回复wordlist中的回复,这是不可取的> . >

非常感谢任何帮助,非常感谢! :d

1 回答

  • 0

    这样的事情应该有效 . 每次收到消息时,检查过去10秒内是否有超过5条消息,如果是,请不要打印 . 否则,追加当前消息时间,然后打印 .

    我在这里使用了一些全局变量,这通常被认为是不好的做法 . 在这个玩具示例中不需要它,但是当您使用无法修改参数的异步函数时,我不确定如何避免使用它们 .

    我相信拥有比我更多蟒蛇技能的人可能会提出一个比这更好的方法 .

    import time
    
    lastMessageTimes = []
    maxResponses = 5
    timeFrameWindow = 10
    
    def shouldPrint():
        currentTime = time.time()
    
        global lastMessageTimes
        # remove any messages that haven't occured in the last timeFrameWindow seconds
        lastMessageTimes = [x for x in lastMessageTimes if not currentTime - x > timeFrameWindow]
    
        # check if we've had over maxResponses in the last timeFrameWindow
        if len(lastMessageTimes) >= maxResponses:
            return False
        return True
    
    def on_message(message):
        if shouldPrint():
            # insert the current message timestamp
            lastMessageTimes.append(time.time())
            print("Hello world!")
    
    while(True):
        # empty message for demonstration purposes
        on_message("")
    

    如果你试试这个,你应该看到它以每10秒5块的形式打印“Hello World”,我认为这是你想要的 .

相关问题