Module: Brainiac::Plugins::Discord::Api

Defined in:
lib/brainiac/plugins/discord/api.rb

Overview

Discord REST API helpers.

Low-level HTTP methods and convenience wrappers for the Discord v10 API. Used by the Discord handler itself, but also available for other plugins (e.g. GitHub deploy notifications, Zoho email notifications).

Constant Summary collapse

DISCORD_API_BASE =
"https://discord.com/api/v10"
RESERVED_EMOJIS =

Emojis reserved for brainiac functionality — not treated as feedback

%w[👀  🛑 🚫 ⚠️  😶   🧠].freeze

Class Method Summary collapse

Class Method Details

.add_reaction(channel_id, message_id, emoji, token:) ⇒ Object

--- Reactions ---



132
133
134
135
# File 'lib/brainiac/plugins/discord/api.rb', line 132

def add_reaction(channel_id, message_id, emoji, token:)
  encoded = URI.encode_www_form_component(emoji)
  request(:put, "/channels/#{channel_id}/messages/#{message_id}/reactions/#{encoded}/@me", token: token)
end

.create_forum_post(channel_id, title:, content:, token:) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/brainiac/plugins/discord/api.rb', line 177

def create_forum_post(channel_id, title:, content:, token:)
  thread_name = title.length > 100 ? "#{title[0..96]}..." : title
  result = request(:post, "/channels/#{channel_id}/threads", token: token, body: {
                     name: thread_name,
                     message: { content: content },
                     auto_archive_duration: 1440
                   })
  if result && result["id"]
    LOG.info "[Discord] Forum post created in channel #{channel_id}, thread_id: #{result["id"]}" if defined?(LOG)
  elsif defined?(LOG)
    LOG.error "[Discord] Failed to create forum post in channel #{channel_id}, result: #{result.inspect}"
  end
  result
end

.create_thread(channel_id, message_id, name:, token:) ⇒ Object

--- Threads & Forums ---



144
145
146
147
148
149
150
# File 'lib/brainiac/plugins/discord/api.rb', line 144

def create_thread(channel_id, message_id, name:, token:)
  thread_name = name.length > 100 ? "#{name[0..96]}..." : name
  request(:post, "/channels/#{channel_id}/messages/#{message_id}/threads", token: token, body: {
            name: thread_name,
            auto_archive_duration: 1440
          })
end

.fetch_channel_history(channel_id, before_message_id, token:, limit: 10) ⇒ Object

--- Channel & Message Operations ---



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/brainiac/plugins/discord/api.rb', line 59

def fetch_channel_history(channel_id, before_message_id, token:, limit: 10)
  messages = request(:get, "/channels/#{channel_id}/messages?before=#{before_message_id}&limit=#{limit}", token: token)

  all_messages = messages.is_a?(Array) ? messages : []

  if all_messages.any?
    oldest = all_messages.last
    all_messages << oldest["referenced_message"] if oldest && oldest["type"] == 21 && oldest["referenced_message"]
  end

  return "" if all_messages.empty?

  lines = all_messages.reverse.filter_map do |msg|
    author = msg.dig("author", "username") || "unknown"
    content = msg["content"]&.strip || ""
    next if content.empty?

    "#{author}: #{content}"
  end

  return "" if lines.empty?

  lines.join("\n")
rescue StandardError => e
  LOG.warn "[Discord] Failed to fetch channel history: #{e.message}" if defined?(LOG)
  ""
end

.fetch_channel_info(channel_id, token:) ⇒ Object



87
88
89
# File 'lib/brainiac/plugins/discord/api.rb', line 87

def fetch_channel_info(channel_id, token:)
  request(:get, "/channels/#{channel_id}", token: token)
end

.fetch_guild_member(guild_id, user_id, token:) ⇒ Object



95
96
97
# File 'lib/brainiac/plugins/discord/api.rb', line 95

def fetch_guild_member(guild_id, user_id, token:)
  request(:get, "/guilds/#{guild_id}/members/#{user_id}", token: token)
end

.fetch_message(channel_id, message_id, token:, log_errors: true) ⇒ Object



91
92
93
# File 'lib/brainiac/plugins/discord/api.rb', line 91

def fetch_message(channel_id, message_id, token:, log_errors: true)
  request(:get, "/channels/#{channel_id}/messages/#{message_id}", token: token, log_errors: log_errors)
end

.find_latest_forum_thread(channel_id, token:) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/brainiac/plugins/discord/api.rb', line 157

def find_latest_forum_thread(channel_id, token:)
  channel_info = fetch_channel_info(channel_id, token: token)
  return nil unless channel_info && channel_info["guild_id"]

  guild_id = channel_info["guild_id"]
  result = request(:get, "/guilds/#{guild_id}/threads/active", token: token)
  return nil unless result && result["threads"]

  forum_threads = result["threads"]
                  .select { |t| t["parent_id"] == channel_id }
                  .sort_by { |t| t["id"].to_i }
                  .reverse

  return nil if forum_threads.empty?

  latest = forum_threads.first
  LOG.info "[Discord] Found latest forum thread: #{latest["id"]} (#{latest["name"]}) in channel #{channel_id}" if defined?(LOG)
  latest
end

.find_root_message(message, channel_id, bot_token) ⇒ Object

--- Helpers ---



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/brainiac/plugins/discord/api.rb', line 214

def find_root_message(message, channel_id, bot_token)
  current_msg = message
  visited = Set.new
  max_depth = 20
  walked = false

  max_depth.times do
    msg_id = current_msg["id"]
    return { id: msg_id, content: nil, author: nil } if visited.include?(msg_id)

    visited << msg_id

    ref = current_msg["message_reference"]
    break unless ref

    ref_msg_id = ref["message_id"]
    ref_channel = ref["channel_id"] || channel_id
    break unless ref_msg_id

    referenced = request(:get, "/channels/#{ref_channel}/messages/#{ref_msg_id}", token: bot_token)
    break unless referenced

    current_msg = referenced
    walked = true
  end

  {
    id: current_msg["id"],
    content: walked ? current_msg["content"]&.strip : nil,
    author: walked ? current_msg.dig("author", "username") : nil
  }
end

.forum_channel?(channel_id, token:) ⇒ Boolean

Returns:

  • (Boolean)


152
153
154
155
# File 'lib/brainiac/plugins/discord/api.rb', line 152

def forum_channel?(channel_id, token:)
  info = fetch_channel_info(channel_id, token: token)
  info && info["type"] == 15
end

.mention_rosterObject

Build a Discord mention roster so the agent can @mention people and other bots.



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/brainiac/plugins/discord/api.rb', line 248

def mention_roster
  lines = []

  Gateway.each_bot do |agent_key, info|
    next unless info[:user_id]

    display = agent_display_name(agent_key) || agent_key.capitalize
    lines << "  - #{display}: `<@#{info[:user_id]}>`"
  end

  Config.user_mappings.each do |name, discord_id|
    lines << "  - #{name}: `<@#{discord_id}>`"
  end

  lines.join("\n")
end

.remove_reaction(channel_id, message_id, emoji, token:) ⇒ Object



137
138
139
140
# File 'lib/brainiac/plugins/discord/api.rb', line 137

def remove_reaction(channel_id, message_id, emoji, token:)
  encoded = URI.encode_www_form_component(emoji)
  request(:delete, "/channels/#{channel_id}/messages/#{message_id}/reactions/#{encoded}/@me", token: token)
end

.request(method, path, token:, body: nil, log_errors: true) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/brainiac/plugins/discord/api.rb', line 22

def request(method, path, token:, body: nil, log_errors: true)
  uri = URI("#{DISCORD_API_BASE}#{path}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  req = case method
        when :get    then Net::HTTP::Get.new(uri)
        when :post   then Net::HTTP::Post.new(uri)
        when :put    then Net::HTTP::Put.new(uri)
        when :delete then Net::HTTP::Delete.new(uri)
        end

  req["Authorization"] = "Bot #{token}"
  req["Content-Type"] = "application/json"
  req.body = body.to_json if body

  response = http.request(req)

  if response.code.to_i == 429
    retry_after = JSON.parse(response.body)["retry_after"] || 1
    LOG.warn "[Discord] Rate limited, waiting #{retry_after}s" if defined?(LOG)
    sleep retry_after
    return request(method, path, token: token, body: body, log_errors: log_errors)
  end

  if response.code.to_i >= 400 && log_errors && defined?(LOG)
    LOG.error "[Discord] API error (#{method} #{path}): HTTP #{response.code} - #{response.body}"
  end

  JSON.parse(response.body) unless response.body.nil? || response.body.empty?
rescue StandardError => e
  LOG.error "[Discord] API error (#{method} #{path}): #{e.message}" if log_errors && defined?(LOG)
  nil
end

.search_gif(query) ⇒ Object

--- GIF Search ---



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/brainiac/plugins/discord/api.rb', line 194

def search_gif(query)
  api_key = Config.giphy_api_key
  return [] unless api_key

  uri = URI("https://api.giphy.com/v1/gifs/search")
  uri.query = URI.encode_www_form(api_key: api_key, q: query, limit: 5, rating: "pg-13")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  response = http.get(uri)
  return [] unless response.code.to_i == 200

  data = JSON.parse(response.body)
  (data["data"] || []).map { |g| { "url" => g.dig("images", "original", "url") || g["url"] } }
rescue StandardError => e
  LOG.warn "[Discord] GIF search error: #{e.message}" if defined?(LOG)
  []
end

.send_long_message(channel_id, content, token:, reply_to: nil) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/brainiac/plugins/discord/api.rb', line 113

def send_long_message(channel_id, content, token:, reply_to: nil)
  if content.length <= 2000
    send_message(channel_id, content, token: token, reply_to: reply_to)
    return
  end

  chunks = split_content(content)
  chunks.each_with_index do |chunk, i|
    send_message(channel_id, chunk, token: token, reply_to: i.zero? ? reply_to : nil)
    sleep 0.5
  end
end

.send_message(channel_id, content, token:, reply_to: nil) ⇒ Object

--- Messaging ---



101
102
103
104
105
106
107
108
109
110
111
# File 'lib/brainiac/plugins/discord/api.rb', line 101

def send_message(channel_id, content, token:, reply_to: nil)
  body = { content: content }
  body[:message_reference] = { message_id: reply_to } if reply_to
  result = request(:post, "/channels/#{channel_id}/messages", token: token, body: body)
  if result && result["id"]
    LOG.info "[Discord] Message posted to channel #{channel_id}, message_id: #{result["id"]}" if defined?(LOG)
  elsif defined?(LOG)
    LOG.error "[Discord] Failed to post message to channel #{channel_id}, result: #{result.inspect}"
  end
  result
end

.send_typing(channel_id, token:) ⇒ Object



126
127
128
# File 'lib/brainiac/plugins/discord/api.rb', line 126

def send_typing(channel_id, token:)
  request(:post, "/channels/#{channel_id}/typing", token: token)
end