Skip to content

Commit

Permalink
Merge pull request #512 from Th3-M4jor/dont-crash-when-discord-leaks-…
Browse files Browse the repository at this point in the history
…a-struct

don't crash when discord leaks a struct
  • Loading branch information
jchristgit authored Jun 16, 2023
2 parents 7c5ddc6 + 62f1627 commit fc0a4ba
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/nostrum/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,26 @@ defmodule Nostrum.Util do
"""
@spec safe_atom_map(map) :: map
def safe_atom_map(term) do
cond do
is_map(term) ->
case term do
# to handle the rare occasion that discord leaks a `:__struct__` key
# rather than outright crashing, we'll just log a warning and continue
%{__struct__: struct_name} ->
Logger.warning(
"Discord's gateway leaked a struct with name #{inspect(struct_name)}, please report this to the library maintainer"
)

term = Map.from_struct(term)
for {key, value} <- term, into: %{}, do: {maybe_to_atom(key), safe_atom_map(value)}

is_list(term) ->
# if we have a regular map
%{} ->
for {key, value} <- term, into: %{}, do: {maybe_to_atom(key), safe_atom_map(value)}

# if we have a non-empty list
[_ | _] ->
Enum.map(term, fn item -> safe_atom_map(item) end)

true ->
_ ->
term
end
end
Expand Down

0 comments on commit fc0a4ba

Please # to comment.