This repository was archived by the owner on Mar 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservercount.go
83 lines (70 loc) · 1.85 KB
/
servercount.go
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
77
78
79
80
81
82
83
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/andersfylling/disgord"
"github.com/google/go-github/v32/github"
"github.com/meooow25/cfspy/bot"
"golang.org/x/oauth2"
)
var (
githubToken = os.Getenv("GITHUB_TOKEN")
gistID = os.Getenv("GIST_ID")
)
const (
gistFilename = "server-count.json"
gistJSONFmt = `{"serverCount": %v}`
)
const refreshInterval = 15 * time.Minute
func updateServerCount(s disgord.Session, gc *github.Client) {
ctx := context.Background()
gist, _, err := gc.Gists.Get(ctx, gistID)
if err != nil {
s.Logger().Error("Error getting gist: ", err)
return
}
curContent := *gist.Files[gistFilename].Content
guilds, err := s.CurrentUser().GetGuilds(nil)
if err != nil {
s.Logger().Error("Error fetching guilds: ", err)
return
}
newContent := fmt.Sprintf(gistJSONFmt, len(guilds))
if newContent == curContent {
return
}
s.Logger().Info("Updating server count: ", newContent)
_, _, err = gc.Gists.Edit(ctx, gistID, &github.Gist{
Files: map[github.GistFilename]github.GistFile{
gistFilename: {Content: &newContent},
},
})
if err != nil {
s.Logger().Error("Error updating gist: ", err)
}
}
func startServerCountTask(s disgord.Session) {
go func() {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: githubToken})
tc := oauth2.NewClient(context.Background(), ts)
gc := github.NewClient(tc)
for {
updateServerCount(s, gc)
time.Sleep(refreshInterval)
}
}()
}
// Installs the server count feature, which updates a Github Gist with the bot's server count at
// regular intervals.
func installServerCountFeature(b *bot.Bot) {
b.Client.Logger().Info("Setting up server count feature")
if githubToken == "" {
panic("GITHUB_TOKEN env var missing")
}
if gistID == "" {
panic("GIST_ID env var missing")
}
b.Client.Gateway().BotReady(func() { startServerCountTask(b.Client) })
}