...
1 package status
2
3 import (
4 "context"
5 "fmt"
6 "log"
7 "os"
8 "time"
9
10 dContext "go.formulabun.club/discord/context"
11 translator "go.formulabun.club/translator/client"
12
13 "github.com/bwmarrin/discordgo"
14 )
15
16 var trClient *translator.APIClient
17 var logger = log.New(os.Stdout, "/status | ", log.LstdFlags)
18
19 func Start(c *dContext.DiscordContext) {
20 ticker := time.NewTicker(5 * time.Second)
21
22 config := translator.NewConfiguration()
23 trClient = translator.NewAPIClient(config)
24
25 setIdleStatus(c.S)
26 go setupTimer(ticker, c.S)
27
28 for _ = range c.Cancel {
29 }
30 ticker.Stop()
31 }
32
33 func setupTimer(tick *time.Ticker, s *discordgo.Session) {
34 for _ = range tick.C {
35 updateStatus(s)
36 }
37 }
38
39 func makeNoStatusData() discordgo.UpdateStatusData {
40 i := 0
41 status := discordgo.Activity{
42 Name: "until you'll help me",
43 Type: discordgo.ActivityTypeWatching,
44 CreatedAt: time.Now(),
45 }
46
47 return discordgo.UpdateStatusData{
48 &i,
49 []*discordgo.Activity{&status},
50 false,
51 string(discordgo.StatusDoNotDisturb),
52 }
53 }
54
55 func makeStatusData(info *translator.ServerInfo) discordgo.UpdateStatusData {
56 i := 0
57 var statusText string
58 playerCount := int(info.GetNumberOfPlayer())
59 switch playerCount {
60 case 0:
61 statusText = "an empty map"
62 case 1:
63 statusText = fmt.Sprintf("%d player race", playerCount)
64 default:
65 statusText = fmt.Sprintf("%d players race", playerCount)
66 }
67
68 status := discordgo.Activity{
69 Name: statusText,
70 Type: discordgo.ActivityTypeWatching,
71 CreatedAt: time.Now(),
72 }
73
74 return discordgo.UpdateStatusData{
75 &i,
76 []*discordgo.Activity{&status},
77 false,
78 string(discordgo.StatusOnline),
79 }
80 }
81
82 func setIdleStatus(s *discordgo.Session) {
83 i := 0
84 updateStatus := discordgo.UpdateStatusData{
85 &i,
86 []*discordgo.Activity{},
87 true,
88 string(discordgo.StatusIdle),
89 }
90 s.UpdateStatusComplex(updateStatus)
91 }
92
93 func updateStatus(s *discordgo.Session) {
94 resp, _, err := trClient.DefaultApi.ServerinfoGet(context.Background()).Execute()
95 var updateStatus discordgo.UpdateStatusData
96 if err != nil {
97 updateStatus = makeNoStatusData()
98 } else {
99 updateStatus = makeStatusData(resp)
100 }
101 err = s.UpdateStatusComplex(updateStatus)
102 if err != nil {
103 logger.Print(fmt.Sprintf("Could not update status: %s", err))
104 return
105 }
106 }
107
View as plain text