forum: automatically post new forum posts to Discord.

This commit is contained in:
evazion
2021-02-18 07:08:45 -06:00
parent 93f6e935a8
commit b63d8207a9
6 changed files with 106 additions and 0 deletions

View File

@@ -250,6 +250,29 @@ class DText
text.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "")
end
def self.to_markdown(dtext)
html_to_markdown(format_text(dtext))
end
def self.html_to_markdown(html)
html = Nokogiri::HTML.fragment(html)
html.children.map do |node|
case node.name
when "div", "blockquote", "table"
"" # strip [expand], [quote], and [table] tags
when "br"
"\n"
when "text"
node.text.gsub(/_/, '\_').gsub(/\*/, '\*')
when "p", "h1", "h2", "h3", "h4", "h5", "h6"
html_to_markdown(node.inner_html) + "\n\n"
else
html_to_markdown(node.inner_html)
end
end.join
end
def self.from_html(text, inline: false, &block)
html = Nokogiri::HTML.fragment(text)

View File

@@ -0,0 +1,56 @@
class DiscordApiClient
attr_reader :webhook_id, :webhook_secret, :http
def initialize(webhook_id: Danbooru.config.discord_webhook_id, webhook_secret: Danbooru.config.discord_webhook_secret, http: Danbooru::Http.new)
@webhook_id = webhook_id
@webhook_secret = webhook_secret
@http = http
end
def enabled?
webhook_id.present? && webhook_secret.present?
end
# https://discord.com/developers/docs/resources/webhook#execute-webhook
def post_message(forum_post)
return unless enabled?
http.post(webhook_url, params: { wait: true }, json: build_message(forum_post))
end
# https://discord.com/developers/docs/resources/channel#embed-object
def build_message(forum_post)
{
embeds: [{
title: forum_post.topic.title,
description: convert_dtext(forum_post.body),
timestamp: forum_post.created_at.iso8601,
url: Routes.url_for(forum_post),
author: {
name: forum_post.creator.name,
url: Routes.url_for(forum_post.creator)
},
fields: [
{
name: "Replies",
value: forum_post.topic.response_count,
inline: true
},
{
name: "Users",
value: forum_post.topic.forum_posts.distinct.count(:creator_id),
inline: true
}
]
}]
}
end
def convert_dtext(dtext)
DText.to_markdown(dtext).truncate(2000)
end
def webhook_url
"https://discord.com/api/webhooks/#{webhook_id}/#{webhook_secret}"
end
end