在Python中,如何在命令后设置一个时间延迟?

2024-06-17 15:46:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何使用时间。睡觉()命令在脚本中创建延迟,但我正在开发一个chatango bot,我想通过在每个命令后添加3秒延迟来防止它淹没聊天。但是,我不确定如何使其准确实现,我当前的尝试只是使脚本本身延迟3秒。我举个例子:

    s = message.body
    if 'test' in s:
        print(room.message("This is a sample."))
        import time
        time.sleep(3)

我不太清楚从这里能做什么,所以任何帮助都将不胜感激,谢谢。在

注意:这与“如何在Python中创建时间延迟”不同在这个问题上没有答案对我有任何帮助,这是另一回事。在

再次注意:人们总是暗示这是同一个问题,但事实并非如此。这是另一个问题。为什么你们这么难理解?在


Tags: intest命令脚本messageiftimebot
3条回答

试试这个:

import ch
import time

z = dict()

class bot(ch.RoomManager):
    def onMessage(self, room, user, message):
        s = message.body
        if 'test' in s:
            if room.name in z:
                if time.time() < z[room.name]:
                    return
                else:
                    z[room.name] = time.time()+3
                    print(room.message("This is a sample."))
            else:
                z[room.name] = time.time()+3
                print(room.message("This is a sample."))

if __name__ == "__main__":
    bot.easy_start()

这是我在我的机器人上对游戏命令使用的一种方法,可以对命令进行延时。在

import time
time_dict = dict()
class Bot(ch.RoomManager)
      def onMessage(self, room, user, message):  
          s = message.body
          if 'test' in s:   
            try:
             if room in time_dict:
                timeset = time_dict[room]
             else:
                timeset = time.time()-3
                time_dict[room] = timeset
                if time.time() - float(timeset) < 150:
                   return
                else:
                    room.message("This is a sample.")

onMessage()内保存最后一次回复到实例变量的时间。每次你在房间里打印信息时都要更新。只有在以下情况下才回复:

import time
class Bot(ch.RoomManager):
    def onMessage(self, room, user, message):
        NOW = time.time()
        s = message.body
        if 'test' in s AND NOW - 3 > self._last_sent:
            print(room.message("This is a sample."))
            self._last_sent = NOW

相关问题 更多 >