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

如何用discord.py v2.0实现修改论坛帖子标签的机器人命令?

Discord.py v2.0 修改论坛帖子标签实现方案

discord.py v2.0完全支持修改论坛帖子标签的功能,你可以通过ForumThread.edit()方法来更新帖子的应用标签,该方法接受applied_tags参数,传入目标标签对象的列表即可实现替换或修改标签。

实现示例代码

以下是实现!complete命令的完整代码,满足管理员在目标帖子内发送命令后,将标签从"issue"改为"completed"的需求:

import discord
from discord.ext import commands

# 配置机器人意图,需开启消息内容权限
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')

@bot.command()
@commands.has_permissions(manage_threads=True)  # 限制仅有权限的用户使用
async def complete(ctx):
    # 校验当前频道是否为论坛帖子
    if not isinstance(ctx.channel, discord.Thread) or ctx.channel.parent.type != discord.ChannelType.forum:
        await ctx.send('此命令仅能在论坛帖子内使用!')
        return
    
    forum_channel = ctx.channel.parent
    issue_tag = None
    completed_tag = None

    # 遍历论坛标签,匹配目标标签
    for tag in forum_channel.tags:
        if tag.name == "issue":
            issue_tag = tag
        elif tag.name == "completed":
            completed_tag = tag
    
    if not issue_tag or not completed_tag:
        await ctx.send('未找到指定标签,请检查论坛标签设置!')
        return
    
    # 替换标签:移除issue,添加completed
    updated_tags = [tag for tag in ctx.channel.applied_tags if tag != issue_tag]
    updated_tags.append(completed_tag)
    
    await ctx.channel.edit(applied_tags=updated_tags)
    await ctx.send('帖子标签已更新为「completed」!')

# 替换为你的机器人令牌
bot.run('YOUR_BOT_TOKEN')

注意事项

  • 需确保机器人拥有ManageThreads权限,且在Discord开发者门户开启Message Content Intent。
  • 代码中的标签名称需与论坛实际创建的标签完全一致,也可通过标签ID(tag.id == 目标ID)匹配,避免名称变更导致失效。
  • applied_tags参数仅接受ForumTag对象列表,不能直接传入字符串标签名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:10:25