Skip to content

Instantly share code, notes, and snippets.

@blakef
Created December 29, 2016 15:30
Show Gist options
  • Save blakef/5f8713dbc83339c644a95ab3629452bf to your computer and use it in GitHub Desktop.
Save blakef/5f8713dbc83339c644a95ab3629452bf to your computer and use it in GitHub Desktop.
// Monitors a path for file changes and reports them to Slack
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/nlopes/slack"
)
type configuration struct {
refresh int
path string
api_key string
}
type changes map[string]time.Time
var config configuration
func init() {
flag.IntVar(&config.refresh, "seconds", 5, "Poll for changes")
flag.StringVar(&config.path, "path", ".", "Path to watch for changes")
config.api_key = os.Getenv("SLACK_API_KEY")
}
func monitor(folder string, current changes) []string {
files, err := ioutil.ReadDir(folder)
update := make([]string, 0, len(files))
if err != nil {
log.Fatal(err)
}
for _, file := range files {
name, time := file.Name(), file.ModTime()
if date, ok := current[name]; !ok || time.After(date) {
update = append(update, name)
current[name] = file.ModTime()
}
}
return update
}
func main() {
flag.Parse()
refresh := time.Duration(config.refresh) * time.Second
status := make(changes)
api := slack.New(config.api_key)
slack_config := slack.PostMessageParameters{Username: "lootbot", IconEmoji: "blowfish"}
fmt.Printf("Monitoring: %s every %ds", config.path, config.refresh)
monitor(config.path, status)
for {
time.Sleep(refresh)
if update := monitor(config.path, status); len(update) > 0 {
fmt.Printf("\nupdate = %+v\n", update)
api.PostMessage("general", fmt.Sprintf("GoT Loot: %v", update), slack_config)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment