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

如何在discord.py中实现Discord论坛帖子标签检测功能?

实现Discord论坛帖子标签检测与待发布列表管理

核心步骤与代码实现(以discord.py v2.x为例)

  1. 监听论坛帖子创建事件
    Discord论坛的帖子本质是带标签的线程(Thread),需监听on_thread_create事件,先判断线程是否来自论坛频道:
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.guilds = True
intents.messages = True
intents.message_content = True

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

# 用字典存待发布列表:键为标签名,值为对应帖子链接列表
pending_posts = {}

@bot.event
async def on_thread_create(thread):
    # 确认是论坛频道的帖子
    if isinstance(thread.parent, discord.ForumChannel):
        # 提取帖子的所有标签名称
        applied_tags = [tag.name for tag in thread.applied_tags]
        post_url = thread.jump_url  # 获取帖子的跳转链接
        
        # 按标签分类存入待发布列表
        for tag in applied_tags:
            if tag not in pending_posts:
                pending_posts[tag] = []
            pending_posts[tag].append(post_url)
        print(f"已捕获新帖子:{post_url},标签:{applied_tags}")
  1. 实现斜杠命令发布待发布列表
    添加斜杠命令,支持按标签查看或发布对应帖子:
@bot.tree.command(name="发布待发帖子", description="按标签发布待发布的帖子链接")
async def publish_posts(interaction: discord.Interaction, 标签: str):
    if 标签 not in pending_posts or len(pending_posts[标签]) == 0:
        await interaction.response.send_message(f"标签「{标签}」下暂无待发布帖子", ephemeral=True)
        return
    
    # 拼接帖子链接列表
    post_list = "\n".join(pending_posts[标签])
    await interaction.response.send_message(f"发布标签「{标签}」下的待发帖子:\n{post_list}")
    
    # 发布后清空该标签下的待发布列表(可根据需求调整是否保留历史)
    pending_posts[标签] = []

关键细节说明

  • 权限配置:机器人需开启Server Members Intent和Message Content Intent,并在Discord开发者后台的Bot页面勾选对应权限。
  • 标签获取:thread.applied_tags返回ForumTag对象列表,可按需获取tag.id(标签ID)或tag.name(标签名称)。
  • 持久化存储:示例用内存字典存储,重启机器人后数据会丢失,实际部署建议用SQLite、MySQL等数据库做持久化。
  • 其他库适配:若使用discord.js,逻辑类似——监听threadCreate事件,通过thread.appliedTags获取标签,用thread.url获取帖子链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:33:13