rockneurotiko/ex_gram

How to run custom code at bot startup?

aus70 opened this issue · 5 comments

aus70 commented

I'd like to run set_my_command, set_my_description, set_my_name and some other initialization code at bot startup. What's the best way to do it?
Thanks!

Currently there are not an easy way of dealing with this, but I'll add an optional init/1 callback on the bot so this inital setup is easy

aus70 commented

that'd be great, thanks!

The problem I found with init/1 is that it's running from the Supervisor init, and that means the Dispatcher is still not running. Even more, it's a mess if we want to use Phoenix.PubSub for receiving information inside of the Dispatcher because it only could be done by performing a request to the Dispatcher, not when the dispatcher is up and running.

I suggest init/1 callback for Bot be moved to Dispatcher when the connection is up and working, or that we could define any hooks/triggers/callbacks for when the connection is up and running (handle_up/1) and previously to that (init/1 but inside of the Dispatcher).

@manuel-rubio What's the use case for needing the Dispatcher started in the init/1 callback?

If you are trying to link a bot with Phoenix.PubSub in order to receive broadcast messages, I don't think subscribing from the dispatcher is a good thing. I would definitely go with my own Supervisor, with the Bot and a GenServer to handle the subscription, then the GenServer can send messages to the bot manually (Either with BotModule.message(<origin>, <message>) or with GenServer.call(<:bot_name>, <message>)

I did it in that way, but it's weird to have a GenServer only for sending messages to another process.

defmodule MyProject.Bot.Proxy do
  use GenServer

  def init([]) do
    Phoenix.PubSub.subscribe(MyProject.PubSub, "topic1")
    {:ok, nil}
  end

  def handle_info(info, nil) do
    send(MyProject.Bot.name(), info)
    {:ok, nil}
  end
end

It's not providing value at all and it's needed only because I cannot run startup code inside of the Dispatcher process.

My problem with that is I put in the init/1 the PubSub subscriptions and suddenly we have messages from the supervisor saying it receives an unexpected message, it sounded not very intuitive for me that init/1 was running in the supervisor process and handle/2 is running in the Dispatcher process, based on GenServer I was expecting both running on the same process.