# Streaming donations: Go

This bot receives donations through the [live stream](https://developers.donatty.com/en/realtime.md) and prints those allowed by the [moderation rules](https://developers.donatty.com/en/structures/donation.md#moderation-and-display). It uses one file and the [centrifuge-go](https://github.com/centrifugal/centrifuge-go) library. Delivery time depends on payment processing and the [source conditions](https://developers.donatty.com/en/conditions/sources.md).

## What you need

- Go 1.26 or newer.
- A secret key with `donations:read` in the `DONATTY_TOKEN` variable: [how to save it](https://developers.donatty.com/en/tokens.md#save-the-key-in-a-variable).

## 1. Save the code

Create an empty folder and save the code in it as `main.go`.

> **Name and message are untrusted input.**
> Treat donor names and messages as untrusted input. Sanitize them before sending them to chat, an overlay or HTML. This example replaces control characters with a space to prevent messages from controlling the terminal.

```go title="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

In the same terminal window where you saved the key, go to the folder with the file and run:

```sh
go mod init donatty-bot
go get github.com/centrifugal/centrifuge-go@v0.13.0
go run .
```

The commands are the same on macOS, Linux and Windows.

## 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:

```text
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

- The key is in the `Config.Header` field: the library sends it as a connection header, without including it in the URL.
- The bot asks for the donations channel only: the `Data` field holds `{"channels":["donations"]}`.
- The bot prints `NONE` and `PASSED` donations right away. It remembers a `PENDING` donation and prints it after `donation.moderated` with the `PASSED` status. It never prints `BLOCKED` or an unknown status: that is the [Moderation and display](https://developers.donatty.com/en/structures/donation.md#moderation-and-display) rule.
- `donation.replayed` arrives 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](https://developers.donatty.com/en/realtime/recovery.md#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 (`Recovered` is `false`), the bot waits a random time from 1 to 10 seconds and reads the donations with the [Donations](https://developers.donatty.com/en/reference/donations.md) method: the steps are in the [Stream and catch-up](https://developers.donatty.com/en/examples/stream-recovery.md) example.
- If the server rejects the connection permanently, the bot prints the code and stops: [what the code means](https://developers.donatty.com/en/realtime/close-codes.md).
- The bot prints an amount as the `value` string with its currency code, without converting it to a number: [money](https://developers.donatty.com/en/data.md#formats).

## 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_TOKEN` and restart the bot.

## What to change

- Replace `fmt.Printf` with sending to chat or an overlay. Clean the name and message first.
- To receive goals too, remove `Data` and handle the `goal.updated` event: the key needs the `goals:read` scope.
- This program does not handle Twitch and YouTube events. See [Stream channels](https://developers.donatty.com/en/realtime/channels.md) for channels, scopes and event types. To catch up on platform events, follow the [Stream and catch-up](https://developers.donatty.com/en/examples/stream-recovery.md) example.
