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

discord.py开发时为什么无法使用message.user.tag获取用户4位标签?

问题修复方案

报错原因

  • 你错误导入了discord.message模块,代码中调用的message.user.tag实际是访问这个模块的属性,模块本身不存在user属性,直接触发AttributeError
  • 你混淆了模块和上下文对象的用法,在commands框架下不需要手动导入message获取触发用户信息

正确实现方式

在discord.py的命令结构中,直接通过命令上下文ctx的author属性即可获取触发命令的用户对象,用户的4位识别标签对应discriminator属性,完整的用户名#xxxx格式对应tag属性。

修正后的参考代码

import discord
from discord.ext import commands

# 2.0以上版本必须显式配置intents,同时需要在Discord开发者后台打开对应权限
client = commands.Bot(command_prefix = '!', intents=discord.Intents.all())

##########HOURS##########
chung_victor = [21, 10]
##########HOURS##########

@client.command(name='hours')
async def hours(ctx):
    # 提取用户4位识别码并转为整数
    usertag = int(ctx.author.discriminator)
    # 匹配用户
    if usertag == 5308:
        h = chung_victor[0]
        m = chung_victor[1]
        await ctx.send(f'> You currently have {h} hours and {m} minutes!')

client.run('你的机器人令牌')

补充说明

  • 如果需要获取完整的用户名#xxxx格式的用户标识,替换为ctx.author.tag即可
  • 若运行时提示权限相关错误,检查Discord开发者后台Bot面板的「Privileged Gateway Intents」选项,打开对应权限后再启动机器人

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:24:11