This repository has been archived by the owner on Aug 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conversation.go
105 lines (83 loc) · 2.05 KB
/
conversation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package telegram
import (
"context"
"github.com/jfk9w-go/flu/syncf"
"github.com/pkg/errors"
)
var (
ErrUnexpectedAnswer = errors.New("unexpected answer")
)
type Question chan *Message
type Sender interface {
Send(ctx context.Context, chatID ChatID, sendable Sendable, options *SendOptions) (*Message, error)
}
type conversationAware struct {
sender Sender
questions map[ID]Question
mu syncf.RWMutex
}
func conversations(sender Sender) *conversationAware {
return &conversationAware{
sender: sender,
questions: make(map[ID]Question),
}
}
func (a *conversationAware) Ask(ctx context.Context, chatID ChatID, sendable Sendable, options *SendOptions) (*Message, error) {
if options == nil {
options = new(SendOptions)
}
options.ReplyMarkup = ForceReply{ForceReply: true, Selective: true}
m, err := a.sender.Send(ctx, chatID, sendable, options)
if err != nil {
return nil, errors.Wrap(err, "send question")
}
question, err := a.addQuestion(ctx, m.ID)
if err != nil {
return nil, errors.Wrap(err, "add question")
}
defer a.removeQuestion(ctx, m.ID)
select {
case <-ctx.Done():
return nil, ctx.Err()
case answer := <-question:
return answer, nil
}
}
func (a *conversationAware) Answer(ctx context.Context, message *Message) error {
ctx, cancel := a.mu.RLock(ctx)
if ctx.Err() != nil {
return ctx.Err()
}
defer cancel()
question, ok := a.questions[message.ReplyToMessage.ID]
if !ok {
return ErrUnexpectedAnswer
}
select {
case <-ctx.Done():
return ctx.Err()
case question <- message:
return nil
}
}
func (a *conversationAware) addQuestion(ctx context.Context, id ID) (Question, error) {
question := make(Question)
ctx, cancel := a.mu.Lock(ctx)
if ctx.Err() != nil {
return nil, ctx.Err()
}
defer cancel()
if a.questions == nil {
a.questions = make(map[ID]Question)
}
a.questions[id] = question
return question, nil
}
func (a *conversationAware) removeQuestion(ctx context.Context, id ID) {
ctx, cancel := a.mu.Lock(ctx)
if ctx.Err() != nil {
return
}
defer cancel()
delete(a.questions, id)
}