ref: dba5389efd8ee1de58f18f85c04c50676161eef7 kart/bot/main.go -rw-r--r-- 1.5 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main

import (
	"flag"
	"fmt"
	"github.com/minio/minio-go/v6"
	"github.com/robfig/cron/v3"
	"os/exec"
	"strings"
	"time"
)

func dbFromS3() {
	client, err := minio.New(Config.S3.Endpoint, Config.S3.Id, Config.S3.Secret, true)
	if err != nil {
		fmt.Printf("Error: %s\n", err.Error())
		return
	}

	for {

		doneCh := make(chan struct{})
		defer close(doneCh)

		for object := range client.ListObjects(Config.S3.Bucket, Config.S3.GoodPrefix, false, doneCh) {
			var entry Entry

			key := strings.ReplaceAll(object.Key, Config.S3.GoodPrefix, "")
			DB.Find(&entry, "name = ?", key)
			if entry.ID == 0 {
				entry.Name = key
				DB.Create(&entry)
				fmt.Printf("Adding %s to the database!\n", key)
			}
		}

		time.Sleep(5 * time.Second)
	}

}

func sendBot() {
	var entries []Entry

	DB.Limit(1).Order("RANDOM()").Where("sent = 0").Find(&entries)
	for _, people := range Config.Bot.People {
	retry:
		out, err := exec.Command("sudo", "-u", "keybase", "keybase", "chat", "send", people, Config.Bot.CDN+"/"+entries[0].Name).Output()
		if err == nil {
			DB.Model(&entries[0]).Update("sent", true)
		} else {
			fmt.Printf("Error: %s, '%s'\n", err.Error(), out)
			goto retry
		}
	}
}

func main() {
	filename := flag.String("config", "/etc/kart-worker.conf", "The yaml configuration file")
	flag.Parse()
	ReadConfig(*filename)

	go dbFromS3()

	c := cron.New()
	for _, cron := range Config.Bot.Crons {
		fmt.Printf("Adding cron with %s\n", cron)
		c.AddFunc(cron, sendBot)
	}
	c.Start()

	for {
		time.Sleep(5 * time.Second)
	}
}