From 9ee386a0cb9e1b80f47d0c68b8cce3ddcc2be073 Mon Sep 17 00:00:00 2001 From: rodley82 Date: Mon, 26 Sep 2022 00:08:26 -0300 Subject: [PATCH] Agregado servicio systemd y otras mejoras para deployar de forma mas sencilla en otro equipo --- .gitignore | 4 +++- Makefile | 16 ++++++++++++++++ cmd/bot.go | 7 ------- config/app.go | 24 +++++++++++++++--------- .env.example => env.template | 0 internal/slack/handler.go | 23 +++-------------------- main.go | 9 +++++++++ scripts/check_server_ping.sh | 9 +++++++++ scripts/poweroffserver.sh | 3 +++ scripts/wakeup_server.sh | 2 ++ systemd/slackbot.service | 19 +++++++++++++++++++ 11 files changed, 79 insertions(+), 37 deletions(-) create mode 100644 Makefile delete mode 100644 cmd/bot.go rename .env.example => env.template (100%) create mode 100644 main.go create mode 100644 scripts/check_server_ping.sh create mode 100644 scripts/poweroffserver.sh create mode 100644 scripts/wakeup_server.sh create mode 100644 systemd/slackbot.service diff --git a/.gitignore b/.gitignore index d6711a1..05d2c84 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ bot -.env \ No newline at end of file +.env +tmp +slack-bot \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5a39781 --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +all: linux +linux: + go build . +install: + cp slack-bot /usr/local/bin/ + cp env.template /etc/slackbot.env +systemd-install: + cp systemd/slackbot.service /lib/systemd/system/ + systemctl daemon-reload +systemd-uninstall: + rm -Rf /lib/systemd/system/slackbot.service + systemctl daemon-reload +uninstall: + rm -Rf /usr/local/bin/slack-bot +clean: + rm -Rf slack-bot diff --git a/cmd/bot.go b/cmd/bot.go deleted file mode 100644 index 72ddfb1..0000000 --- a/cmd/bot.go +++ /dev/null @@ -1,7 +0,0 @@ -package main - -import "rodleyserverbot/slack-bot/internal/slack" - -func main() { - slack.Start() -} diff --git a/config/app.go b/config/app.go index 2eb2d53..7fcfa38 100644 --- a/config/app.go +++ b/config/app.go @@ -2,6 +2,7 @@ package config import ( "fmt" + "log" "os" "encoding/csv" "strings" @@ -25,14 +26,20 @@ var Config ConfigEntries // var Actions []ActionScript func init() { - fmt.Println("Initializing App Config settings") - // TODO: Add if defined app will read from .env - godotenv.Load(".env") + log.Println("Initializing App Config settings") + envFile := os.Getenv("SLACKBOT_ENV_FILE") + if envFile != "" { + log.Printf("Reading env vars from [%s]", envFile) + } else { + envFile = ".env" + } + + godotenv.Load(envFile) Config.SlackAuthToken = os.Getenv("SLACK_AUTH_TOKEN") Config.SlackAppToken = os.Getenv("SLACK_APP_TOKEN") actionsLoaded := initalizeDefinedActions() - fmt.Println("Finished loading config. Actions found:", actionsLoaded) - fmt.Println("Actions:", Config.Actions) + log.Println("Finished loading config. Actions found:", actionsLoaded) + log.Println("Actions:", Config.Actions) } // Each action is defined on an env variable named `BOT_ACTION_1` `BOT_ACTION_2` @@ -41,19 +48,18 @@ func init() { // For example: // `poweron,Encender Server,/some/script.sh` func initalizeDefinedActions() int { - fmt.Println("initalizeDefinedActions") + log.Println("initalizeDefinedActions") var count = 1 var value string var exists bool for { envVarName := fmt.Sprintf("BOT_ACTION_%d", count) - fmt.Println("Checking for env var:", envVarName) + log.Println("Checking for env var:", envVarName) value, exists = os.LookupEnv(envVarName) if !exists { - fmt.Println("Not fonud, giving up") break } - fmt.Println("Action found:", value) + log.Println("Action found:", value) action := actionStringToActionScript(value) // Actions = append(Actions, action) Config.Actions = append(Config.Actions, action) diff --git a/.env.example b/env.template similarity index 100% rename from .env.example rename to env.template diff --git a/internal/slack/handler.go b/internal/slack/handler.go index 6474eb6..744603f 100644 --- a/internal/slack/handler.go +++ b/internal/slack/handler.go @@ -49,8 +49,6 @@ func Start() { switch event.Type { // handle EventInteractive events case socketmode.EventTypeInteractive: - //fmt.Println("Recivimos un Interactive!", event) - callback, ok := event.Data.(slack.InteractionCallback) if !ok { @@ -60,9 +58,7 @@ func Start() { socketClient.Ack(*event.Request) switch callback.Type { case slack.InteractionTypeInteractionMessage: - //fmt.Println("type:", callback.Type, "callBackId:", callback.CallbackID, "aactions[0]", *callback.ActionCallback.AttachmentActions[0]) action := *callback.ActionCallback.AttachmentActions[0] - //fmt.Println("Value:", action.Value) var output string var err error @@ -73,18 +69,15 @@ func Start() { replyToAction(callback.Channel.ID, finalMessage, client) } case slack.InteractionTypeMessageAction: - //fmt.Println("is a message action?") case slack.InteractionTypeBlockActions: // See https://api.slack.com/apis/connections/socket-implement#button - //fmt.Println("button clicked!") case slack.InteractionTypeShortcut: case slack.InteractionTypeViewSubmission: // See https://api.slack.com/apis/connections/socket-implement#modal case slack.InteractionTypeDialogSubmission: default: - //fmt.Println("Don't know what type it is") } // handle EventAPI events case socketmode.EventTypeEventsAPI: @@ -104,7 +97,6 @@ func Start() { // log.Fatal(err) } default: - //fmt.Println("Event received no matching TYPE:", event.Type, "event:", event) } } @@ -121,7 +113,6 @@ func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) case slackevents.CallbackEvent: innerEvent := event.InnerEvent - // fmt.Println("We received an event!", innerEvent) // Yet Another Type switch on the actual Data to see if its an AppMentionEvent switch ev := innerEvent.Data.(type) { case *slackevents.AppMentionEvent: @@ -132,7 +123,6 @@ func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) //log.Println("MessageEvent!", ev) handleAppMessagedEvent(ev, client) default: - //fmt.Println("Not handled EventMessage!:", ev) } default: return errors.New("unsupported event type") @@ -141,7 +131,6 @@ func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) } func executeAction(actionName string) (string, error) { - //fmt.Println("executeAction actionName:", actionName, "actions:", config.Config.Actions) var output_str string var err error for _, action := range config.Config.Actions { @@ -172,28 +161,26 @@ func executeScript(scriptPath string) (string, error) { // The error returned by cmd.Output() will be OS specific based on what // happens when a process is killed. if ctx.Err() == context.DeadlineExceeded { - fmt.Println("Command timed out") + log.Println("Command timed out") return "", context.DeadlineExceeded } // If there's no context error, we know the command completed (or errored). if err != nil { - fmt.Println("Non-zero exit code:", err) + log.Println("Non-zero exit code:", err) } output_str := string(out) - // fmt.Println("Output:", output_str) return output_str, nil } func replyToAction(channelName string, message string, client *slack.Client) error { - //fmt.Println("replyToAction channel:", channelName, "Message:", message) attachment := slack.Attachment{} attachment.Text = message attachment.Color = "#4af030" _, _, err := client.PostMessage(channelName, slack.MsgOptionAttachments(attachment)) if err != nil { - //fmt.Println("failed to post message:", err) + log.Println("failed to post message:", err) return err } return nil @@ -213,7 +200,6 @@ func getAttachmentButtons() []slack.AttachmentAction{ } func handleAppMessagedEvent(event *slackevents.MessageEvent, client *slack.Client) error { - //fmt.Println("handleAppMessagedEvent event:", event, "BotID:", event.BotID) if event.BotID != "" { // We're not interested in messages from ourselves or other bots return nil @@ -239,8 +225,6 @@ func handleAppMessagedEvent(event *slackevents.MessageEvent, client *slack.Clien // handleAppMentionEvent is used to take care of the AppMentionEvent when the bot is mentioned func handleAppMentionEvent(event *slackevents.AppMentionEvent, client *slack.Client) error { - // fmt.Println("handleAppMentionEvent event:", event) - var err error // Create the attachment and assigned based on the message attachment := slack.Attachment{} @@ -251,7 +235,6 @@ func handleAppMentionEvent(event *slackevents.AppMentionEvent, client *slack.Cli attachment.Pretext = fmt.Sprintf("Como te puedo ayudar?") attachment.Color = "#3d3d3d" actions := getAttachmentButtons() - //fmt.Println(actions) attachment.Actions = actions // Send the message to the channel diff --git a/main.go b/main.go new file mode 100644 index 0000000..0538e17 --- /dev/null +++ b/main.go @@ -0,0 +1,9 @@ +package main + +import ( + "rodleyserverbot/slack-bot/internal/slack" +) + +func main() { + slack.Start() +} diff --git a/scripts/check_server_ping.sh b/scripts/check_server_ping.sh new file mode 100644 index 0000000..d6d247d --- /dev/null +++ b/scripts/check_server_ping.sh @@ -0,0 +1,9 @@ +#! /bin/bash +ping -W 1 -c 1 server_ip > /dev/null + +if [ $? -gt 0 ] +then + echo "El servidor no responde" +elif + echo "Servidor Encendido" +fi diff --git a/scripts/poweroffserver.sh b/scripts/poweroffserver.sh new file mode 100644 index 0000000..1fca94d --- /dev/null +++ b/scripts/poweroffserver.sh @@ -0,0 +1,3 @@ +#! /bin/bash +ssh user@server "nohup sudo poweroff &" & +echo "Apagando..." \ No newline at end of file diff --git a/scripts/wakeup_server.sh b/scripts/wakeup_server.sh new file mode 100644 index 0000000..3d627f8 --- /dev/null +++ b/scripts/wakeup_server.sh @@ -0,0 +1,2 @@ +#! /bin/bash +wakeonlan cc:cc:cc:cc:cc:cc diff --git a/systemd/slackbot.service b/systemd/slackbot.service new file mode 100644 index 0000000..9255d60 --- /dev/null +++ b/systemd/slackbot.service @@ -0,0 +1,19 @@ +[Unit] +Description=slackbot +After=network.target + +[Service] +# User=someuser +# ExecStart=/home/someuser/slack-bot + +Environment="SLACKBOT_ENV_FILE=/etc/slackbot.env" +ExecStart=/usr/local/bin/slack-bot +ExecReload=/bin/kill -HUP $MAINPID +KillMode=process +IgnoreSIGPIPE=true +Restart=always +RestartSec=3 +Type=simple + +[Install] +WantedBy=multi-user.target