Browse Source

Agregado servicio systemd y otras mejoras para deployar de forma mas sencilla en otro equipo

pull/1/head
rodley82 3 years ago
parent
commit
9ee386a0cb
  1. 4
      .gitignore
  2. 16
      Makefile
  3. 7
      cmd/bot.go
  4. 24
      config/app.go
  5. 0
      env.template
  6. 23
      internal/slack/handler.go
  7. 9
      main.go
  8. 9
      scripts/check_server_ping.sh
  9. 3
      scripts/poweroffserver.sh
  10. 2
      scripts/wakeup_server.sh
  11. 19
      systemd/slackbot.service

4
.gitignore

@ -1,2 +1,4 @@
bot
.env
.env
tmp
slack-bot

16
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

7
cmd/bot.go

@ -1,7 +0,0 @@
package main
import "rodleyserverbot/slack-bot/internal/slack"
func main() {
slack.Start()
}

24
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)

0
.env.example → env.template

23
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

9
main.go

@ -0,0 +1,9 @@
package main
import (
"rodleyserverbot/slack-bot/internal/slack"
)
func main() {
slack.Start()
}

9
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

3
scripts/poweroffserver.sh

@ -0,0 +1,3 @@
#! /bin/bash
ssh user@server "nohup sudo poweroff &" &
echo "Apagando..."

2
scripts/wakeup_server.sh

@ -0,0 +1,2 @@
#! /bin/bash
wakeonlan cc:cc:cc:cc:cc:cc

19
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
Loading…
Cancel
Save