如果您有一个现有的网站或应用程序,并希望在您的 Discourse 论坛上鼓励讨论,那么在您的应用程序中显示 Discourse 通知会很有帮助。本指南将向您展示如何使用 Discourse API 来获取用户通知以及如何将它们标记为已读。
推荐的 API 使用方式是让您的应用程序向 Discourse 发起后端请求,然后将该数据传递给您应用程序的前端/表示层。
请查看 API 文档以获取有关如何使用 Discourse API 的信息。
获取用户通知
要通过 API 获取通知,您可以向 /notifications 端点发出经过身份验证的 GET 请求。您可以在 Api-Username 标头或作为查询参数中指定要获取通知的用户名:/notifications?username=<username>。
可选查询参数
| 参数 | 描述 |
|---|---|
username |
要获取通知的用户名 |
filter |
按阅读状态筛选:read 或 unread |
filter_by_types |
要筛选的通知类型名称的逗号分隔列表(例如 mentioned,replied) |
offset |
分页偏移量 |
limit |
要返回的通知数量(最多 60 个) |
示例请求
curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: system"
这将返回以下 JSON 响应
{
"notifications": [
{
"id": 3,
"user_id": 5,
"external_id": null,
"notification_type": 12,
"read": true,
"high_priority": false,
"created_at": "2019-06-17T20:26:05.670Z",
"post_number": null,
"topic_id": null,
"slug": null,
"data": {
"badge_id": 41,
"badge_name": "First Emoji",
"badge_slug": "first-emoji",
"badge_title": false,
"username": "blake"
}
},
{
"id": 2,
"user_id": 5,
"external_id": null,
"notification_type": 6,
"read": true,
"high_priority": true,
"created_at": "2019-06-17T20:26:04.305Z",
"post_number": 1,
"topic_id": 10,
"fancy_title": "Greetings!",
"slug": "greetings",
"data": {
"topic_title": "Greetings!",
"original_post_id": 14,
"original_post_type": 1,
"original_username": "discobot",
"revision_number": null,
"display_username": "discobot"
}
}
],
"total_rows_notifications": 2,
"seen_notification_id": 3,
"load_more_notifications": "/notifications?offset=60&username=blake"
}
这会返回一个通知数组。如果您只对显示未读通知感兴趣,可以传递 filter=unread 查询参数,让服务器只返回未读通知。例如:
curl -X GET "http://localhost:8080/notifications.json?username=blake.erickson&filter=unread" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: system"
您可以访问此页面查看 通知类型列表。例如,通知类型 12 对应于“granted_badge”(授予徽章)。
将通知标记为已读
现在您已经获取了用户的通知,可以通过向 /notifications/mark-read 发送 PUT 请求并将通知的 id 放在请求正文中,并在请求标头中指定用户名来将其标记为已读。
示例请求
curl -X PUT "http://localhost:8080/notifications/mark-read" \
-H "Api-Key: e81c4022f148c872a98fb38dac1d9619c7f5b245b42ba98fa467968bbed7551e" \
-H "Api-Username: blake.erickson" \
-F "id=4"
您也可以省略通知 ID,它将把该用户的所有通知标记为已读。
这将返回一个简单的“OK”JSON 响应:
{
"success": "OK"
}