如何用discord.py 1.7.0实现个人Discord账号定时隐身?
Discord自机器人无法切换隐身状态的修复方案
你用discord.py 1.7.0搭建自机器人,想要定时切换在线/隐身状态,但代码无报错却不生效,问题出在这几个细节上:
1. 函数未实际调用
on_ready里的判断if goInvis:只是检查函数对象是否存在,永远返回True,根本没执行时间判断逻辑。必须改成调用函数:
if goInvis():
2. 变量名冲突导致判断逻辑失效
goInvis函数里已经获取了当前小时数hour,但判断时误用了time——这个time是你导入的datetime.time模块,不是当前小时数值。把判断条件里的time替换成hour:
if hour < time_stamps[0] or hour > time_stamps[1]:
3. 依赖未知方法引发隐性问题
getTime里的string.before来自essentials模块,这个第三方方法的可靠性无法保证,换成Python原生字符串分割更稳妥:
t_str = str(timestamp).split('.')[0] t = datetime.strptime(t_str, '%H:%M:%S')
4. 同步sleep阻塞异步事件循环
用t.sleep(2)会卡死discord.py的异步事件循环,导致状态变更请求无法被处理。换成异步版本的sleep:
await asyncio.sleep(2)
修复后的完整代码
from discord.ext import commands from datetime import datetime import discord import asyncio intents = discord.Intents().all() intents.typing = False intents.presences = False # 本地变量 token = "my-token" prefix = "." bot = commands.Bot(command_prefix=prefix, intents=intents, help_command=None, self_bot=True) # 定义函数 def getTime(): timestamp = datetime.now().time() # 用原生方法分割时间字符串,去掉毫秒部分 t_str = str(timestamp).split('.')[0] t = datetime.strptime(t_str, '%H:%M:%S') return t.hour def goInvis(): hour = getTime() time_stamps = [12,22] # 用hour变量判断,不是time模块 if hour < time_stamps[0] or hour > time_stamps[1]: return True else: return False @bot.event async def on_ready(): print("Ready") while True: # 调用goInvis函数 if goInvis(): print("切换为隐身状态") await bot.change_presence(status=discord.Status.offline) else: print("切换为在线状态") await bot.change_presence(status=discord.Status.online) # 用异步sleep await asyncio.sleep(2) bot.run(token, bot=False)
内容的提问来源于stack exchange,提问作者Zgn
相关产品推荐
相关产品推荐

