Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reply directly to a user's message using Phoenix channels?

I've built the basic chat application showed in the Phoenix Channels docs. Now I want a way to handle certain messages by replying only to the sender.

Eg, if the user types /who, send them (and only them) a list of connected users.

How can I do this?

like image 576
Nathan Long Avatar asked Dec 07 '22 22:12

Nathan Long


1 Answers

In Phoenix

The matching handle_in function head needs to return a response formatted like this: {:reply, {status :: atom, response :: map}, Socket.t}.

For example:

  def handle_in("new_msg", %{"body" => "/who"}, socket) do
    user_list = UserList.get # or whatever
    {:reply, {:ok, %{kind: "private", from: "server", body: user_list}}, socket}
  end

(If you set handle_in to return garbage, like an empty string, the resulting error explains the acceptable return value formats, which is where I learned this.)

In Javascript

When you channel.push, just chain on a .receive for the reply.

    channel.push("new_msg", {body: $chatInput.val()}).receive(
      "ok", (reply) => console.log("got reply", reply)
     )

(Thanks to Manuel Kallenbach for this answer.)

like image 136
Nathan Long Avatar answered Feb 27 '23 15:02

Nathan Long