How to send messages using WebSockex

So, I’m trying to build a Discord library in Elixir and I have to connect to the Discord gateway for that. The connection part works, but when I try to send a message as shown here: Discord Developer Portal

I get no response back - it also says timeout when I do it manually in iex

defmodule Chemie.Discord.Gateway do
  @moduledoc false

  use WebSockex

  import Chemie.Constants, only: [gateway_url: 0, bot_token: 0]
  require Logger

  @url gateway_url()

  def start_link(state \\ []) do
    WebSockex.start_link(@url, __MODULE__, state, name: __MODULE__)
  end

  def handle_frame({_type, message}, state) do
    json = Jason.decode!(message)

    IO.inspect(json)

    Map.new(~w[d op s t]a, &{&1, json[to_string(&1)]})
    |> handle_discord_message()

    {:ok, state}
  end

  defp handle_discord_message(%{op: 10}) do
    data =
      Jason.encode!(%{
        "op" => 2,
        "d" => %{
          "token" => bot_token(),
          "intents" => 513,
          "properties" => %{
            "$os" => "linux",
            "$browser" => "chemie",
            "$device" => "chemie"
          }
        }
      })

    # This is where I send the message
    WebSockex.send_frame(__MODULE__, {:text, data})
  end

  defp handle_discord_message(data) do
    IO.inspect(data)
  end
end

Am I sending the message in a wrong way?

Thanks!

Hi!

Did you ever manage to solve this?

If not:
It seems you are using MODULE instead of a pid when calling

WebSockex.send_frame(MODULE, {:text, data})

Using the pid of the Chemie.Discord.Gateway process should do the trick!

I saw now that you correctly name your WebSockex with __MODULE__ as well… so that should’nt be a problem.

Looks correct on the Elixir side to me!

If not, you can also try using gun. Which seems a little more stable.
Good luck!

1 Like