用于根据用户和类别ID向Composer添加自定义消息的组件

今天我遇到了这个问题:

https://meta.discourse.org/t/required-tags-should-only-be-required-based-on-type-of-user/392238

但在此期间,在团队解决这个问题之前(希望如此),我决定向 Claude 寻求帮助,构建一个组件,允许我在“撰写器”(Composer)中设置自定义消息,以提醒我添加标签。我可以按 ID 添加一个或多个用户,也可以按 ID 将其限制在特定分类(category)中。

如果 ID(用户和分类)不在列表中,我看到这个:

image

如果 ID 在列表中,我看到这条消息:

image

如果这对其他人有帮助,代码如下(只需创建一个组件并将脚本添加到 JS 选项卡):

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("0.8.31", (api) => {
  // 配置:在此处添加您的用户 ID 和分类 ID
  const TARGET_USER_IDS = [2]; // 替换为实际的用户 ID
  const TARGET_CATEGORY_IDS = [4,49]; // 替换为实际的分类 ID
  const REMINDER_MESSAGE = "🛑 Add the appropriate tag to this post!"; // 🛑 在此帖中添加适当的标签!
  
  let previousCategoryId = null;
  let checkInterval = null;
  
  function checkAndUpdateMessage() {
    const composer = api.container.lookup("controller:composer");
    if (!composer || !composer.model) {
      // Composer 已消失,停止检查
      if (checkInterval) {
        clearInterval(checkInterval);
        checkInterval = null;
      }
      return;
    }
    
    const currentUser = api.getCurrentUser();
    if (!currentUser || !TARGET_USER_IDS.includes(currentUser.id)) return;
    
    const model = composer.model;
    const categoryId = model.categoryId;
    
    // 仅在分类更改时执行操作
    if (categoryId === previousCategoryId) return;
    previousCategoryId = categoryId;
    
    const currentReply = model.reply || "";
    
    // 如果消息已被添加,则将其删除
    if (currentReply.startsWith(REMINDER_MESSAGE)) {
      model.set("reply", currentReply.replace(REMINDER_MESSAGE, "").trim());
    }
    
    // 如果在目标分类中且撰写器为空,则添加消息
    if (categoryId && TARGET_CATEGORY_IDS.includes(categoryId)) {
      const cleanReply = model.reply || "";
      if (cleanReply.trim().length === 0) {
        model.set("reply", REMINDER_MESSAGE);
      }
    }
  }
  
  // 撰写器打开时进行检查
  api.onAppEvent("composer:opened", () => {
    previousCategoryId = null;
    checkAndUpdateMessage();
    
    // 开始轮询分类更改
    if (checkInterval) clearInterval(checkInterval);
    checkInterval = setInterval(checkAndUpdateMessage, 300);
  });
  
  // 撰写器关闭时停止检查
  api.onAppEvent("composer:closed", () => {
    if (checkInterval) {
      clearInterval(checkInterval);
      checkInterval = null;
    }
    previousCategoryId = null;
  });
});
1 个赞