如何让Discord机器人响应!restore时输出不同的datetime时间
修复Discord机器人响应时输出相同时间的问题
问题原因
你的代码中now = datetime.datetime.now()是在程序启动阶段执行的,只会获取一次当前时间,后续所有打印操作都复用这个固定的时间值,导致每次输出的时间都相同。
修改方案
将获取当前时间的操作移到处理!restore指令的逻辑内部,确保每次触发指令时都重新获取最新的时间。
修改后的完整代码
import discum import random import time from termcolor import colored import datetime import token bot = discum.Client(token='token',log={"console":False, "file":False}) @bot.gateway.command def helloworld(resp): if resp.event.message: m = resp.parsed.auto() channelID = m['channel_id'] username = m['author']['username'] AuthorID = m['author']['id'] if m['content']== '!restore': time_to_sleep = random.uniform(2.5, 3.1) time.sleep(time_to_sleep) bot.sendMessage(channelID, "$restoreuser " + AuthorID + " 1") # 每次触发指令时重新获取当前时间 now = datetime.datetime.now() print(colored(username , 'yellow') , colored("Utilizou Cleanself", 'cyan'), now.strftime("%d-%m-%y %H:%M:%S")) time_to_sleep2 = random.uniform(3.5, 4.2) time.sleep(time_to_sleep2) bot.sendMessage(channelID, "**if you haven't been restored, type **__!restore__** again**") bot.gateway.run()
关键修改点
- 删除全局作用域中的
now = datetime.datetime.now() - 在
!restore指令的处理逻辑内部、打印语句之前添加now = datetime.datetime.now(),确保每次触发指令都获取最新时间
内容的提问来源于stack exchange,提问作者Seris
相关产品推荐
相关产品推荐

