Skip to content

Post from a short-lived job

You have a job that runs, says one thing in a channel, and exits: a release announcement, a nightly summary. Build a client with NeedPosting, mint a scope that allows the channel, and call Post without calling Connect. From comms v0.33.0, and the comms-discord release after v0.31.5 that carries spec 0041, that is one REST request and no gateway session. On comms-discord v0.31.5 Post still returns ErrNotConnected until you connect.

Before you start

  • A bot token, ideally for a bot of its own. Posting needs no gateway, but it still spends the token's REST rate limits, and a job that later calls Connect by mistake would identify beside whatever else uses the token. A separate bot application keeps the job's traffic and its mistakes away from a running bot, and is what colophon does for its release announcements (colophon spec 0031).
  • The channel's id, which goes on the scope's allowlist.

1. Build the client and mint a scope

The Discord provider registers itself from a blank import:

import _ "gitlab.com/phpboyscout/go/comms-discord"
c, err := comms.NewClient(ctx, "discord", comms.ClientConfig{
    Token: os.Getenv("DISCORD_TOKEN"),
    Needs: []comms.Need{comms.NeedPosting},
})
if err != nil {
    return err
}

defer c.Close()

channel := comms.ID(os.Getenv("DISCORD_CHANNEL"))

p, err := c.Provider(ctx, comms.ID(os.Getenv("DISCORD_GUILD")),
    comms.WithAllowedChannels(channel),
)
if err != nil {
    return err
}

Neither call reaches the network. Use WithAllowedChannels, not WithPublicChannels: a public scope can tell a channel is public only from a live connection, so before Connect it refuses every post with ErrNotConnected.

2. Post, and don't connect

poster, ok := comms.AsPoster(p)
if !ok {
    return errors.New("this provider cannot post")
}

ref, err := poster.Post(ctx, channel, comms.PostSpec{Content: "v1.4.0 is out"})
if err != nil {
    return err
}

Post refuses a bad message or a channel outside the allowlist before any request, as it does on a connected scope. From Discord, a 403 is ErrForbidden, usually because the bot lacks Send Messages in that channel.

Keep ref if you may want to correct the post later. Author.Replace and Delete take it, but they still need a connected scope.

Check that the job never connects

Nothing in the contract stops a scope connecting; a job that never calls Connect never does. If your job's correctness depends on that, which it does when it shares a token with a running bot, assert it in your own test: build the job against a fake Reader whose Connect fails the test.