Created
June 10, 2018 06:09
-
-
Save trojanh/0f8491e8930333a5b447282201686de6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Bot do | |
use Application | |
use GenServer | |
alias MyApp.{Repo, BotSetting} | |
import Logger | |
def start(_, state), do: {:ok, state} | |
def start_link do | |
GenServer.start_link(__MODULE__, [:ok], name: __MODULE__) | |
end | |
def init(state) do | |
send(self(), :work) | |
{:ok, state} | |
end | |
@doc """ | |
invoked by Spervisor worker on start up, to start SlackBot for all the teams in DB | |
""" | |
def handle_info(:work, state) do | |
Logger.info("============================") | |
Logger.info("Starting bots for following Teams:.....................") | |
Logger.info("============================") | |
try do | |
process_ids = start_all_bots() | |
Logger.info("============================") | |
if process_ids[:error] do | |
Logger.error("#{inspect(process_ids)}") | |
else | |
Logger.info("#{inspect(process_ids)}") | |
end | |
Logger.info("============================") | |
debug("Done starting bots for all the teams...") | |
rescue | |
e -> | |
Logger.error("#{inspect(e)}") | |
Sentry.capture_exception( | |
e, | |
stacktrace: System.stacktrace(), | |
extra: %{message: "Bot crashed"} | |
) | |
end | |
{:stop, :normal, state} | |
end | |
@doc """ | |
it starts SlackBot for all the teams in DB and invalids the invalid teams i.e while starting the bots if the slack | |
responds with error for that particular team credential we know that we cannot run our bot for that team so we delete | |
that team from our DB as it is invalid stale credential. | |
""" | |
def start_all_bots() do | |
BotSetting | |
|> Repo.all() | |
|> Enum.map(fn bot -> | |
%{team_name: bot.team_name, token: bot.bot_access_token} | |
processes = Slack.Bot.start_link(MyApp.SlackBot, [], bot.bot_access_token) | |
case processes do | |
{:ok, _} -> | |
Logger.info("#{bot.team_name}, ") | |
{:error, "Could not connect to the Slack RTM API"} -> | |
Logger.error( | |
"You are offline. Could not start bot for #{bot.team_name}'. \n'Could not connect to the Slack RTM API'" | |
) | |
{:error, message} -> | |
Logger.error("#{bot.team_name} is invalid. Deleting this team now.") | |
Logger.error( | |
"'Bot Could not start Bot for :#{inspect(message)}'. Deleting this team now." | |
) | |
Repo.delete!(bot) | |
end | |
processes | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment