Files
danbooru/app/logical/discord_api_client.rb
evazion d5903b61c4 discord: add function to register all commands.
* Add a `DiscordSlashCommand.register_slash_commands!` method to register
  all slash commands with the Discord API.
* Allow registering global commands.
* Refactor slash commands to use class attributes for the command
  name, description, and options.
2021-03-18 22:59:43 -05:00

59 lines
1.4 KiB
Ruby

class DiscordApiClient
extend Memoist
BASE_URL = "https://discord.com/api/v8"
attr_reader :application_id, :bot_token, :http
def initialize(application_id: Danbooru.config.discord_application_client_id, bot_token: Danbooru.config.discord_bot_token, http: Danbooru::Http.new)
@application_id = application_id
@bot_token = bot_token
@http = http
end
def register_slash_command(name:, description:, options: [], guild_id: nil)
json = {
name: name,
description: description,
options: options
}
if guild_id.present?
post("/applications/#{application_id}/guilds/#{guild_id}/commands", json)
else
post("/applications/#{application_id}/commands", json)
end
end
def get_channel(channel_id, **options)
get("/channels/#{channel_id}", **options)
end
def me(**options)
get("/users/@me", **options)
end
def get(url, cache: nil, **options)
if cache
client.cache(cache).get("#{BASE_URL}/#{url}").parse
else
client.get("#{BASE_URL}/#{url}").parse
end
end
def post(url, data)
client.post("#{BASE_URL}/#{url}", json: data).parse
end
def client
headers = {
"User-Agent": "#{Danbooru.config.canonical_app_name} (#{Danbooru.config.source_code_url}, 1.0)",
"Authorization": "Bot #{bot_token}"
}
http.headers(headers)
end
memoize :client
end