gitlab-org--gitlab-foss/app/models/project_services/discord_service.rb

68 lines
1.8 KiB
Ruby
Raw Normal View History

2018-10-30 11:23:20 +00:00
# frozen_string_literal: true
require "discordrb/webhooks"
class DiscordService < ChatNotificationService
ATTACHMENT_REGEX = /: (?<entry>.*?)\n - (?<name>.*)\n*/.freeze
2018-10-30 11:23:20 +00:00
def title
s_("DiscordService|Discord Notifications")
2018-10-30 11:23:20 +00:00
end
def description
s_("DiscordService|Receive event notifications in Discord")
2018-10-30 11:23:20 +00:00
end
def self.to_param
"discord"
end
def help
2018-11-06 11:07:07 +00:00
"This service sends notifications about project events to Discord channels.<br />
2018-10-30 11:23:20 +00:00
To set up this service:
<ol>
2018-11-05 00:24:26 +00:00
<li><a href='https://support.discordapp.com/hc/en-us/articles/228383668-Intro-to-Webhooks'>Setup a custom Incoming Webhook</a>.</li>
2018-10-30 11:23:20 +00:00
<li>Paste the <strong>Webhook URL</strong> into the field below.</li>
<li>Select events below to enable notifications.</li>
</ol>"
end
def event_field(event)
2018-11-05 00:24:26 +00:00
# No-op.
2018-10-30 11:23:20 +00:00
end
def default_channel_placeholder
2018-11-05 00:24:26 +00:00
# No-op.
2018-10-30 11:23:20 +00:00
end
def self.supported_events
%w[push issue confidential_issue merge_request note confidential_note tag_push
pipeline wiki_page]
end
2018-10-30 11:23:20 +00:00
def default_fields
[
2018-11-09 22:50:37 +00:00
{ type: "text", name: "webhook", placeholder: "e.g. https://discordapp.com/api/webhooks/…" },
2018-10-30 11:23:20 +00:00
{ type: "checkbox", name: "notify_only_broken_pipelines" },
{ type: 'select', name: 'branches_to_be_notified', choices: branch_choices }
2018-10-30 11:23:20 +00:00
]
end
private
def notify(message, opts)
client = Discordrb::Webhooks::Client.new(url: webhook)
2018-11-05 00:24:26 +00:00
2018-10-30 11:23:20 +00:00
client.execute do |builder|
builder.add_embed do |embed|
embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: message.user_name, icon_url: message.user_avatar)
embed.description = (message.pretext + "\n" + Array.wrap(message.attachments).join("\n")).gsub(ATTACHMENT_REGEX, " \\k<entry> - \\k<name>\n")
end
2018-10-30 11:23:20 +00:00
end
end
def custom_data(data)
super(data).merge(markdown: true)
end
end