如何用Python开发支持给Discord用户添加公开/管理员可见备注的Bot
Discord 备注Bot Python开发指引
你描述的备注功能完全可以通过Python实现,主流使用discord.py库即可完成全功能开发,具体指引如下:
1. 前期准备
- 安装核心依赖:执行命令
pip install discord.py - 到Discord开发者平台创建Bot应用,获取Bot Token,同时开启「消息内容读取」「服务器成员读取」「发送消息」权限,将Bot邀请到目标服务器。
2. 核心功能实现逻辑
- 存储方案:小型场景可直接用JSON文件存储备注映射,结构参考
{"用户ID": {"note": "备注内容", "create_time": "添加时间"}},多服务器或大容量场景可改用SQLite轻量数据库。 - 权限控制:预先配置备注操作权限范围,如果设置为仅管理员可用,收到命令时先校验发起者是否拥有服务器管理员权限,如果开放给所有人可直接跳过身份校验。
- 命令解析:监听服务器内的所有消息,匹配前缀为
!note的指令,拆分消息内容:提取第一个@的用户作为目标对象,剩余文本作为备注内容,格式校验通过后写入存储。 - 查看功能:可新增
!shownote @目标用户指令,收到请求后先校验发起者权限,有权限则从存储中取出对应备注内容返回。
3. 核心代码片段示例
import discord from discord.ext import commands import json import datetime # 配置项 ALLOW_ALL_USER = False # 设置为True则所有人可操作备注,False仅管理员可操作 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) # 加载已有备注 try: with open('notes.json', 'r', encoding='utf-8') as f: notes = json.load(f) except FileNotFoundError: notes = {} @bot.command(name='note') async def add_note(ctx, user: discord.Member, *, note_content): # 权限校验 if not ALLOW_ALL_USER and not ctx.author.guild_permissions.administrator: await ctx.send("你没有权限使用该命令") return # 存储备注 notes[str(user.id)] = { "note": note_content, "create_time": str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) } with open('notes.json', 'w', encoding='utf-8') as f: json.dump(notes, f, ensure_ascii=False, indent=2) await ctx.send(f"已成功为{user.mention}添加备注") @bot.command(name='shownote') async def show_note(ctx, user: discord.Member): # 权限校验 if not ALLOW_ALL_USER and not ctx.author.guild_permissions.administrator: await ctx.send("你没有权限使用该命令") return user_note = notes.get(str(user.id), {}).get("note", "该用户暂无备注") await ctx.send(f"{user.mention}的备注:{user_note}") bot.run("你的Bot Token")
使用时将代码中的你的Bot Token替换为你从Discord开发者平台获取的实际Token即可运行,输入!note @用户 备注内容即可完成添加操作。
内容的提问来源于stack exchange,提问作者Aabis Zafar
相关产品推荐
相关产品推荐

