如何在discord.py中为单个用户ID实现独立无干扰的秒表功能
实现Discord.py多用户独立秒表功能
要实现多用户独立启停的秒表功能,核心是用全局字典存储每个用户的秒表状态——用户ID作为唯一键,避免不同用户的操作互相干扰。以下是完整的实现代码:
import discord from discord.ext import commands from datetime import datetime # 初始化Bot(根据你的实际配置调整前缀和intents) intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='/', intents=intents) # 存储活跃秒表:键=用户ID,值={start_time: 启动时间, flight_plan: 飞行计划} active_logs = {} @bot.command(name='logstart') async def logstart(ctx, *flight_plan_parts): await ctx.message.delete() # 拼接所有参数为完整飞行计划字符串 flight_plan = ' '.join(flight_plan_parts) # 记录当前用户的启动时间和飞行计划 active_logs[ctx.author.id] = { "start_time": datetime.now(), "flight_plan": flight_plan } await ctx.send('Log Started') @bot.command(name='logstop') async def logstop(ctx): await ctx.message.delete() user_id = ctx.author.id # 检查用户是否有正在运行的秒表 if user_id not in active_logs: await ctx.send('你还没有启动秒表,请先执行 /logstart 命令!') return # 获取秒表数据并计算时长 log_data = active_logs.pop(user_id) duration = datetime.now() - log_data["start_time"] # 格式化时长(去掉微秒部分,输出更简洁) formatted_duration = str(duration).split('.')[0] # 构建飞行日志消息 log_message = f"""**FLIGHT LOG** Duration: {formatted_duration} Flight Plan: {log_data["flight_plan"]}""" await ctx.send(log_message) # 运行Bot(替换成你的Token) bot.run('YOUR_BOT_TOKEN_HERE')
关键细节说明:
- 多用户隔离:用
ctx.author.id作为字典的键,每个用户的秒表数据独立存储,互不干扰。 - 参数处理:
*flight_plan_parts可以捕获用户输入的所有参数(比如EGCC(DEP) EGLL(ARR)),再拼接成完整的飞行计划字符串。 - 状态校验:执行
logstop时先检查用户是否有活跃秒表,避免无意义报错。 - 时长格式化:通过
str(duration).split('.')[0]去掉时间差中的微秒部分,让输出更符合阅读习惯。
内容的提问来源于stack exchange,提问作者Petros Muston
相关产品推荐
相关产品推荐

