Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions lib/bot/command_cache.ex
Original file line number Diff line number Diff line change
@@ -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 -> "</#{name}:#{id}>"
end
end
end
81 changes: 67 additions & 14 deletions lib/bot/command_handler.ex
Original file line number Diff line number Diff line change
@@ -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

_ ->
Expand All @@ -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
Comment thread
dustinrouillard marked this conversation as resolved.
Resolved

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
71 changes: 71 additions & 0 deletions lib/bot/command_registration.ex
Original file line number Diff line number Diff line change
@@ -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
43 changes: 43 additions & 0 deletions lib/bot/commands/about.ex
Original file line number Diff line number Diff line change
@@ -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
81 changes: 55 additions & 26 deletions lib/bot/commands/api_key.ex
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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
Loading
Loading