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

如何为Discord机器人实现描述存储与user info command展示功能

实现用户描述设置与信息调取的Discord机器人命令

刚入门的话,用JSON文件存储数据是最直接的方案,不需要复杂的数据库,下面用discord.py框架给你写完整实现步骤:

1. 准备工作

先安装依赖库:

pip install discord.py

同时在Discord开发者门户里,给你的机器人开启服务器成员意图和消息内容意图,否则机器人无法读取消息和成员信息。

2. 核心代码实现

import discord
from discord.ext import commands
import json
import os

# 初始化机器人,前缀用!,按需调整
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# 加载用户描述数据
def load_data():
    # 若文件不存在,创建空的JSON文件
    if not os.path.exists('user_descriptions.json'):
        with open('user_descriptions.json', 'w', encoding='utf-8') as f:
            json.dump({}, f, ensure_ascii=False)
    # 读取文件内容
    with open('user_descriptions.json', 'r', encoding='utf-8') as f:
        return json.load(f)

# 保存用户描述数据
def save_data(data):
    with open('user_descriptions.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4, ensure_ascii=False)

# 设置个人描述的命令
@bot.command(name='setdesc')
async def set_description(ctx, *, description: str):
    # 用用户ID作为唯一标识,转成字符串避免JSON类型问题
    user_id = str(ctx.author.id)
    data = load_data()
    # 更新当前用户的描述
    data[user_id] = description
    save_data(data)
    await ctx.send(f'✅ 你的个人描述已更新:\n{description}')

# 查看用户信息的命令
@bot.command(name='userinfo')
async def user_info(ctx, member: discord.Member = None):
    # 没指定成员的话,默认查看自己的信息
    member = member or ctx.author
    user_id = str(member.id)
    data = load_data()
    # 获取描述,没有设置就显示默认文本
    desc = data.get(user_id, '😶 该用户还没设置个人描述')

    # 用Embed美化消息(可选,比纯文本更美观)
    embed = discord.Embed(title=f'{member.display_name} 的个人信息', color=discord.Color.green())
    embed.add_field(name='用户ID', value=member.id, inline=False)
    embed.add_field(name='个人描述', value=desc, inline=False)
    # 显示用户头像
    avatar_url = member.avatar.url if member.avatar else member.default_avatar.url
    embed.set_thumbnail(url=avatar_url)

    await ctx.send(embed=embed)

# 机器人启动提示
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')

# 替换成你的机器人令牌,别泄露!
bot.run('你的机器人令牌')

3. 关键细节说明

  • 数据存储:user_descriptions.json会自动生成在脚本同目录,内容是类似{"123456789": "我是喜欢Discord的开发者"}的键值对,键是用户ID字符串,值是描述文本。
  • 服务器专属描述:如果想让用户在不同服务器设置不同描述,把存储的键改成f"{member.guild.id}-{member.id}",这样每个服务器的描述互相独立。
  • 长度限制:可以给setdesc命令加长度判断,比如if len(description) > 300: await ctx.send('描述不能超过300字哦'); return,避免存储过长内容。
  • 异常处理:如果需要更稳定,可以给文件读写加try-except块,防止意外报错导致机器人崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:24:18