Streaming donations: Go
This bot receives donations through the live stream and prints those allowed by the moderation rules. It uses one file and the centrifuge-go library. Delivery time depends on payment processing and the source conditions.
What you need
Section titled “What you need”- Go 1.26 or newer.
- A secret key with
donations:readin theDONATTY_TOKENvariable: how to save it.
1. Save the code
Section titled “1. Save the code”Create an empty folder and save the code in it as main.go.
package main
import ( "encoding/json" "fmt" "log" "math/rand" "net/http" "net/url" "os" "regexp" "strconv" "strings" "sync" "time"
"github.com/centrifugal/centrifuge-go")
const api = "https://api.donatty.com"
type donation struct { ID string `json:"id"` DonorName string `json:"donorName"` Message string `json:"message"` Amount struct { Value string `json:"value"` Currency string `json:"currency"` } `json:"amount"` Moderation struct { Status string `json:"status"` } `json:"moderation"`}
type event struct { ID string `json:"id"` Type string `json:"type"` Time time.Time `json:"time"` Data donation `json:"data"`}
var ( token = os.Getenv("DONATTY_TOKEN") // untrusted input: control characters → space control = regexp.MustCompile(`[\x00-\x1f\x7f-\x{9f}\x{2028}\x{2029}\x{202a}-\x{202e}\x{2066}-\x{2069}]`) mu sync.Mutex events = map[string]bool{} // ids of events already handled: one event can arrive twice shown = map[string]bool{} // ids of donations already shown waiting = map[string]donation{} // id → donation moderation has not decided on last = time.Now() // time of the last event; before the first one, the launch moment)
func show(d donation) { shown[d.ID] = true fmt.Printf("%s — %s %s: %s\n", control.ReplaceAllString(d.DonorName, " "), d.Amount.Value, d.Amount.Currency, control.ReplaceAllString(d.Message, " "))}
func accept(d donation, replay bool) { switch status := d.Moderation.Status; { case status == "PENDING": waiting[d.ID] = d // shown after donation.moderated with the PASSED status case (status == "NONE" || status == "PASSED") && (replay || !shown[d.ID]): show(d) }}
func handle(raw []byte) { var e event if err := json.Unmarshal(raw, &e); err != nil { return } mu.Lock() defer mu.Unlock() if events[e.ID] { return } events[e.ID] = true if e.Time.After(last) { last = e.Time } switch e.Type { case "donation.created": accept(e.Data, false) case "donation.replayed": // you pressed «Повторить на стриме» (Repeat on stream) accept(e.Data, true) case "donation.moderated": d, ok := waiting[e.Data.ID] delete(waiting, e.Data.ID) if ok && e.Data.Moderation.Status == "PASSED" { show(d) } }}
// The channel history did not cover the gap: read the donations with regular requests.func catchUp() { mu.Lock() since := last.Add(-time.Minute).UTC().Format(time.RFC3339Nano) mu.Unlock() // so that all programs do not arrive in the same second after an outage time.Sleep(time.Second + time.Duration(rand.Int63n(int64(9*time.Second)))) client := &http.Client{Timeout: 10 * time.Second} var items []donation for cursor := ""; ; { address := api + "/v1/donations?limit=100&since=" + since if cursor != "" { address += "&cursor=" + url.QueryEscape(cursor) } req, _ := http.NewRequest(http.MethodGet, address, nil) req.Header.Set("Authorization", "Bearer "+token) var page struct { Items []donation `json:"items"` NextCursor string `json:"nextCursor"` } res, err := client.Do(req) if err == nil && res.StatusCode == http.StatusOK { err = json.NewDecoder(res.Body).Decode(&page) } if res != nil { res.Body.Close() } if res != nil && (res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden) { log.Fatalf("%d: the key does not work", res.StatusCode) } if err != nil || res.StatusCode != http.StatusOK { pause := 5 if res != nil { if after, bad := strconv.Atoi(res.Header.Get("Retry-After")); bad == nil { pause = after } } time.Sleep(time.Duration(pause) * time.Second) continue } items = append(items, page.Items...) if cursor = page.NextCursor; cursor == "" { break } } mu.Lock() defer mu.Unlock() for i := len(items) - 1; i >= 0; i-- { // oldest first accept(items[i], false) }}
func main() { if token == "" { log.Fatal("Set DONATTY_TOKEN: a secret key with the donations:read scope") } client := centrifuge.NewJsonClient( strings.Replace(api, "http", "ws", 1)+"/v1/realtime/websocket", // https → wss centrifuge.Config{ Header: http.Header{"Authorization": {"Bearer " + token}}, Data: []byte(`{"channels":["donations"]}`), // donations only; without Data all the key's channels arrive }) done := make(chan struct{}) client.OnConnecting(func(e centrifuge.ConnectingEvent) { log.Printf("connecting: %d %s", e.Code, e.Reason) }) client.OnDisconnected(func(e centrifuge.DisconnectedEvent) { // final refusal: the library does not reconnect any more log.Printf("disconnected: %d %s", e.Code, e.Reason) close(done) }) client.OnSubscribed(func(e centrifuge.ServerSubscribedEvent) { if e.WasRecovering && !e.Recovered { go catchUp() } }) client.OnPublication(func(e centrifuge.ServerPublicationEvent) { handle(e.Data) }) if err := client.Connect(); err != nil { log.Fatal(err) } <-done os.Exit(1)}2. Run it
Section titled “2. Run it”In the same terminal window where you saved the key, go to the folder with the file and run:
go mod init donatty-botgo get github.com/centrifugal/centrifuge-go@v0.13.0go run .The commands are the same on macOS, Linux and Windows.
What you’ll see
Section titled “What you’ll see”The bot shows donations that arrive after it starts, so at first the terminal has only the connection line. Every donation you can show on stream appears as a line:
Alex — 500.00 RUB: Thanks for the stream!To test the bot, press «Тест на стриме» (Test on stream) in your dashboard: the test donation arrives as an event.
How it works
Section titled “How it works”- The key is in the
Config.Headerfield: the library sends it as a connection header, without including it in the URL. - The bot asks for the donations channel only: the
Datafield holds{"channels":["donations"]}. - The bot prints
NONEandPASSEDdonations right away. It remembers aPENDINGdonation and prints it afterdonation.moderatedwith thePASSEDstatus. It never printsBLOCKEDor an unknown status: that is the Moderation and display rule. donation.replayedarrives when you press «Повторить на стриме» (Repeat on stream): the donation is printed once more.- The bot skips an event that arrived twice by its
id(repeats and order). - After a drop the library reconnects by itself, and the server sends what was missed from the history. If the history did not cover the gap (
Recoveredisfalse), the bot waits a random time from 1 to 10 seconds and reads the donations with the Donations method: the steps are in the Stream and catch-up example. - If the server rejects the connection permanently, the bot prints the code and stops: what the code means.
- The bot prints an amount as the
valuestring with its currency code, without converting it to a number: money.
Example limitations
Section titled “Example limitations”- After a restart, the bot reads new donations only. It does not keep a record of previously displayed donations.
- The bot does not show a donation that was waiting for moderation at the moment of the restart.
- To replace the key, set the new one in
DONATTY_TOKENand restart the bot.
What to change
Section titled “What to change”- Replace
fmt.Printfwith sending to chat or an overlay. Clean the name and message first. - To receive goals too, remove
Dataand handle thegoal.updatedevent: the key needs thegoals:readscope. - This program does not handle Twitch and YouTube events. See Stream channels for channels, scopes and event types. To catch up on platform events, follow the Stream and catch-up example.