-
Notifications
You must be signed in to change notification settings - Fork 0
/
complex_messages.go
214 lines (203 loc) · 6.55 KB
/
complex_messages.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"fortio.org/log"
"github.com/bwmarrin/discordgo"
"grol.io/grol/eval"
"grol.io/grol/extensions"
"grol.io/grol/object"
"grol.io/grol/repl"
)
func errorReply(s *discordgo.Session, i *discordgo.InteractionCreate, userID, msg string) {
log.S(log.Warning, msg, log.Any("author", userID))
resp := &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "🔴 I'm sorry Dave. I'm afraid I can't do that.",
Flags: discordgo.MessageFlagsEphemeral,
},
}
err := s.InteractionRespond(i.Interaction, resp)
if err != nil {
log.Errf("Error responding to interaction: %v", err)
}
}
func processApplicationCommandInteraction(s *discordgo.Session, i *discordgo.InteractionCreate) {
log.S(log.Info, "Processing application command interaction", log.Any("interaction", i))
if i.ApplicationCommandData().Options != nil {
slashCmdInteraction(s, i)
return
}
var userID string
if i.User == nil {
userID = i.Member.User.ID
} else {
userID = i.User.ID
}
resolved := i.ApplicationCommandData().Resolved
if resolved == nil {
errorReply(s, i, userID, "Resolved data is nil")
return
}
msgs := resolved.Messages
if len(msgs) != 1 {
errorReply(s, i, userID, "Expected exactly one message")
return
}
var msg *discordgo.Message
for _, v := range msgs {
msg = v
}
if !IsThisBot(msg.Author.ID) {
errorReply(s, i, userID, "Expected message to be from the bot")
return
}
resp := &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "✨ Poof! The message has vanished into the void.",
Flags: discordgo.MessageFlagsEphemeral,
},
}
log.S(log.Warning, "command-delete", log.Any("user", userID), log.Any("message", msg))
err := s.ChannelMessageDelete(i.ChannelID, msg.ID)
if err != nil {
log.Errf("Error deleting message: %v", err)
}
err = s.InteractionRespond(i.Interaction, resp)
if err != nil {
log.Errf("Error responding to interaction: %v", err)
}
}
func interactionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Type == discordgo.InteractionApplicationCommand {
processApplicationCommandInteraction(s, i)
return
}
if i.Type != discordgo.InteractionMessageComponent {
log.S(log.Info, "Ignoring interaction", log.Any("type", i.Type))
return
}
log.S(log.Info, "interaction", log.Any("interaction", i))
// Call into grol interpreter.
data := i.MessageComponentData()
json, err := json.Marshal(data)
if err != nil {
log.Critf("Error marshaling interaction data: %v", err)
return
}
// Key state of the message ID.
var userID string
if i.User == nil {
userID = i.Member.User.ID
} else {
userID = i.User.ID
}
code := fmt.Sprintf("discord.doInteraction(%q,%q,%s)", i.Message.ID, userID, json)
log.Infof("Running code: %s", code)
cfg := replConfig()
cfg.PreInput = func(state *eval.State) {
st := MessageState{
Session: s,
Interaction: i.Interaction,
}
name, fn := InteractionRespondFunction(&st)
state.Extensions[name] = fn
}
res, errs, _ := repl.EvalStringWithOption(context.Background(), cfg, code)
log.Infof("Interaction (ignored) result: %q errs %v", res, errs)
if len(errs) > 0 {
p := &CommandParams{
session: s,
message: i.Message,
channelID: i.ChannelID,
}
res += "<@" + userID + ">:" + errorsBlock(errs)
reply(s, res, p)
}
}
type MessageState struct {
Session *discordgo.Session
ChannelID string
TriggerMessageID string
// for interaction responses
Interaction *discordgo.Interaction
ImageMap extensions.ImageMap
}
func InteractionRespondFunction(st *MessageState) (string, object.Extension) {
cmd := object.Extension{
Name: "InteractionRespond",
MinArgs: 1,
MaxArgs: 1,
ArgTypes: []object.Type{object.MAP},
ClientData: st, // Unique to the current interpreter
Callback: func(cdata any, _ string, args []object.Object) object.Object {
msgContext, ok := cdata.(*MessageState)
if !ok {
log.Fatalf("Invalid client data type: %T", cdata)
}
log.Debugf("InteractionRespond Message state %+v", msgContext)
msg := args[0].(object.Map).Unwrap(true).(map[string]any)
msg["data"].(map[string]any)["allowed_mentions"] = discordgo.MessageAllowedMentions{
Parse: []discordgo.AllowedMentionType{},
}
endpoint := discordgo.EndpointInteractionResponse(msgContext.Interaction.ID, msgContext.Interaction.Token)
_, err := msgContext.Session.RequestWithBucketID(http.MethodPost, endpoint, msg, endpoint)
if err != nil {
log.Errf("Error sending interaction response: %v", err)
return object.Errorf("Error sending interaction response: %v", err)
}
return object.NULL
},
}
return cmd.Name, cmd
}
func ChannelMessageSendComplexFunction(st *MessageState) (string, object.Extension) {
cmd := object.Extension{
Name: "ChannelMessageSendComplex",
MinArgs: 1,
MaxArgs: 1,
ArgTypes: []object.Type{object.MAP},
ClientData: st, // Unique to the current interpreter
Callback: func(cdata any, _ string, args []object.Object) object.Object {
msgContext, ok := cdata.(*MessageState)
if !ok {
log.Fatalf("Invalid client data type: %T", cdata)
}
log.Debugf("ChannelMessageSendComplex Message state %+v", msgContext)
chID := msgContext.ChannelID
msg := args[0].(object.Map).Unwrap(true).(map[string]any)
// Make this a reply to identify the origin source (person) of the message.
ref := make(map[string]string, 1)
ref["message_id"] = msgContext.TriggerMessageID
msg["message_reference"] = ref
msg["allowed_mentions"] = discordgo.MessageAllowedMentions{
Parse: []discordgo.AllowedMentionType{},
}
log.Debugf("Sending message to channel %s: %v", chID, msg)
endpoint := discordgo.EndpointChannelMessages(chID)
response, err := msgContext.Session.RequestWithBucketID(http.MethodPost, endpoint, msg, endpoint)
if err != nil {
log.Errf("Error sending message: %v", err)
return object.Errorf("Error sending message: %v", err)
}
var m discordgo.Message
err = json.Unmarshal(response, &m)
if err != nil {
log.Errf("Error unmarshalling message: %v", err)
return object.Errorf("Error unmarshalling message: %v", err)
}
updateMap(msgContext.TriggerMessageID, m.ID)
return object.String{Value: m.ID}
},
}
return cmd.Name, cmd
}
/*
Basic working JSON example:
{"content":"A test...","components":[{"type":1,"components":[{"label":"Option 1","type":2},{"label":"Option 2","type":2}]}]}
Now handled in discord.gr
*/