Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ it:
GOCHAT_URL=http://localhost:8080 GOCHAT_BOT_TOKEN=b_... go run ./examples/echobot -state echobot.pts
```

[docs/bots.md](docs/bots.md) is the guide to building bots: making one,
the three ways to get updates, commands and buttons, limits, and running
one in production. Its examples include a Python bot that long-polls with
nothing but the standard library, and a webhook bot.

### Client API for native apps

The [mobile apps](mobile) speak [the GoChat protocol](docs/protocol.md)
Expand Down Expand Up @@ -835,8 +840,8 @@ api/protobuf/ protobuf sources and generated protobuf + DRPC code
cmd/ cobra commands and embedded default configs
config/ configs for host runs and for the Docker stack
deployments/ Dockerfile and compose files
docs/ the GoChat protocol's specification
examples/ bots built on pkg/gochat
docs/ the GoChat protocol's specification and the bots guide
examples/ bots: over the socket, long polling and a webhook
internal/actors ask, pools and middleware on top of hollywood
internal/app wiring of the server and web processes
internal/authz casbin model and enforcer
Expand Down
486 changes: 486 additions & 0 deletions docs/bots.md

Large diffs are not rendered by default.

24 changes: 19 additions & 5 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,11 @@ or an `ApiError`:
| 16 | Unauthenticated |

Ids are the client's to choose, unique among its calls in flight. Results
come in any order. A socket has at most 32 calls in flight; more wait
their turn. Calls spend the session's request budget, as the HTTP API's do.
come in any order. A socket has at most 32 calls in flight, and up to 256
more wait their turn; past that the server closes it with 4009. A client
sends at most 10 frames a second, in bursts of 40: faster, and the server
closes the socket with 1008. Calls spend the session's request budget, as
the HTTP API's do.

People may make the unary calls the apps make over `/api/v1` (see
[`internal/web/api.go`](../internal/web/api.go)), plus `UpdatesService` and
Expand Down Expand Up @@ -229,6 +232,8 @@ message. A bot opts its own messages out with `no_link_preview`.

## Bots

[bots.md](bots.md) walks through building one, with examples.

A bot is an account a person owns. People make bots in the web's settings,
or with `BotService.CreateBot`, which answers the bot and its token once:

Expand Down Expand Up @@ -259,9 +264,14 @@ By default a bot is in **privacy mode** and receives, from its channels:
- `CallbackQuery` when someone presses a button of its messages;
- `ChannelJoined` and `ChannelLeft` as it is added to channels and removed.

It also receives `TeamJoined` and `TeamLeft` as it joins and leaves teams.
In privacy mode it reads only what it was sent: `GetMessage` of another
message answers code 5, and `ListMessages` and `ListThread` code 7.

With `sees_all` on (`UpdateBot`), a bot added to a channel from then on
receives every message there and may read its history. A channel keeps
what the bot had when it was added; add it again to change it.
what the bot had when it was added; add it again to change it. No one
leaves a team's `town-square`, so a bot keeps its mode there for good.

### What bots may call

Expand All @@ -271,7 +281,7 @@ what the bot had when it was added; add it again to change it.
| `UserService` | `GetUser`, `UpdateProfile` |
| `TeamService` | `ListTeams`, `GetTeam`, `ListTeamMembers` |
| `ChannelService` | `ListChannels`, `GetChannel`, `ListChannelMembers`, `JoinChannel`, `LeaveChannel`, `OpenDirectChannel` |
| `MessageService` | `PostMessage`, `EditMessage`, `DeleteMessage` (its own), `GetMessage`, `ListMessages`, `ListThread` (with `sees_all`), `SendTyping`, `React`, `RemoveLinkPreview` (its own) |
| `MessageService` | `PostMessage`, `EditMessage`, `DeleteMessage` (its own), `GetMessage`, `ListMessages` and `ListThread` (with `sees_all`), `SendTyping`, `React`, `RemoveLinkPreview` (its own) |
| `UpdatesService` | `GetState`, `GetDifference` |
| `BotService` | `SetCommands`, `GetCommands`, `AnswerCallback`, `SetWebhook`, `DeleteWebhook`, `GetWebhookInfo`, `ConfirmUpdates` |
| `FileService` | uploads and downloads, at `/api/v2/files` |
Expand Down Expand Up @@ -338,9 +348,13 @@ proto field names), and the answer is always JSON:

```json
{"ok": true, "result": { ... }}
{"ok": false, "error_code": 7, "description": "permission denied"}
{"ok": false, "error_code": 403, "description": "permission denied"}
```

`error_code` is the answer's HTTP status. Calls over the request budget are
refused before they reach the Bot API: 429 with `Retry-After` and an
`ApiError`, `{"code": 8, "message": "too many requests, slow down"}`.

| Method | Call |
| --- | --- |
| `getMe` | `AuthService/Me` |
Expand Down
143 changes: 143 additions & 0 deletions examples/dicebot/dicebot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""A GoChat bot over the HTTP Bot API, with long polling and nothing but
Python's standard library: /roll answers a die's roll under a Roll again
button, and /roll 20 rolls a twenty-sided one.

GOCHAT_URL=https://chat.example.com GOCHAT_BOT_TOKEN=b_... python3 examples/dicebot/dicebot.py

The server remembers the last update the bot confirmed, so after a restart
the bot gets what it missed. docs/bots.md walks through it.
"""

import json
import os
import random
import sys
import time
import urllib.error
import urllib.request

URL = os.environ.get("GOCHAT_URL", "").rstrip("/")
TOKEN = os.environ.get("GOCHAT_BOT_TOKEN", "")
# How long getUpdates waits for an update, at most 50 seconds.
POLL = 50


class APIError(Exception):
def __init__(self, status, description, retry_after=0):
super().__init__(f"{description} ({status})")
self.status = status
self.retry_after = retry_after


def call(method, body=None, timeout=10):
"""Makes one call of the HTTP Bot API and answers its result."""
req = urllib.request.Request(
f"{URL}/api/v2/bot/{method}",
data=json.dumps(body or {}).encode(),
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
return json.load(res).get("result", {})
except urllib.error.HTTPError as e:
try:
answer = json.load(e)
except ValueError:
answer = {}
# Calls over the request budget answer 429 with an ApiError and
# Retry-After.
description = answer.get("description") or answer.get("message") or e.reason
raise APIError(e.code, description, int(e.headers.get("Retry-After") or 0)) from None


def command(text, bot):
"""Reads "/roll 20", or "/roll@dice_bot 20" addressed to this bot."""
if not text.startswith("/"):
return None
word, _, args = text[1:].partition(" ")
name, at, to = word.partition("@")
if not name or (at and to.lower() != bot.lower()):
return None
return name.lower(), args.strip()


def roll(sides):
"""A roll and its button, which carries the die in its data."""
text = f"🎲 d{sides}: {random.randint(1, sides)}"
markup = {"rows": [{"buttons": [{"text": "Roll again", "callback_data": f"roll:{sides}"}]}]}
return text, markup


def handle(update, me):
m = update.get("message_posted", {}).get("message")
if m and m.get("author", {}).get("id") != me["id"]:
cmd = command(m.get("content", ""), me["username"])
if cmd and cmd[0] == "roll":
sides = int(cmd[1]) if cmd[1].isdigit() and 2 <= int(cmd[1]) <= 1000 else 6
text, markup = roll(sides)
call("sendMessage", {
"channel_id": m["channel_id"], "root_id": m.get("root_id", ""),
"content": text, "markup": markup,
})
return
q = update.get("callback_query")
if q:
kind, _, sides = q.get("data", "").partition(":")
if kind != "roll" or not sides.isdigit():
call("answerCallback", {"query_id": q["id"]})
return
text, markup = roll(int(sides))
msg = q["message"]
# Editing replaces the buttons: send them again to keep them.
call("editMessage", {
"channel_id": msg["channel_id"], "message_id": msg["id"], "root_id": msg.get("root_id", ""),
"content": text, "markup": markup,
})
call("answerCallback", {"query_id": q["id"], "text": "Rolled again."})


def main():
if not URL or not TOKEN:
sys.exit("set GOCHAT_URL and GOCHAT_BOT_TOKEN")
me = call("getMe")["user"]
print(f"signed in as @{me['username']}", flush=True)
call("setCommands", {"commands": [{"name": "roll", "description": "Roll a die: /roll or /roll 20"}]})

# 0 starts after the last update the server knows the bot handled.
offset, delay = 0, 1
while True:
try:
res = call("getUpdates", {"offset": offset, "timeout": POLL}, timeout=POLL + 10)
except APIError as e:
if e.status == 401:
sys.exit("the token is not valid: was it reset?")
# 409: another copy of the bot is polling, or a webhook is set.
print(f"getUpdates: {e}", file=sys.stderr, flush=True)
time.sleep(e.retry_after or delay)
delay = min(delay * 2, 60)
continue
except OSError as e:
print(f"getUpdates: {e}", file=sys.stderr, flush=True)
time.sleep(delay)
delay = min(delay * 2, 60)
continue
delay = 1
for u in res.get("updates", []):
# One update the bot cannot handle must not hold back the rest.
try:
handle(u, me)
except Exception as e:
print(f"update {u['pts']}: {e!r}", file=sys.stderr, flush=True)
# Numbers are strings in JSON: int64 in protobuf's mapping.
offset = int(u["pts"]) + 1
if res.get("too_long"):
print("updates were lost while the bot was away", file=sys.stderr, flush=True)
offset = int(res["pts"]) + 1


if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
8 changes: 7 additions & 1 deletion examples/echobot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,13 @@ func save(path string, pts int64) {
if path == "" {
return
}
if err := os.WriteFile(path, []byte(strconv.FormatInt(pts, 10)), 0o600); err != nil {
// Renamed over the old, the file never holds half a number.
tmp := path + ".tmp"
if err := os.WriteFile(tmp, []byte(strconv.FormatInt(pts, 10)), 0o600); err != nil {
log.Printf("saving the state: %v", err)
return
}
if err := os.Rename(tmp, path); err != nil {
log.Printf("saving the state: %v", err)
}
}
Loading
Loading