diff --git a/lib/bot/command_cache.ex b/lib/bot/command_cache.ex new file mode 100644 index 0000000..08369f2 --- /dev/null +++ b/lib/bot/command_cache.ex @@ -0,0 +1,30 @@ +defmodule Lanyard.DiscordBot.CommandCache do + @table :slash_commands + + def init do + :ets.new(@table, [:named_table, :set, :public]) + end + + def put_many(commands) when is_list(commands) do + Enum.each(commands, fn + %{"name" => name, "id" => id} -> :ets.insert(@table, {name, id}) + _ -> :ok + end) + end + + def get_id(name) do + case :ets.lookup(@table, name) do + [{^name, id}] -> id + _ -> nil + end + rescue + ArgumentError -> nil + end + + def mention(name) do + case get_id(name) do + nil -> "`/#{name}`" + id -> "" + end + end +end diff --git a/lib/bot/command_handler.ex b/lib/bot/command_handler.ex index 3eaf7a5..aa6424a 100644 --- a/lib/bot/command_handler.ex +++ b/lib/bot/command_handler.ex @@ -1,31 +1,28 @@ defmodule Lanyard.DiscordBot.CommandHandler do + alias Lanyard.DiscordBot.CommandCache + alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed + @command_map %{ "get" => Lanyard.DiscordBot.Commands.Get, "set" => Lanyard.DiscordBot.Commands.Set, "del" => Lanyard.DiscordBot.Commands.Del, "apikey" => Lanyard.DiscordBot.Commands.ApiKey, "kv" => Lanyard.DiscordBot.Commands.KV, - "help" => Lanyard.DiscordBot.Commands.Help + "help" => Lanyard.DiscordBot.Commands.Help, + "about" => Lanyard.DiscordBot.Commands.About } def handle_message(payload) do case payload.data do - # Don't handle messages from other bots %{"author" => %{"bot" => true}} -> :ok - %{"content" => content} -> - if String.starts_with?(content, Application.get_env(:lanyard, :command_prefix)) do - [attempted_command | args] = - content - |> String.to_charlist() - |> tl() - |> to_string() - |> String.split(" ") - - unless @command_map[attempted_command] == nil do - @command_map[attempted_command].handle(args, payload.data) - end + %{} = data -> + cond do + dm?(data) -> handle_dm(data) + bot_mentioned?(data) -> send_mention_hint(data["channel_id"]) + true -> :ok end _ -> @@ -34,4 +31,60 @@ defmodule Lanyard.DiscordBot.CommandHandler do end def handle_command(_unknown_command, _args), do: :ok + + defp handle_dm(data) do + prefix = Application.get_env(:lanyard, :command_prefix) + content = data["content"] || "" + + if String.starts_with?(content, prefix) do + handle_prefix_command(content, data) + else + send_dm_hint(data["channel_id"]) + end + end + + defp handle_prefix_command(content, data) do + [attempted_command | args] = + content + |> String.to_charlist() + |> tl() + |> to_string() + |> String.split(" ") + + unless @command_map[attempted_command] == nil do + @command_map[attempted_command].handle(args, data) + end + end + + defp dm?(data), do: is_nil(data["guild_id"]) + + defp bot_mentioned?(data) do + bot_id = Application.get_env(:lanyard, :bot_user_id) + mentions = data["mentions"] || [] + bot_id != nil && Enum.any?(mentions, fn m -> m["id"] == bot_id end) + end + + defp send_dm_hint(channel_id) do + embed = + Embed.info(%{ + title: ":wave: Hi! I'm Lanyard", + description: + "Looking for your API key? Use #{CommandCache.mention("apikey")} — the response is private to you.\n\n**Other slash commands:**\n#{CommandCache.mention("kv")} — view your K/V keys\n#{CommandCache.mention("get")} — get a value\n#{CommandCache.mention("set")} — set a key\n#{CommandCache.mention("del")} — delete a key\n#{CommandCache.mention("about")} — about Lanyard, docs & privacy policy", + footer: %{text: "Type / in any channel to see my commands"} + }) + + DiscordApi.send_message(channel_id, embed) + end + + defp send_mention_hint(channel_id) do + embed = + Embed.info(%{ + title: ":wave: Hi, I'm Lanyard", + description: + "I expose your Discord presence as a public API. Embed your status on websites, dashboards, and more.\n\n**Slash commands:**\n#{CommandCache.mention("kv")} — view your K/V keys\n#{CommandCache.mention("get")} — get a value\n#{CommandCache.mention("set")} — set a key\n#{CommandCache.mention("del")} — delete a key\n#{CommandCache.mention("apikey")} — generate or rotate your private API key (response is private to you)\n#{CommandCache.mention("about")} — about Lanyard, docs & privacy policy", + footer: %{text: "Type / in any channel to see my commands"} + }) + + DiscordApi.send_message(channel_id, embed) + end end diff --git a/lib/bot/command_registration.ex b/lib/bot/command_registration.ex new file mode 100644 index 0000000..a28994c --- /dev/null +++ b/lib/bot/command_registration.ex @@ -0,0 +1,71 @@ +defmodule Lanyard.DiscordBot.CommandRegistration do + require Logger + + alias Lanyard.DiscordBot.CommandCache + alias Lanyard.DiscordBot.InteractionHandler + + @api_host "https://discord.com/api/v9" + + def register(application_id) do + definitions = InteractionHandler.command_definitions() + + result = + :put + |> Finch.build( + "#{@api_host}/applications/#{application_id}/commands", + [ + {"Authorization", "Bot " <> Application.get_env(:lanyard, :bot_token)}, + {"Content-Type", "application/json"} + ], + Jason.encode!(definitions) + ) + |> Finch.request(Lanyard.Finch) + + case result do + {:ok, %{status: status, body: body}} when status in 200..299 -> + cache_from_body(body) + Logger.info("Discord: Registered #{length(definitions)} slash commands") + :ok + + {:ok, %{status: status, body: body}} -> + Logger.error("Discord: Failed to register slash commands (status #{status}): #{body}") + fetch(application_id) + :error + + {:error, reason} -> + Logger.error("Discord: Failed to register slash commands: #{inspect(reason)}") + fetch(application_id) + :error + end + end + + def fetch(application_id) do + result = + :get + |> Finch.build( + "#{@api_host}/applications/#{application_id}/commands", + [{"Authorization", "Bot " <> Application.get_env(:lanyard, :bot_token)}] + ) + |> Finch.request(Lanyard.Finch) + + case result do + {:ok, %{status: status, body: body}} when status in 200..299 -> + cache_from_body(body) + :ok + + _ -> + Logger.error("Discord: Failed to fetch slash commands: #{inspect(result)}") + :error + end + end + + defp cache_from_body(body) do + case Jason.decode(body) do + {:ok, commands} when is_list(commands) -> + CommandCache.put_many(commands) + + _ -> + :ok + end + end +end diff --git a/lib/bot/commands/about.ex b/lib/bot/commands/about.ex new file mode 100644 index 0000000..9ed1f3c --- /dev/null +++ b/lib/bot/commands/about.ex @@ -0,0 +1,43 @@ +defmodule Lanyard.DiscordBot.Commands.About do + alias Lanyard.DiscordBot.CommandCache + alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed + alias Lanyard.DiscordBot.InteractionHandler + + def definition do + %{ + name: "about", + description: "Learn what Lanyard is, how to use it, and where to find the docs" + } + end + + def handle(_, payload) do + DiscordApi.send_message(payload["channel_id"], embed(payload["author"]["id"])) + end + + def handle_interaction(interaction) do + user_id = InteractionHandler.user_id(interaction) + + DiscordApi.respond_to_interaction(interaction["id"], interaction["token"], embed(user_id)) + end + + defp embed(user_id) do + base = Application.get_env(:lanyard, :external_url) + + Embed.info(%{ + title: ":wave: Hi, I'm Lanyard", + description: + "I expose your Discord presence as a public API. Embed your status on websites, dashboards, and more.\n\n**Slash commands:**\n#{CommandCache.mention("kv")} — view your K/V keys\n#{CommandCache.mention("get")} — get a value\n#{CommandCache.mention("set")} — set a key\n#{CommandCache.mention("del")} — delete a key\n#{CommandCache.mention("apikey")} — generate or rotate your private API key (response is private to you)\n#{CommandCache.mention("help")} — list all commands", + fields: [ + %{name: "Your presence", value: "#{base}/v1/users/#{user_id}", inline: false}, + %{ + name: "Links", + value: + "[API/Socket docs](https://github.com/Phineas/lanyard#readme) · [Source code](https://github.com/Phineas/lanyard) · [Privacy policy](https://privacy.lanyard.rest/)", + inline: false + } + ], + footer: %{text: "lanyard.rest"} + }) + end +end diff --git a/lib/bot/commands/api_key.ex b/lib/bot/commands/api_key.ex index 194df86..f5f2ed9 100644 --- a/lib/bot/commands/api_key.ex +++ b/lib/bot/commands/api_key.ex @@ -1,25 +1,32 @@ defmodule Lanyard.DiscordBot.Commands.ApiKey do alias Lanyard.Connectivity.Redis alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed - def handle(_, %{"channel_id" => channel_id, "guild_id" => _guild_id} = _p) do - DiscordApi.send_message(channel_id, ":x: You can only perform this command in DMs with me") + def definition do + %{ + name: "apikey", + description: "Generate (or regenerate) your private Lanyard API key" + } end def handle(_, payload) do user_id = payload["author"]["id"] key = generate_api_key(user_id) - Lanyard.DiscordBot.DiscordApi.send_message(payload["channel_id"], %{ - title: "Lanyard API Key", - description: - "**Absolutely do not share or post this key anywhere, it is a secret key that will allow anyone to manage your Lanyard K/V**\n\n**This key is not to be used in a front-end application/website**\n\nIf you are looking for the public endpoint for your data, you would use your discord user ID like so\n#{Application.get_env(:lanyard, :external_url)}/v1/users/#{user_id}", - color: 0x5865F2, - footer: %{text: "Run this command again if you need to re-generate your key"}, - fields: [ - %{name: "Key", value: "||`#{key}`||\n-# *click above to reveal*", inline: false} - ] - }) + DiscordApi.send_message(payload["channel_id"], key_embed(user_id, key, ephemeral?: false)) + end + + def handle_interaction(interaction) do + user_id = interaction_user_id(interaction) + key = generate_api_key(user_id) + + DiscordApi.respond_to_interaction( + interaction["id"], + interaction["token"], + key_embed(user_id, key, ephemeral?: true), + ephemeral: true + ) end def contains_api_key?(user_id, candidates) do @@ -30,20 +37,12 @@ defmodule Lanyard.DiscordBot.Commands.ApiKey do |> Enum.any?(&(&1 == stored_key)) end - def generate_and_send_new(original_channel, user_id) do - DiscordApi.send_message( - original_channel, - ":x: Whoops, you just posted your API key, this is meant to stay private, regenerating this for you, check your DM" - ) - - key = generate_api_key(user_id) - - dm_channel = DiscordApi.create_dm(user_id) - - DiscordApi.send_message( - dm_channel, - ":repeat: **We've regenerated your api key as you used it in a K/V command.**\nYour new Lanyard API key is `#{key}`\n\n**ABSOLUTELY DO NOT SHARE OR POST THIS KEY ANYWHERE IT WILL ALLOW ANYONE TO MANAGE YOUR LANYARD K/V**\n*Run `.apikey` in this DM if you need to re-generate your key*" - ) + def leak_warning_embed do + Embed.warn(%{ + title: ":warning: That looks like your API key", + description: + "Your private Lanyard API key isn't a K/V key or value — it's a separate credential for the HTTP API and shouldn't be pasted as a command argument.\n\nIf you think the key has been exposed and want to rotate it, run #{Lanyard.DiscordBot.CommandCache.mention("apikey")}." + }) end def generate_api_key(user_id) do @@ -59,4 +58,34 @@ defmodule Lanyard.DiscordBot.Commands.ApiKey do key end + + defp key_embed(user_id, key, opts) do + base = Application.get_env(:lanyard, :external_url) + ephemeral? = Keyword.get(opts, :ephemeral?, false) + + save_line = + if ephemeral? do + "**Save this key now — this message is only visible to you and won't stick around.** You can always run #{Lanyard.DiscordBot.CommandCache.mention("apikey")} to generate a new one, but the old one will stop working." + else + "**Save this key somewhere safe.** You can always run #{Lanyard.DiscordBot.CommandCache.mention("apikey")} to generate a new one, but the old one will stop working." + end + + Embed.info(%{ + title: "Lanyard API Key", + description: + "#{save_line}\n\n**Do not share or post this key anywhere — it lets anyone manage your Lanyard K/V.**\n\nThis key is not meant for front-end applications. For the public read endpoint, use your Discord user ID:\n#{base}/v1/users/#{user_id}", + fields: [ + %{name: "Key", value: "||`#{key}`||\n-# *click to reveal*", inline: false} + ], + footer: %{text: "Run /apikey again if you need to regenerate"} + }) + end + + defp interaction_user_id(interaction) do + cond do + user = interaction["user"] -> user["id"] + member = interaction["member"] -> member["user"]["id"] + true -> nil + end + end end diff --git a/lib/bot/commands/del.ex b/lib/bot/commands/del.ex index 15cd1a9..6097562 100644 --- a/lib/bot/commands/del.ex +++ b/lib/bot/commands/del.ex @@ -1,27 +1,73 @@ defmodule Lanyard.DiscordBot.Commands.Del do alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed alias Lanyard.DiscordBot.Commands.ApiKey + alias Lanyard.DiscordBot.InteractionHandler - def handle([key], payload) do - if ApiKey.contains_api_key?(payload["author"]["id"], key) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) + def definition do + %{ + name: "del", + description: "Delete a key from your Lanyard K/V store", + options: [ + %{name: "key", description: "The key to delete", type: 3, required: true} + ] + } + end + + def handle(args, payload) do + user_id = payload["author"]["id"] + channel_id = payload["channel_id"] + + if ApiKey.contains_api_key?(user_id, args) do + DiscordApi.send_message(channel_id, ApiKey.leak_warning_embed()) else - Lanyard.KV.Interface.del(payload["author"]["id"], key) + embed = + case args do + [key] -> kv_del_embed(user_id, key) + _ -> usage_embed() + end - DiscordApi.send_message(payload["channel_id"], ":white_check_mark: Deleted key: `#{key}`") + DiscordApi.send_message(channel_id, embed) end + + :ok end - def handle(args, payload) do - if ApiKey.contains_api_key?(payload["author"]["id"], args) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) + def handle_interaction(interaction) do + user_id = InteractionHandler.user_id(interaction) + key = InteractionHandler.option(interaction, "key") + interaction_id = interaction["id"] + interaction_token = interaction["token"] + + if ApiKey.contains_api_key?(user_id, key) do + DiscordApi.respond_to_interaction( + interaction_id, + interaction_token, + ApiKey.leak_warning_embed(), + ephemeral: true + ) else - DiscordApi.send_message( - payload["channel_id"], - "Invalid usage. Example `del` command usage:\n`#{Application.get_env(:lanyard, :command_prefix)}del `" + DiscordApi.respond_to_interaction( + interaction_id, + interaction_token, + kv_del_embed(user_id, key) ) end + end - :ok + defp kv_del_embed(user_id, key) do + Lanyard.KV.Interface.del(user_id, key) + + Embed.success(%{ + title: ":white_check_mark: Key Deleted", + description: "Deleted key `#{key}` from your K/V store." + }) + end + + defp usage_embed do + Embed.error(%{ + title: ":x: Invalid usage", + description: "Usage: `#{Application.get_env(:lanyard, :command_prefix)}del `" + }) end end diff --git a/lib/bot/commands/get.ex b/lib/bot/commands/get.ex index 7c34566..622c3c2 100644 --- a/lib/bot/commands/get.ex +++ b/lib/bot/commands/get.ex @@ -1,46 +1,101 @@ defmodule Lanyard.DiscordBot.Commands.Get do alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed alias Lanyard.DiscordBot.Commands.ApiKey + alias Lanyard.DiscordBot.InteractionHandler - def handle([key], payload) do - if ApiKey.contains_api_key?(payload["author"]["id"], key) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) - else - case Lanyard.KV.Interface.get(payload["author"]["id"], key) do - {:ok, v} -> - DiscordApi.send_message( - payload["channel_id"], - response_content(key, v, payload["author"]["id"]) - ) - - {:error, msg} -> - DiscordApi.send_message(payload["channel_id"], ":x: #{msg}") - end - end + def definition do + %{ + name: "get", + description: "Get a value from your Lanyard K/V store", + options: [ + %{name: "key", description: "The key to get", type: 3, required: true} + ] + } end def handle(args, payload) do - if ApiKey.contains_api_key?(payload["author"]["id"], args) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) + user_id = payload["author"]["id"] + channel_id = payload["channel_id"] + + if ApiKey.contains_api_key?(user_id, args) do + DiscordApi.send_message(channel_id, ApiKey.leak_warning_embed()) else - DiscordApi.send_message( - payload["channel_id"], - "Invalid usage. Example `get` command usage:\n`#{Application.get_env(:lanyard, :command_prefix)}get `" - ) + embed = + case args do + [key] -> + case kv_get_embed(user_id, key) do + {_kind, e} -> e + end + + _ -> + usage_embed() + end + + DiscordApi.send_message(channel_id, embed) end :ok end + def handle_interaction(interaction) do + user_id = InteractionHandler.user_id(interaction) + key = InteractionHandler.option(interaction, "key") + interaction_id = interaction["id"] + interaction_token = interaction["token"] + + if ApiKey.contains_api_key?(user_id, key) do + DiscordApi.respond_to_interaction( + interaction_id, + interaction_token, + ApiKey.leak_warning_embed(), + ephemeral: true + ) + else + case kv_get_embed(user_id, key) do + {:ok, embed} -> + DiscordApi.respond_to_interaction(interaction_id, interaction_token, embed) + + {:error, embed} -> + DiscordApi.respond_to_interaction(interaction_id, interaction_token, embed, ephemeral: true) + end + end + end + + @max_field_length 1_024 + + defp kv_get_embed(user_id, key) do + case Lanyard.KV.Interface.get(user_id, key) do + {:ok, v} -> + {:ok, + Embed.success(%{ + title: ":white_check_mark: Key Retrieved", + fields: [ + %{name: "Key", value: "`#{key}`", inline: false}, + %{name: "Value", value: value_field(key, v, user_id), inline: false} + ] + })} + + {:error, msg} -> + {:error, Embed.error(%{title: ":x: Error", description: msg})} + end + end + @doc false - def response_content(key, value, user_id) do - content = - ":white_check_mark: Key: `#{key}` | Value: ```#{String.replace(value, "`", "`\u200b")}```" + def value_field(key, value, user_id) do + content = "```#{String.replace(value, "`", "`\u200b")}```" - if DiscordApi.content_within_limit?(content) do + if String.length(content) <= @max_field_length do content else - ":x: The value for `#{key}` is too long to display in Discord.\nView it at #{Application.get_env(:lanyard, :external_url)}/v1/users/#{user_id}" + "The value for `#{key}` is too long to display in Discord.\nView it at #{Application.get_env(:lanyard, :external_url)}/v1/users/#{user_id}" end end + + defp usage_embed do + Embed.error(%{ + title: ":x: Invalid usage", + description: "Usage: `#{Application.get_env(:lanyard, :command_prefix)}get `" + }) + end end diff --git a/lib/bot/commands/help.ex b/lib/bot/commands/help.ex index b0304ca..4f83737 100644 --- a/lib/bot/commands/help.ex +++ b/lib/bot/commands/help.ex @@ -1,19 +1,29 @@ defmodule Lanyard.DiscordBot.Commands.Help do + alias Lanyard.DiscordBot.CommandCache alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed + + def definition do + %{ + name: "help", + description: "List Lanyard's commands" + } + end def handle(_, payload) do - prefix = Application.get_env(:lanyard, :command_prefix) + DiscordApi.send_message(payload["channel_id"], embed()) + end + + def handle_interaction(interaction) do + DiscordApi.respond_to_interaction(interaction["id"], interaction["token"], embed(), ephemeral: true) + end - DiscordApi.send_message(payload["channel_id"], %{ + defp embed do + Embed.info(%{ title: "Lanyard Bot Commands", - description: "Store and manage custom data on your Lanyard profile.", - color: 0x5865F2, + description: + "Store and manage custom data on your Lanyard profile.\n\n#{CommandCache.mention("get")} `` — get the value of a key\n#{CommandCache.mention("set")} ` ` — set a key to a value\n#{CommandCache.mention("del")} `` — delete a key\n#{CommandCache.mention("kv")} — list all of your current keys\n#{CommandCache.mention("apikey")} — get (or regenerate) your API key, only visible to you\n#{CommandCache.mention("about")} — about Lanyard, docs & privacy policy", fields: [ - %{name: "`#{prefix}get `", value: "Get the value of a key", inline: false}, - %{name: "`#{prefix}set `", value: "Set a key to a value", inline: false}, - %{name: "`#{prefix}del `", value: "Delete a key", inline: false}, - %{name: "`#{prefix}kv`", value: "List all of your current keys", inline: false}, - %{name: "`#{prefix}apikey`", value: "Get (or regenerate) your Lanyard API key, sent via DM", inline: false}, %{ name: "Docs & Source", value: diff --git a/lib/bot/commands/kv.ex b/lib/bot/commands/kv.ex index 3a50f99..af1e3cc 100644 --- a/lib/bot/commands/kv.ex +++ b/lib/bot/commands/kv.ex @@ -1,17 +1,77 @@ defmodule Lanyard.DiscordBot.Commands.KV do + alias Lanyard.DiscordBot.CommandCache alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed + alias Lanyard.DiscordBot.InteractionHandler + + def definition do + %{ + name: "kv", + description: "List the keys in your Lanyard K/V store" + } + end def handle(_, payload) do - kv = - Lanyard.KV.Interface.get_all(payload["author"]["id"]) - |> Enum.map(fn {k, _v} -> k end) - |> Enum.join(", ") + DiscordApi.send_message(payload["channel_id"], kv_list_embed(payload["author"]["id"])) + end - kv = if String.length(kv) > 0, do: kv, else: "No keys" + def handle_interaction(interaction) do + user_id = InteractionHandler.user_id(interaction) - DiscordApi.send_message( - payload["channel_id"], - "*`#{Application.get_env(:lanyard, :command_prefix)}get ` to get a value*\n*`#{Application.get_env(:lanyard, :command_prefix)}del ` to delete an existing key*\n*`#{Application.get_env(:lanyard, :command_prefix)}set ` to set a key*\n\n**Keys:** ```#{kv}```" + DiscordApi.respond_to_interaction( + interaction["id"], + interaction["token"], + kv_list_embed(user_id) ) end + + defp kv_list_embed(user_id) do + keys = + Lanyard.KV.Interface.get_all(user_id) + |> Enum.map(fn {k, _v} -> k end) + + keys_value = + case keys do + [] -> "_No keys yet._" + list -> keys_field(list, user_id) + end + + Embed.info(%{ + title: ":file_folder: Your K/V Store", + description: + "#{CommandCache.mention("get")} `` — get a value\n#{CommandCache.mention("set")} ` ` — set a key\n#{CommandCache.mention("del")} `` — delete a key", + fields: [ + %{name: "Keys (#{length(keys)})", value: keys_value, inline: false} + ] + }) + end + + # Embed field values are capped at 1024 chars, users can have 512 keys of up to 255 chars each + @max_field_length 1_024 + # Room for the code fence and the "...and N more" footer + @reserved_length 120 + + @doc false + def keys_field(keys, user_id) do + {shown, _length} = + keys + |> Enum.map(&String.replace(&1, "`", "`\u200b")) + |> Enum.reduce_while({[], 0}, fn key, {acc, length} -> + new_length = length + String.length(key) + 2 + + if new_length > @max_field_length - @reserved_length, + do: {:halt, {acc, length}}, + else: {:cont, {[key | acc], new_length}} + end) + + content = "```#{shown |> Enum.reverse() |> Enum.join(", ")}```" + + case length(keys) - length(shown) do + 0 -> + content + + hidden -> + "#{content}…and #{hidden} more, see all at #{Application.get_env(:lanyard, :external_url)}/v1/users/#{user_id}" + end + end end diff --git a/lib/bot/commands/set.ex b/lib/bot/commands/set.ex index 1f74466..bb2eca4 100644 --- a/lib/bot/commands/set.ex +++ b/lib/bot/commands/set.ex @@ -1,41 +1,96 @@ defmodule Lanyard.DiscordBot.Commands.Set do + alias Lanyard.DiscordBot.CommandCache alias Lanyard.DiscordBot.DiscordApi + alias Lanyard.DiscordBot.Embed alias Lanyard.DiscordBot.Commands.ApiKey + alias Lanyard.DiscordBot.InteractionHandler - def handle([key | value_s], payload) when length(value_s) > 0 do - value = Enum.join(value_s, " ") + def definition do + %{ + name: "set", + description: "Set a key in your Lanyard K/V store", + options: [ + %{name: "key", description: "The key to set", type: 3, required: true}, + %{name: "value", description: "The value to store", type: 3, required: true} + ] + } + end + + def handle(args, payload) do + user_id = payload["author"]["id"] + channel_id = payload["channel_id"] - if ApiKey.contains_api_key?(payload["author"]["id"], [key, value]) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) + if ApiKey.contains_api_key?(user_id, args) do + DiscordApi.send_message(channel_id, ApiKey.leak_warning_embed()) else - case Lanyard.KV.Interface.set(payload["author"]["id"], key, value) do - {:error, reason} -> - DiscordApi.send_message( - payload["channel_id"], - ":x: #{reason}" - ) - - _ -> - DiscordApi.send_message( - payload["channel_id"], - ":white_check_mark: `#{key}` was set. View it with `#{Application.get_env(:lanyard, :command_prefix)}get #{key}` or go to #{Application.get_env(:lanyard, :external_url)}/v1/users/#{payload["author"]["id"]}" - ) - end + embed = + case args do + [key | value_parts] when value_parts != [] -> + case kv_set_embed(user_id, key, Enum.join(value_parts, " ")) do + {_kind, e} -> e + end + + _ -> + usage_embed() + end + + DiscordApi.send_message(channel_id, embed) end :ok end - def handle(args, payload) do - if ApiKey.contains_api_key?(payload["author"]["id"], args) do - ApiKey.generate_and_send_new(payload["channel_id"], payload["author"]["id"]) - else - DiscordApi.send_message( - payload["channel_id"], - "Invalid usage. Example `set` command usage:\n`#{Application.get_env(:lanyard, :command_prefix)}set `" + def handle_interaction(interaction) do + user_id = InteractionHandler.user_id(interaction) + key = InteractionHandler.option(interaction, "key") + value = InteractionHandler.option(interaction, "value") + interaction_id = interaction["id"] + interaction_token = interaction["token"] + + if ApiKey.contains_api_key?(user_id, [key, value]) do + DiscordApi.respond_to_interaction( + interaction_id, + interaction_token, + ApiKey.leak_warning_embed(), + ephemeral: true ) + else + case kv_set_embed(user_id, key, value) do + {:ok, embed} -> + DiscordApi.respond_to_interaction(interaction_id, interaction_token, embed) + + {:error, embed} -> + DiscordApi.respond_to_interaction(interaction_id, interaction_token, embed, ephemeral: true) + end end :ok end + + defp kv_set_embed(user_id, key, value) do + case Lanyard.KV.Interface.set(user_id, key, value) do + {:error, reason} -> + {:error, Embed.error(%{title: ":x: Could not set key", description: reason})} + + _ -> + external_url = Application.get_env(:lanyard, :external_url) + profile_url = "#{external_url}/v1/users/#{user_id}" + + {:ok, + Embed.success(%{ + title: ":white_check_mark: Key Set", + description: "View it with #{CommandCache.mention("get")} or open [your profile](#{profile_url}).", + fields: [ + %{name: "Key", value: "`#{key}`", inline: true} + ] + })} + end + end + + defp usage_embed do + Embed.error(%{ + title: ":x: Invalid usage", + description: "Usage: `#{Application.get_env(:lanyard, :command_prefix)}set `" + }) + end end diff --git a/lib/bot/discord_api.ex b/lib/bot/discord_api.ex index 29002a6..d61f5f9 100644 --- a/lib/bot/discord_api.ex +++ b/lib/bot/discord_api.ex @@ -46,6 +46,43 @@ defmodule Lanyard.DiscordBot.DiscordApi do |> Kernel.<=(@max_content_length) end + def respond_to_interaction(interaction_id, interaction_token, content, opts \\ []) + + def respond_to_interaction(interaction_id, interaction_token, content, opts) + when is_binary(content) do + Lanyard.Metrics.Collector.inc(:counter, :lanyard_discord_messages_sent) + + sanitized_content = sanitize_content(content) + + data = %{content: sanitized_content} + data = if opts[:ephemeral], do: Map.put(data, :flags, 64), else: data + + :post + |> Finch.build( + "#{@api_host}/interactions/#{interaction_id}/#{interaction_token}/callback", + [{"Content-Type", "application/json"}], + Jason.encode!(%{type: 4, data: data}) + ) + |> Finch.request(Lanyard.Finch) + |> track_response() + end + + def respond_to_interaction(interaction_id, interaction_token, %{} = embed, opts) do + Lanyard.Metrics.Collector.inc(:counter, :lanyard_discord_messages_sent) + + data = %{embeds: [embed]} + data = if opts[:ephemeral], do: Map.put(data, :flags, 64), else: data + + :post + |> Finch.build( + "#{@api_host}/interactions/#{interaction_id}/#{interaction_token}/callback", + [{"Content-Type", "application/json"}], + Jason.encode!(%{type: 4, data: data}) + ) + |> Finch.request(Lanyard.Finch) + |> track_response() + end + def create_dm(recipient) do {:ok, response} = :post diff --git a/lib/bot/embed.ex b/lib/bot/embed.ex new file mode 100644 index 0000000..01a181b --- /dev/null +++ b/lib/bot/embed.ex @@ -0,0 +1,11 @@ +defmodule Lanyard.DiscordBot.Embed do + @success 0x57F287 + @error 0xED4245 + @info 0x5865F2 + @warn 0xFEE75C + + def success(fields), do: Map.put(fields, :color, @success) + def error(fields), do: Map.put(fields, :color, @error) + def info(fields), do: Map.put(fields, :color, @info) + def warn(fields), do: Map.put(fields, :color, @warn) +end diff --git a/lib/bot/interaction_handler.ex b/lib/bot/interaction_handler.ex new file mode 100644 index 0000000..1cb3c23 --- /dev/null +++ b/lib/bot/interaction_handler.ex @@ -0,0 +1,49 @@ +defmodule Lanyard.DiscordBot.InteractionHandler do + @command_map %{ + "get" => Lanyard.DiscordBot.Commands.Get, + "set" => Lanyard.DiscordBot.Commands.Set, + "del" => Lanyard.DiscordBot.Commands.Del, + "kv" => Lanyard.DiscordBot.Commands.KV, + "about" => Lanyard.DiscordBot.Commands.About, + "help" => Lanyard.DiscordBot.Commands.Help, + "apikey" => Lanyard.DiscordBot.Commands.ApiKey + } + + @application_command 2 + + def handle_interaction(%{"type" => @application_command, "data" => %{"name" => name}} = interaction) do + case @command_map[name] do + nil -> :ok + module -> module.handle_interaction(interaction) + end + end + + def handle_interaction(_), do: :ok + + def user_id(interaction) do + cond do + user = interaction["user"] -> user["id"] + member = interaction["member"] -> member["user"]["id"] + true -> nil + end + end + + def option(interaction, name) do + case get_in(interaction, ["data", "options"]) do + nil -> + nil + + options -> + Enum.find_value(options, fn opt -> + if opt["name"] == name, do: opt["value"] + end) + end + end + + def command_definitions do + @command_map + |> Map.values() + |> Enum.uniq() + |> Enum.map(& &1.definition()) + end +end diff --git a/lib/gateway/client.ex b/lib/gateway/client.ex index 17d925f..df42c95 100644 --- a/lib/gateway/client.ex +++ b/lib/gateway/client.ex @@ -14,8 +14,7 @@ defmodule Lanyard.Gateway.Client do guild_members: 1 <<< 1, guild_presences: 1 <<< 8, guild_messages: 1 <<< 9, - direct_messages: 1 <<< 12, - message_content: 1 <<< 15 + direct_messages: 1 <<< 12 } @intents_mask Enum.reduce(@intents, 0, fn {_k, bit}, acc -> acc ||| bit end) @@ -255,6 +254,19 @@ defmodule Lanyard.Gateway.Client do Logger.info("Discord: Ready") + bot_user_id = payload.data["user"]["id"] + Application.put_env(:lanyard, :bot_user_id, bot_user_id) + + # READY also fires on full reconnects, commands only need registering once per boot + if Application.get_env(:lanyard, :is_idempotent) and + not :persistent_term.get(:lanyard_commands_registered, false) do + :persistent_term.put(:lanyard_commands_registered, true) + + Task.start(fn -> + Lanyard.DiscordBot.CommandRegistration.register(bot_user_id) + end) + end + {:ok, new_state} end @@ -268,6 +280,16 @@ defmodule Lanyard.Gateway.Client do {:ok, state} end + def handle_event({:interaction_create, payload}, state) do + if Application.get_env(:lanyard, :is_idempotent) do + Task.start(fn -> + Lanyard.DiscordBot.InteractionHandler.handle_interaction(payload.data) + end) + end + + {:ok, state} + end + def handle_event({:guild_create, payload}, state) do create_member_presences(payload) diff --git a/lib/gateway/utility.ex b/lib/gateway/utility.ex index bffb6c7..1bf3a32 100644 --- a/lib/gateway/utility.ex +++ b/lib/gateway/utility.ex @@ -19,6 +19,7 @@ defmodule Lanyard.Gateway.Utility do @dispatch_events %{ "READY" => :ready, "MESSAGE_CREATE" => :message_create, + "INTERACTION_CREATE" => :interaction_create, "GUILD_CREATE" => :guild_create, "PRESENCE_UPDATE" => :presence_update, "GUILD_MEMBER_ADD" => :guild_member_add, diff --git a/lib/lanyard.ex b/lib/lanyard.ex index 2723e5c..51bd787 100644 --- a/lib/lanyard.ex +++ b/lib/lanyard.ex @@ -6,6 +6,7 @@ defmodule Lanyard do :ets.new(:cached_presences, [:named_table, :set, :public]) :ets.new(:global_subscribers, [:named_table, :set, :public]) + Lanyard.DiscordBot.CommandCache.init() children = [ {Finch, name: Lanyard.Finch},