如何在Hikari Lightbulb中获取SlashSubCommand调用者以实现积分系统?
基于Hikari+Lightbulb实现命令积分系统方案
核心问题修正
你之前的错误源于对Lightbulb命令上下文的属性不熟悉:
ctx.author仅适用于前缀命令的上下文(PrefixContext),Slash命令的上下文(SlashContext)对应的用户属性是ctx.user或ctx.member- Slash命令函数不支持额外的
event参数,事件监听函数才需要该参数,命令逻辑里直接通过ctx就能获取执行者信息
实现步骤
1. 初始化积分存储
在扩展文件中定义全局字典用于存储积分(如果需要持久化可以换成数据库,这里按你的需求用字典):
points = {}
2. 正确获取命令执行者信息
在Slash命令函数中,通过ctx.user获取用户对象:
ctx.user.username:纯用户名(不带#和 discriminator)ctx.user.id:用户唯一ID(比用户名更可靠,避免重名)
3. 积分更新逻辑
使用字典的get方法简化积分更新代码,无需判断键是否存在:
# 以用户名为键 points[username] = points.get(username, 0) + 1 # 或者以用户ID为键(推荐) user_id = ctx.user.id points[user_id] = points.get(user_id, 0) + 1
4. 完整命令示例
import lightbulb import hikari # 积分存储字典 points = {} # 创建插件扩展 plugin = lightbulb.Plugin("GamePoints") @plugin.command @lightbulb.command("play", "执行游戏命令并获得积分") @lightbulb.implements(lightbulb.SlashCommand) async def play_game(ctx: lightbulb.SlashContext) -> None: # 获取执行者用户名 username = ctx.user.username # 更新积分 points[username] = points.get(username, 0) + 1 # 回复用户积分变化 await ctx.respond(f"积分+1!当前积分:{points[username]}") # 加载插件到机器人 def load(bot: lightbulb.BotApp) -> None: bot.add_plugin(plugin)
额外说明
- 如果需要获取用户的服务器昵称,用
ctx.member.nickname(仅在服务器内有效) - 若要持久化积分,建议将字典数据写入本地文件(如JSON)或数据库,避免机器人重启后数据丢失
内容的提问来源于stack exchange,提问作者CultistsInc
相关产品推荐
相关产品推荐

