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
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ specifies it.
that only the owner sees, once. The owner adds it to a team, and channel
members add it to channels. Unless it is set to see every message, a bot
gets commands (`/echo hi`), mentions of it, replies in its threads and its
direct messages.
direct messages. A bot may write to a person in its teams first, in a
direct conversation, for reminders and alerts.
- A bot's commands show in the composer as people type `/`, and its messages
may carry buttons: a press reaches the bot as a `CallbackQuery`, and its
answer shows to the person who pressed.
Expand Down Expand Up @@ -720,7 +721,9 @@ Secrets that should come from the environment:
`services.updates` sets how long the update logs keep updates (`retention`,
a week by default), and `services.bots` how many bots a person may own and
how webhooks are delivered. Webhooks go only to public addresses unless
`services.bots.allow_private_webhooks` is set, for development.
`services.bots.allow_private_webhooks` is set, for development. A bot opens
up to `services.directory.max_bot_conversations_per_hour` new direct
conversations an hour, 30 by default.

`services.previews` sets link previews: `enabled` (on by default), the
fetch limits, and `allow_hosts` and `deny_hosts`, host names that cover
Expand Down Expand Up @@ -812,10 +815,11 @@ The end-to-end suite in [test/e2e](test/e2e) drives a running stack through the
web gateway: invites, real-time delivery, typing, attachments, voice messages
and their channel setting, voice channels (with Pion peers that talk through
the voice server), the client API the apps use, bots (commands, buttons,
catching up after a restart, the HTTP Bot API and token resets through
[pkg/gochat](pkg/gochat)), link previews (none for a private address; with
`GOCHAT_E2E_PREVIEW_URL` set to a public page, its card and picture),
private channel isolation, CSRF, TOTP with recovery codes, session
writing to a person first, catching up after a restart, the HTTP Bot API
and token resets through [pkg/gochat](pkg/gochat)), link previews (none for
a private address; with `GOCHAT_E2E_PREVIEW_URL` set to a public page, its
card and picture), private channel isolation, CSRF, TOTP with recovery
codes, session
revocation, deactivation and storage quotas. It needs an existing admin account and team, or with
`GOCHAT_E2E_BOOTSTRAP=1` and the server's token in `GOCHAT_E2E_SETUP_TOKEN`
creates them on a fresh server:
Expand Down
1 change: 1 addition & 0 deletions cmd/serve/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ services:
invite_ttl: 168h
max_invites: 100
max_teams_per_day: 5
max_bot_conversations_per_hour: 30
channels:
idle_timeout: 10m
op_timeout: 10s
Expand Down
27 changes: 25 additions & 2 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,8 @@ A bot connects as a person does, with its token in the hello, and receives
**everything in its account's sequence**: a bot keeps one number and asks
for nothing else. Its owner adds it to teams they may invite people to;
then people add it to channels as they add anyone (a private channel's
admins only), and anyone in its teams may write to it directly.
admins only), and anyone in its teams may write to it directly. A bot may
also [write to a person first](#writing-to-a-person-first).

### What a bot receives

Expand All @@ -269,14 +270,35 @@ what the bot had when it was added; add it again to change it.
| `AuthService` | `Me` |
| `UserService` | `GetUser`, `UpdateProfile` |
| `TeamService` | `ListTeams`, `GetTeam`, `ListTeamMembers` |
| `ChannelService` | `ListChannels`, `GetChannel`, `ListChannelMembers`, `JoinChannel`, `LeaveChannel` |
| `ChannelService` | `ListChannels`, `GetChannel`, `ListChannelMembers`, `JoinChannel`, `LeaveChannel`, `OpenDirectChannel` |
| `MessageService` | `PostMessage`, `EditMessage`, `DeleteMessage` (its own), `GetMessage`, `ListMessages`, `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` |

Any other call answers code 12.

### Writing to a person first

`ChannelService.OpenDirectChannel` with `team_id` and `user_id` opens the
bot's direct conversation with a person, for reminders, alerts and
notices; the bot then posts in it as in any channel. The person is an
active member of the team, as the bot is, or the call answers code 5,
which is also the answer for a deactivated or deleted account. A person
who blocked the bot refuses it with code 7, in the words of a refused
post. A bot opens no group conversation, and none with another bot
(code 3).

A bot opens up to 30 new conversations an hour, as the server's
`services.directory.max_bot_conversations_per_hour` sets; past that the
call answers code 8. Opening a conversation that exists already, one the
bot opened or the person did, costs nothing and returns it.

The person sees the conversation as any other direct one, with the bot's
Bot badge. They may mute it, block the bot, which stops its posts there,
or delete it for themselves. The bot receives every message of it, as of
all its direct conversations.

### Commands

`SetCommands` lists the commands a bot offers, up to 100, each a name of
Expand Down Expand Up @@ -333,6 +355,7 @@ proto field names), and the answer is always JSON:
| `setCommands` / `getCommands` | `BotService/SetCommands` / `GetCommands` |
| `listTeams` | `TeamService/ListTeams` |
| `listChannels` / `getChannel` | `ChannelService/ListChannels` / `GetChannel` |
| `openDirect` | `ChannelService/OpenDirectChannel` |
| `setWebhook` / `deleteWebhook` / `getWebhookInfo` | `BotService/...` |

Any call of the [table above](#what-bots-may-call) may also be made by its
Expand Down
40 changes: 38 additions & 2 deletions examples/echobot/main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Command echobot is a small GoChat bot: /echo repeats what follows it under
// a Thanks button, and /ping answers pong.
// a Thanks button, /ping answers pong, and /remindme 10m stand up writes
// "stand up" to whoever asked in a direct message ten minutes later.
//
// GOCHAT_URL=https://chat.example.com GOCHAT_BOT_TOKEN=b_... go run ./examples/echobot
//
Expand All @@ -17,6 +18,7 @@ import (
"strconv"
"strings"
"syscall"
"time"

pb "github.com/ssenerg/gochat/api/protobuf/gen/gochat/v1"
"github.com/ssenerg/gochat/pkg/gochat"
Expand Down Expand Up @@ -47,6 +49,7 @@ func run(ctx context.Context, url, token, state string) error {
err = c.Call(ctx, "gochat.v1.BotService/SetCommands", &pb.SetCommandsRequest{Commands: []*pb.BotCommand{
{Name: "echo", Description: "Repeat what follows"},
{Name: "ping", Description: "Answer pong"},
{Name: "remindme", Description: "Remind you in a direct message: /remindme 10m stand up"},
}}, &pb.SetCommandsResponse{})
if err != nil {
return err
Expand Down Expand Up @@ -75,7 +78,8 @@ func handle(ctx context.Context, c *gochat.Client, me *pb.User, u gochat.Update)
log.Print("updates were lost while the bot was away")
return nil
}
if m := u.Event.GetMessagePosted().GetMessage(); m != nil && m.GetAuthor().GetId() != me.GetId() {
posted := u.Event.GetMessagePosted()
if m := posted.GetMessage(); m != nil && m.GetAuthor().GetId() != me.GetId() {
name, args, ok := gochat.Command(m.Content, me.GetUsername())
if !ok {
return nil
Expand All @@ -92,6 +96,8 @@ func handle(ctx context.Context, c *gochat.Client, me *pb.User, u gochat.Update)
}}}}
case "ping":
reply.Content = "pong"
case "remindme":
reply.Content = remind(ctx, c, posted.GetTeamId(), m.GetAuthor().GetId(), args)
default:
return nil
}
Expand All @@ -104,6 +110,36 @@ func handle(ctx context.Context, c *gochat.Client, me *pb.User, u gochat.Update)
return nil
}

// maxRemind bounds how far off a reminder is: the bot keeps reminders in
// memory, and a restart forgets them.
const maxRemind = 24 * time.Hour

// remind writes text to userID in their direct conversation in teamID once
// the duration args start with is over, and answers what it set.
func remind(ctx context.Context, c *gochat.Client, teamID, userID, args string) string {
when, text, _ := strings.Cut(args, " ")
d, err := time.ParseDuration(when)
text = strings.TrimSpace(text)
if err != nil || d <= 0 || d > maxRemind || text == "" {
return "Say when, up to 24h, and what: /remindme 10m stand up."
}
time.AfterFunc(d, func() {
if ctx.Err() != nil {
return
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
dm, err := c.OpenDirect(ctx, teamID, userID)
if err == nil {
err = c.Call(ctx, "gochat.v1.MessageService/PostMessage", &pb.PostMessageRequest{ChannelId: dm.GetId(), Content: text}, &pb.PostMessageResponse{})
}
if err != nil {
log.Printf("sending a reminder: %v", err)
}
})
return "I'll remind you in a direct message in " + d.String() + "."
}

func load(path string) int64 {
if path == "" {
return 0
Expand Down
17 changes: 17 additions & 0 deletions internal/repos/scylla/bots_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/ssenerg/gochat/internal/core/ids"
"github.com/ssenerg/gochat/internal/core/models"
"github.com/ssenerg/gochat/internal/core/secure"
ierrors "github.com/ssenerg/gochat/internal/errors"
)

func TestBotsLive(t *testing.T) {
Expand Down Expand Up @@ -88,3 +89,19 @@ func TestBotsLive(t *testing.T) {
t.Fatal("the buttons stayed")
}
}

func TestDirectKeyHolderLive(t *testing.T) {
r := liveRepository(t)
ctx := context.Background()
key := ConversationKey(ids.New(), ids.New().String()+":"+ids.New().String())
if _, err := r.DirectKeyHolder(ctx, key); !ierrors.Is(err, ierrors.CodeNotFound) {
t.Fatalf("an unclaimed key: %v", err)
}
id := ids.New()
if got, err := r.ClaimDirectKey(ctx, key, id); err != nil || got != id {
t.Fatalf("claimed %v, %v", got, err)
}
if got, err := r.DirectKeyHolder(ctx, key); err != nil || got != id {
t.Fatalf("the key's holder %v, %v", got, err)
}
}
9 changes: 9 additions & 0 deletions internal/repos/scylla/channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,15 @@ func (r *Repository) ClaimDirectKey(ctx context.Context, key string, id gocql.UU
return holder, nil
}

// DirectKeyHolder returns the conversation holding key, or NotFound.
func (r *Repository) DirectKeyHolder(ctx context.Context, key string) (gocql.UUID, error) {
var id gocql.UUID
if err := r.query(ctx, "SELECT channel_id FROM direct_channels WHERE pair = ?", key).Scan(&id); err != nil {
return gocql.UUID{}, wrap(err)
}
return id, nil
}

// ConversationKey is the key of a team's conversation of the people a
// conversation's name lists; those from before teams owned them have the
// people alone.
Expand Down
5 changes: 3 additions & 2 deletions internal/server/drpc/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ var streaming = map[string]bool{
}

// botCalls are the calls open to bots: reading and writing in the
// channels they are in, about themselves, and their updates. Any other is
// refused, whatever its own checks.
// channels they are in, opening direct conversations, about themselves,
// and their updates. Any other is refused, whatever its own checks.
var botCalls = map[string]bool{
"/gochat.v1.AuthService/Me": true,
"/gochat.v1.UserService/GetUser": true,
Expand All @@ -50,6 +50,7 @@ var botCalls = map[string]bool{
"/gochat.v1.ChannelService/ListChannelMembers": true,
"/gochat.v1.ChannelService/JoinChannel": true,
"/gochat.v1.ChannelService/LeaveChannel": true,
"/gochat.v1.ChannelService/OpenDirectChannel": true,
"/gochat.v1.MessageService/PostMessage": true,
"/gochat.v1.MessageService/EditMessage": true,
"/gochat.v1.MessageService/DeleteMessage": true,
Expand Down
7 changes: 5 additions & 2 deletions internal/server/drpc/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,16 @@ func TestBotsMakeOnlyTheirCalls(t *testing.T) {
ctx := drpcmetadata.AddPairs(context.Background(), map[string]string{MetaGatewayKey: key, MetaSession: token})
return guard.HandleRPC(&metaStream{ctx: ctx}, rpc)
}
for _, rpc := range []string{"/gochat.v1.MessageService/PostMessage", "/gochat.v1.UpdatesService/GetDifference", "/gochat.v1.BotService/AnswerCallback"} {
for _, rpc := range []string{
"/gochat.v1.MessageService/PostMessage", "/gochat.v1.UpdatesService/GetDifference", "/gochat.v1.BotService/AnswerCallback",
"/gochat.v1.ChannelService/OpenDirectChannel",
} {
if err := call("bot", rpc); err != nil || !reached {
t.Errorf("a bot's %s: %v", rpc, err)
}
}
for _, rpc := range []string{
"/gochat.v1.MessageService/SearchMessages", "/gochat.v1.ChannelService/OpenDirectChannel", "/gochat.v1.TeamService/CreateInvite",
"/gochat.v1.MessageService/SearchMessages", "/gochat.v1.ChannelService/OpenGroupChannel", "/gochat.v1.TeamService/CreateInvite",
"/gochat.v1.AuthService/ChangePassword", "/gochat.v1.UpdatesService/GetChannelDifference", "/gochat.v1.BotService/CreateBot",
"/gochat.v1.MessageService/PressButton", "/gochat.v1.SafetyService/BlockUser", "/gochat.v1.SafetyService/Report",
"/gochat.v1.SafetyService/ListReports", "/gochat.v1.SafetyService/CountReports",
Expand Down
69 changes: 69 additions & 0 deletions internal/services/channels/bots_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,3 +295,72 @@ func TestPushLeavesBotsOut(t *testing.T) {
t.Fatalf("handed %+v", p)
}
}

func TestABotWritesInTheConversationItOpened(t *testing.T) {
person, bot := ids.New(), ids.New()
// opened is the conversation, its members as the directory writes
// those of one a bot opens.
opened := func(list blockList) *channel {
a, _ := blockChannel(t, models.ChannelDirect, list, person, bot)
members := []*models.ChannelMember{
{ChannelID: a.id, UserID: bot, TeamID: a.ch.TeamID, Bot: true, BotSeesAll: true},
{ChannelID: a.id, UserID: person, TeamID: a.ch.TeamID},
}
if err := a.loadBots(context.Background(), members); err != nil {
t.Fatal(err)
}
a.snapshot()
return a
}
a := opened(nil)
seen := &pushes{}
a.Updates = a.Engine.SpawnFunc(func(c *actor.Context) {
if p, ok := c.Message().(updates.Push); ok {
seen.mu.Lock()
seen.got = append(seen.got, p)
seen.mu.Unlock()
}
}, "updates")
pushed := make(chan push.Posted, 4)
a.Push = a.Engine.SpawnFunc(func(c *actor.Context) {
if p, ok := c.Message().(push.Posted); ok {
pushed <- p
}
}, "push")
post := func(p *models.Principal, text string) error {
_, err := a.post(Post{Target: Target{P: p, ChannelID: a.id}, Content: text})
return err
}
asBot := &models.Principal{UserID: bot, Role: models.SystemRoleUser, Bot: true}

// The bot's message is pushed to the person as any other.
if err := post(asBot, "stand up"); err != nil {
t.Fatal(err)
}
select {
case p := <-pushed:
if _, in := p.Members[person.String()]; !in || !p.Conversation {
t.Fatalf("pushed %+v", p)
}
if _, in := p.Members[bot.String()]; in {
t.Fatal("the bot was pushed its own message")
}
case <-time.After(5 * time.Second):
t.Fatal("the bot's message was not pushed")
}
// It gets every message of it, and reads its history.
if err := post(&models.Principal{UserID: person, Role: models.SystemRoleUser}, "done"); err != nil {
t.Fatal(err)
}
if got := posts(t, seen.take(), bot); len(got) != 1 || got[0] != "done" {
t.Fatalf("the bot got %q", got)
}
if err := a.readsHistory(asBot); err != nil {
t.Fatalf("the bot reads its conversation: %v", err)
}
// Once the person blocks it, its posts stop.
a = opened(blockList{person: {bot}})
if err := post(asBot, "again"); ierrors.As(err).Message != ErrNotTaking.Message {
t.Fatalf("a bot the person blocked posted: %v", err)
}
}
6 changes: 6 additions & 0 deletions internal/services/directory/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type Config struct {
// MaxTeamsPerDay caps the teams one person creates a day; system admins
// create any number.
MaxTeamsPerDay int `mapstructure:"max_teams_per_day"`
// MaxBotConversationsPerHour caps the new direct conversations one bot
// opens an hour.
MaxBotConversationsPerHour int `mapstructure:"max_bot_conversations_per_hour"`
}

var _ config.Config = (*Config)(nil)
Expand All @@ -36,5 +39,8 @@ func (c *Config) Validate() error {
if c.MaxTeamsPerDay < 1 {
return errors.New("max_teams_per_day must be at least 1")
}
if c.MaxBotConversationsPerHour < 1 {
return errors.New("max_bot_conversations_per_hour must be at least 1")
}
return nil
}
Loading
Loading