You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Discord中发起斜杠命令的用户ID?

Discord斜杠命令获取用户ID并维护喜好食物列表的修正方案

你当前代码的问题在于错误地从字符串类型的content(用户输入的食物名称)中尝试获取author.id属性——content只是普通文本,根本没有用户相关的属性。正确的做法是从斜杠命令的interaction对象中提取用户信息。

核心修正点

  • 获取用户ID:使用interaction.user.id,interaction.user是发起命令的用户对象,其id属性就是你需要作为字典键的用户ID。
  • 字典逻辑优化:处理用户首次添加食物时的字典初始化,以及重复添加的情况。

修改后的完整代码

client = aclient()
tree = app_commands.CommandTree(client)

# 初始化存储用户喜好的字典
userFavorites = {}

@tree.command(guild=discord.Object(id=guild_id), name='favorite_add', description='Add a food item to your favorite food list')
async def addFavorite(interaction: discord.Interaction, content: str = ""):
    # 校验输入是否为空
    if not content.strip():
        await interaction.response.send_message("请输入有效的食物名称!", ephemeral=True)
        return
    
    user_id = interaction.user.id
    # 检查用户是否已有喜好列表,没有则初始化
    if user_id not in userFavorites:
        userFavorites[user_id] = []
    
    # 避免重复添加相同食物(可选功能)
    if content not in userFavorites[user_id]:
        userFavorites[user_id].append(content)
        await interaction.response.send_message(f"{content} 已成功添加到你的喜好食物列表!", ephemeral=True)
    else:
        await interaction.response.send_message(f"{content} 已经在你的喜好列表中了,无需重复添加!", ephemeral=True)

关键说明

  1. 用户ID获取:interaction对象是斜杠命令的核心载体,包含了所有与当前命令交互相关的信息,其中interaction.user直接指向发起命令的用户,通过.id就能拿到唯一标识用户的ID。
  2. 字典维护:先判断用户ID是否存在于userFavorites字典中,不存在则创建空列表;存在则直接追加食物。可选的重复检查能避免列表中出现冗余数据。
  3. 输入校验:增加空输入判断,防止用户提交无效内容,提升交互体验。

内容的提问来源于stack exchange,提问作者Rexdestoyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:40:42