# 分享您使用 Discourse REST API 的用例 🧑‍💻

**URL:** https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139
**Category:** Development
**Tags:** rest-api
**Created:** [2023年七月19日 15:17 UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139 "2023-07-19T15:17:05Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Canapin](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/canapin/32/119591_2.png) [@Canapin](https://meta.discourse.org/u/Canapin)
#### Post date: [2023年七月19日 15:17 UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139/1 "2023-07-19T15:17:05Z")

</div>

大家好 🙂

许多人出于各种目的使用 Discourse API，从自动化任务到与其他应用程序进行交互。

您能分享一下您是如何使用它的吗？

- 目标是什么？

- 您为此使用了什么技术/软件/编程语言？

以下是我的使用示例：

- 我使用一个可审核项目（reviewable item）的 webhook，它会执行一个 PHP 脚本，该脚本使用 Discourse 的 API 来触发自动删除垃圾信息发送者。我的社区每天都有许多被标记的帖子，垃圾信息检测准确率为 100%，这使得管理员和版主的工作更加轻松，因为他们不再需要手动审核大多数这些账户（我不建议使用这种方法，我在使用前仔细考虑并进行了测试）。

- 使用一个 Ko-Fi（一个捐赠网站）的 webhook，它将通过 PHP 脚本使用 Discourse 的 API 来更新主题组件（theme component）的设置值。目标是在 Discourse 上显示一个实时更新的捐赠进度条。

- 我在测试时使用 Insomnia 来进行测试。它可以用来填充我的测试实例中的特定内容，在构思我想要创建的项目时测试请求，在 meta 上帮助他人等。

您呢？请随意详述，我相信有很多有趣的用法可以听 🙂

* * *

关于 API 的参考主题：[Discourse REST API Documentation](https://meta.discourse.org/t/discourse-rest-api-documentation/22706?u=canapin)  
官方文档： [https://docs.discourse.org/](https://docs.discourse.org/)

---

<div class="post-metadata">

### Author: ![packman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/packman/32/289322_2.png) [@packman](https://meta.discourse.org/u/packman)
#### Post date: [2023年七月19日 15:34 UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139/2 "2023-07-19T15:34:53Z")

</div>

我经营一个业余气象学家（天气观察者）论坛。我和另一个人提供天气数据源，全球有数百人使用这些数据源生成自己的超本地化天气预报。

我们的一位用户编写了一些复杂的统计脚本来检查他的天气预报质量以及数据源的可用性。如果他的脚本发现数据源中存在缺失、损坏或延迟的数据，它们就会在用于支持天气预报软件的论坛类别中发布帖子，让其他天气预报员知道可能也会影响到他们的问题。

用于检测数据源异常的脚本使用 PHP。它们会生成一个描述问题的 JSON 文件，然后使用 cURL 通过 API 上传帖子。

---

<div class="post-metadata">

### Author: ![maiki](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/maiki/32/233950_2.png) [@maiki](https://meta.discourse.org/u/maiki)
#### Post date: [2023年八月8日 18:58 UTC](https://meta.discourse.org/t/share-your-use-cases-of-using-discourse-rest-api/272139/3 "2023-08-08T18:58:57Z")

</div>

我最近尝试了各种平台来连接步骤，我想分享一个让我兴奋的平台：光学字符识别（OCR）来检测图像中的文本，并将其附加到 Discourse 帖子中！

我的沙盒主题展示了它的工作原理：[https://notes.maiki.interi.org/t/testing-ocr-calls/403](https://notes.maiki.interi.org/t/testing-ocr-calls/403)

我首先在 Pipedream 上完成了这个，我将通过遵循这些步骤来解释我是如何做到的。该服务有一个用于共享工作流的 Beta 功能，以下内容共享于 [https://pipedream.com/new?h=tch\_3Z6fa9](https://pipedream.com/new?h=tch_3Z6fa9)。

> ℹ 虽然这可以成为使用 Pipedream 和 Discourse 的深度指南，但我将保持细节的简洁，因为我已经离开了该平台，稍后将分享更多关于它的信息。🙂

### 步骤

大致的思路是：将图像 URL 发送到 Google Cloud Vision API，然后将结果通过 ChatGPT 处理，最后将结果附加到 Discourse 帖子中。

#### 触发器

![Screenshot 2023-08-08 at 11-23-21 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/a/4/a/a4a6415b5ea9f3f902af982409222bfe288c8ae6.png)

这提供了一个用于发送数据的 webhook。在 Discourse 中，我创建了一个具有两个特定设置的 webhook：

![Screenshot 2023-08-08 at 11-24-41 Admin - notes](https://global.discourse-cdn.com/meta/original/4X/8/0/3/80357ec2e66e8a36ce049f5ec2ae5566e7c868df.png)

仅在帖子事件上触发意味着我的初始主题不会触发该过程；这对我很方便，因为我可以计划使用主题作为应用外部功能（我称之为“[功能性笔记](https://notes.maiki.interi.org/t/functional-notes/398)”）的容器。

 ![Screenshot 2023-08-08 at 11-24-52 Admin - notes](https://global.discourse-cdn.com/meta/original/4X/c/b/6/cb6e9f5b5dfe1f6cff178c9f357a1aeaafee9cfd.png)

仅在该标签上触发意味着我可以使用标签来控制每个主题生成的 webhook；通常我只会有一个“functions”标签，以保持流程逻辑简单。

Webhook 发送包含大量信息的负载，我们将在流程稍后使用主题和帖子 ID。

#### 基于条件的结束

 ![Screenshot 2023-08-08 at 11-32-29 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/4/2/f/42ffeaeb3c437b4374447e02242a94ca2eae8570.png)

这是一个检查是否包含编辑原因的步骤。如果包含，则停止工作流。

在最后一步中，我更新了帖子并包含了一个编辑原因，这个检查[确保我不会一直更新帖子](https://notes.maiki.interi.org/t/testing-ocr-calls/403/6)… 😅

> ℹ 我停止使用 Pipedream 的原因之一是我的 webhook 检查消耗了该服务的积分。我认为我不应该为有条件地处理 webhook 付费，因此我继续前进…

#### 提取图像 URL

 ![Screenshot 2023-08-08 at 11-37-22 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/c/7/c/c7c45d8d5856261654b52f818775bbd6c31790b6.png)

我决定在此测试中，每个帖子都将上传一张图片。此步骤检查“cooked”值并使用以下正则表达式提取 URL：

```plaintext
/https?:\/\/[^\s\"]+/

```

#### Google Cloud Vision API 调用

这是 Pipedream 上的一个自定义代码步骤。预制组件不符合我的要求，该服务还有一个代码助手，可以根据提示编写代码；由于这些 API 调用很简单，因此很容易通过这种方法生成。

它获取上一步的值（`{{steps.extract_by_regular_expression.$return_value[0].match}}`），代码如下：

```js
import { axios } from "@pipedream/platform";

export default defineComponent({
  props: {
    imageUrl: {
      type: "string",
      label: "Image URL",
      description: "URL of the image to be processed by Google Vision API",
    },
    apiKey: {
      type: "string",
      label: "API Key",
      description: "Your Google Cloud API Key",
      secret: true,
    },
  },
  async run() {
    const url = `https://vision.googleapis.com/v1/images:annotate?key=${this.apiKey}`;
    const body = {
      requests: [
        {
          image: {
            source: {
              imageUri: this.imageUrl,
            },
          },
          features: [
            {
              type: "TEXT_DETECTION",
            },
          ],
        },
      ],
    };

    const config = {
      method: "POST",
      url,
      data: body,
    };

    const response = await axios(this, config);
    return response;
  },
});

```

#### ChatGPT 进行编辑

 ![Screenshot 2023-08-08 at 11-43-11 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/8/6/c/86c6e9850ee89425fdbc6af86fd354db778d6d6c.png)

获取上一步的输出（`{{steps.google_cloud.$return_value.responses[0].fullTextAnnotation.text}}`）并将其作为用户消息传递。对于系统消息，我有：

> 你正在阅读 Vision API 检测图像中文本的输出。请审阅消息并进行编辑以提高清晰度。仅返回编辑后的文本，不带任何评论。

#### 附加到 Discourse 帖子

 ![Screenshot 2023-08-08 at 11-48-01 OCR Test - Pipedream](https://global.discourse-cdn.com/meta/original/4X/e/2/f/e2f5850c75293edbb2842153f669a67b5759e60a.png)

这是另一个自定义代码部分，因为 Pipedream 中预制的[Discourse 操作](https://pipedream.com/apps/discourse)仅涵盖了少数场景（创建主题或帖子），而我想将文本_附加_到帖子中。

首先，这是代码：

```js
import { axios } from "@pipedream/platform";

export default defineComponent({
  props: {
    discourse: {
      type: "app",
      app: "discourse",
    },
    postId: {
      type: "string",
      label: "Post ID",
      description: "The ID of the post to append text to",
    },
    text: {
      type: "string",
      label: "Text",
      description: "The text to append to the post",
    },
    editReason: {
      type: "string",
      label: "Edit Reason",
      description: "The reason for editing the post",
      optional: true,
    },
  },
  async run({ steps, $ }) {
    const url = `https://${this.discourse.$auth.domain}/posts/${this.postId}.json`;
    const response = await axios($, {
      method: "GET",
      url: url,
      headers: {
        "Api-Username": `${this.discourse.$auth.api_username}`,
        "Api-Key": `${this.discourse.$auth.api_key}`,
      },
    });

    const updatedText = `${response.raw} ${this.text}`;

    return await axios($, {
      method: "PUT",
      url: url,
      headers: {
        "Api-Username": `${this.discourse.$auth.api_username}`,
        "Api-Key": `${this.discourse.$auth.api_key}`,
      },
      data: {
        post: {
          raw: updatedText,
          edit_reason: this.editReason,
        },
      },
    });
  },
});

```

这些步骤的属性填写如下：

##### 帖子 ID

从原始负载中获取帖子 ID：`{{steps.trigger.event.body.post.id}}`

这用于直接编辑该帖子。

##### 文本

```plaintext
---

<blockquote>
 {{steps.chat.$return_value.generated_message.content}}
</blockquote>

[details="Detected text"]
{{steps.google_cloud.$return_value.responses[0].textAnnotations[0].description}}
[/details]

```

基本上，我想在每个图像下方添加一个水平分隔线，其中包含一个编辑过的文本的块引用，以及用于检查原始输出的详细信息。

由于每个帖子只包含一张图片，这很容易实现。我想知道如何一次处理多张图片？🤔

##### 编辑原因

> OCR 文本检测

这被添加为帖子更新的编辑原因，这将防止由于开头的步骤而导致帖子更新循环。☝ ♻ 🆖

> ℹ 我发现始终包含编辑原因非常有帮助，尤其是在处理外部服务时。

* * *

就是这样！正如你从我的沙盒中看到的，效果相当不错！

我即将进行一次旅行，我计划对 OpenAI 编辑进行微调，使其在需要时也能翻译成英文，这是我将添加到此工作流系统提示中的一个选项。
