通过API授予自定义徽章

Custom badges that you have created on your forum can be granted through the API. This is a great way to award badges without having to use custom badge SQL.

To grant a badge through the API, you need to know the username of the user that you wish to grant the badge to, and the ID of the badge you wish to grant. You also need to make sure you have generated an All Users API Key from your site’s Admin/API section.

Finding your API Key

This screenshot is from my local development site. Generally, you need to be very careful about sharing your API keys:

Finding the Badge ID

You can get the Badge ID from the badge’s URL. Go to your Admin/Badges section and then click on the badge that you wish to grant. The URL will look something like this: https://forum.example.com/admin/badges/102. The last number in the URL is the badge ID.

Making the API call

To test an API call, you can try granting a badge using curl or Postman. Here is how I grant a badge from my computer’s terminal with curl.

First, to make things easier, set an api_key variable:

 api_key=yourallusersapikey

Then to grant a badge with the ID of 102 to the user bobby:

curl -X POST "https://forum.example.com/user_badges" \
-H "Content-Type: multipart/form-data;" \
-H "Api-Key: $api_key" \
-H "Api-Username: system" \
-F "username=bobby" \
-F "badge_id=102" \
-F "reason=https://forum.example.com/t/whats-the-best-photo-youve-ever-taken/160/2"

The reason parameter is optional. If you supply it, it must be set to the URL of a topic or a post on your site.

You should get a JSON response with details about the badge and when it was granted.

26 个赞

Has anybody added a badge (or flair) via Zapier to Discourse API like outlined here?

Also, seems like a great candidate for an action via the official integration, @HAWK.

3 个赞

另请参阅 https://meta.discourse.org/t/how-to-create-a-custom-badge-with-an-image-through-the-api/210616,其中展示了如何上传,并提供了另一个授予徽章的示例(使用 Python)。

1 个赞

此方法未在 https://docs.discourse.org/ 的 API 文档中说明的原因是什么?

我在那里找不到这个。

2 个赞

因为似乎没有人负责维护这些文档的完整性或及时更新,而且有好心人在这里发布了这些说明。通常,API 的文档是通过 逆向工程 Discourse API 和查看源代码来获取的。

7 个赞

太好了,那是不是没有办法通过 API 自动授予此类徽章了?

例如,某人因回复获得 5,000 个赞而被授予徽章。

1 个赞

如果您是自托管用户或企业版用户,您需要启用徽章 SQL

2 个赞

如果你无法启用徽章 SQL,技术上来说可以实现自动化,但这需要分两步进行。首先,发出 API 请求运行一个数据探索器查询,该查询将返回符合你条件但尚未获得徽章的用户的用户名:使用 Discourse API 运行数据探索器查询。然后,使用该查询返回的用户名通过 API 授予徽章。

不过,这感觉有点效率低下。据我所知,没有一个路由可以一次性向多个用户授予徽章,因此,根据符合条件的用户的数量,你可能会发出大量的 API 请求。

最终,这似乎是自动化插件可以处理的事情。可以有一个定期触发器来运行具有给定查询 ID 的数据探索器查询。根据查询返回的字段,结果可用于触发各种脚本。例如,如果查询返回了 username 字段,则可用于运行授予徽章、将用户添加到组等的脚本。

2 个赞

这不会导致最初禁用徽章 SQL 的相同问题吗?

1 个赞

我不这么认为。Data Explorer 查询在 10 秒后超时的事务块中运行。我认为这样做的目的是避免徽章查询可能触发的那种问题。如果配置不当,低效的 Data Explorer 查询可能会导致网站崩溃。

现在想想,我想知道自定义徽章 SQL 是否可以有同样的保护措施。

4 个赞