Skip to content

Commit

Permalink
Added the Wait API into Handler and example
Browse files Browse the repository at this point in the history
  • Loading branch information
diamondburned committed Jan 23, 2020
1 parent d38cf15 commit c6155d6
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
35 changes: 35 additions & 0 deletions _example/advanced_bot/context.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package main

import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"

"github.com/diamondburned/arikawa/bot"
"github.com/diamondburned/arikawa/bot/extras/arguments"
Expand Down Expand Up @@ -45,6 +47,39 @@ func (bot *Bot) Say(m *gateway.MessageCreateEvent, f *arguments.Flag) error {
return err
}

// Repeat tells the bot to wait for the user's response, then repeat what they
// said.
func (bot *Bot) Repeat(m *gateway.MessageCreateEvent) error {
_, err := bot.Ctx.SendMessage(m.ChannelID,
"What do you want me to say?", nil)
if err != nil {
return err
}

ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

v := bot.Ctx.WaitFor(ctx, func(v interface{}) bool {
// Incoming event is a message create event:
mg, ok := v.(*gateway.MessageCreateEvent)
if !ok {
return false
}

// Message is from the same author:
return mg.Author.ID == m.Author.ID
})

if v == nil {
return errors.New("Timed out waiting for response.")
}

ev := v.(*gateway.MessageCreateEvent)

_, err = bot.Ctx.SendMessage(m.ChannelID, ev.Content, nil)
return err
}

func (bot *Bot) Embed(
m *gateway.MessageCreateEvent, f *arguments.Flag) error {

Expand Down
20 changes: 20 additions & 0 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
package handler

import (
"context"
"fmt"
"reflect"
"sync"
Expand Down Expand Up @@ -67,6 +68,25 @@ func (h *Handler) Call(ev interface{}) {
}
}

func (h *Handler) WaitFor(ctx context.Context, fn func(interface{}) bool) interface{} {
var result = make(chan interface{})

cancel := h.AddHandler(func(v interface{}) {
if fn(v) {
result <- v
}
})

defer cancel()

select {
case r := <-result:
return r
case <-ctx.Done():
return nil
}
}

func (h *Handler) AddHandler(handler interface{}) (rm func()) {
rm, err := h.addHandler(handler)
if err != nil {
Expand Down

0 comments on commit c6155d6

Please sign in to comment.