Thumbnail

rani/matterbridge.git

Clone URL: https://git.buni.party/rani/matterbridge.git

Viewing file on branch master

1package bdiscord
2
3import (
4 "bytes"
5 "fmt"
6 "strings"
7 "sync"
8
9 "github.com/bwmarrin/discordgo"
10 lru "github.com/hashicorp/golang-lru"
11 "github.com/matterbridge-org/matterbridge/bridge"
12 "github.com/matterbridge-org/matterbridge/bridge/config"
13 "github.com/matterbridge-org/matterbridge/bridge/discord/transmitter"
14 "github.com/matterbridge-org/matterbridge/bridge/helper"
15)
16
17const (
18 MessageLength = 1950
19 cFileUpload = "file_upload"
20)
21
22type Bdiscord struct {
23 *bridge.Config
24
25 c *discordgo.Session
26
27 nick string
28 userID string
29 guildID string
30
31 channelsMutex sync.RWMutex
32 channels []*discordgo.Channel
33 channelInfoMap map[string]*config.ChannelInfo
34
35 membersMutex sync.RWMutex
36 userMemberMap map[string]*discordgo.Member
37 nickMemberMap map[string]*discordgo.Member
38
39 // Never send Discord's attachments as URLs, always download and re-upload them to the destination as regular files
40 alwaysDownloadFiles bool
41
42 // Webhook specific logic
43 useAutoWebhooks bool
44 transmitter *transmitter.Transmitter
45 cache *lru.Cache
46}
47
48func New(cfg *bridge.Config) bridge.Bridger {
49 newCache, err := lru.New(5000)
50 if err != nil {
51 cfg.Log.Fatalf("Could not create LRU cache: %v", err)
52 }
53
54 b := &Bdiscord{
55 Config: cfg,
56 cache: newCache,
57 }
58
59 b.userMemberMap = make(map[string]*discordgo.Member)
60 b.nickMemberMap = make(map[string]*discordgo.Member)
61 b.channelInfoMap = make(map[string]*config.ChannelInfo)
62
63 b.alwaysDownloadFiles = b.GetBool("AlwaysDownloadFiles")
64
65 b.useAutoWebhooks = b.GetBool("AutoWebhooks")
66 if b.useAutoWebhooks {
67 b.Log.Debug("Using automatic webhooks")
68 }
69 return b
70}
71
72func (b *Bdiscord) Connect() error {
73 var err error
74 token := b.GetString("Token")
75 b.Log.Info("Connecting")
76 if !strings.HasPrefix(b.GetString("Token"), "Bot ") {
77 token = "Bot " + b.GetString("Token")
78 }
79 // if we have a User token, remove the `Bot` prefix
80 if strings.HasPrefix(b.GetString("Token"), "User ") {
81 token = strings.ReplaceAll(b.GetString("Token"), "User ", "")
82 }
83
84 b.c, err = discordgo.New(token)
85 if err != nil {
86 return err
87 }
88 b.Log.Info("Connection succeeded")
89 // Add privileged intent for guild member tracking. This is needed to track nicks
90 // for display names and @mention translation
91 b.c.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAllWithoutPrivileged |
92 discordgo.IntentsGuildMembers)
93
94 err = b.c.Open()
95 if err != nil {
96 return err
97 }
98 guilds, err := b.c.UserGuilds(100, "", "", false)
99 if err != nil {
100 return err
101 }
102 userinfo, err := b.c.User("@me")
103 if err != nil {
104 return err
105 }
106 serverName := strings.ReplaceAll(b.GetString("Server"), "ID:", "")
107 b.nick = userinfo.Username
108 b.userID = userinfo.ID
109
110 // Try and find this account's guild, and populate channels
111 b.channelsMutex.Lock()
112 for _, guild := range guilds {
113 // Skip, if the server name does not match the visible name or the ID
114 if guild.Name != serverName && guild.ID != serverName {
115 continue
116 }
117
118 // Complain about an ambiguous Server setting. Two Discord servers could have the same title!
119 // For IDs, practically this will never happen. It would only trigger if some server's name is also an ID.
120 if b.guildID != "" {
121 return fmt.Errorf("found multiple Discord servers with the same name %#v, expected to see only one", serverName)
122 }
123
124 // Getting this guild's channel could result in a permission error
125 b.channels, err = b.c.GuildChannels(guild.ID)
126 if err != nil {
127 return fmt.Errorf("could not get %#v's channels: %w", b.GetString("Server"), err)
128 }
129
130 b.guildID = guild.ID
131 }
132 b.channelsMutex.Unlock()
133
134 // If we couldn't find a guild, we print extra debug information and return a nice error
135 if b.guildID == "" {
136 err = fmt.Errorf("could not find Discord server %#v", b.GetString("Server"))
137 b.Log.Error(err.Error())
138
139 // Print all of the possible server values
140 b.Log.Info("Possible server values:")
141 for _, guild := range guilds {
142 b.Log.Infof("\t- Server=%#v # by name", guild.Name)
143 b.Log.Infof("\t- Server=%#v # by ID", guild.ID)
144 }
145
146 // If there are no results, we should say that
147 if len(guilds) == 0 {
148 b.Log.Info("\t- (none found)")
149 }
150
151 return err
152 }
153
154 // Legacy note: WebhookURL used to have an actual webhook URL that we would edit,
155 // but we stopped doing that due to Discord making rate limits more aggressive.
156 //
157 // Even older: the same WebhookURL used to be used by every channel, which is usually unexpected.
158 // This is no longer possible.
159 if b.GetString("WebhookURL") != "" {
160 message := "The global WebhookURL setting has been removed. "
161 message += "You can get similar \"webhook editing\" behaviour by replacing this line with `AutoWebhooks=true`. "
162 message += "If you rely on the old-OLD (non-editing) behaviour, can move the WebhookURL to specific channel sections."
163 b.Log.Errorln(message)
164 return fmt.Errorf("use of removed WebhookURL setting")
165 }
166
167 if b.GetInt("debuglevel") == 2 {
168 b.Log.Debug("enabling even more discord debug")
169 b.c.Debug = true
170 }
171
172 // Initialise webhook management
173 b.transmitter = transmitter.New(b.c, b.guildID, "matterbridge", b.useAutoWebhooks)
174 b.transmitter.Log = b.Log
175
176 var webhookChannelIDs []string
177 for _, channel := range b.Channels {
178 channelID := b.getChannelID(channel.Name) // note(qaisjp): this readlocks channelsMutex
179
180 // If a WebhookURL was not explicitly provided for this channel,
181 // there are two options: just a regular bot message (ugly) or this is should be webhook sent
182 if channel.Options.WebhookURL == "" {
183 // If it should be webhook sent, we should enforce this via the transmitter
184 if b.useAutoWebhooks {
185 webhookChannelIDs = append(webhookChannelIDs, channelID)
186 }
187 continue
188 }
189
190 whID, whToken, ok := b.splitURL(channel.Options.WebhookURL)
191 if !ok {
192 return fmt.Errorf("failed to parse WebhookURL %#v for channel %#v", channel.Options.WebhookURL, channel.ID)
193 }
194
195 b.transmitter.AddWebhook(channelID, &discordgo.Webhook{
196 ID: whID,
197 Token: whToken,
198 GuildID: b.guildID,
199 ChannelID: channelID,
200 })
201 }
202
203 if b.useAutoWebhooks {
204 err = b.transmitter.RefreshGuildWebhooks(webhookChannelIDs)
205 if err != nil {
206 b.Log.WithError(err).Println("transmitter could not refresh guild webhooks")
207 return err
208 }
209 }
210
211 // Obtaining guild members and initializing nickname mapping.
212 b.membersMutex.Lock()
213 defer b.membersMutex.Unlock()
214 members, err := b.c.GuildMembers(b.guildID, "", 1000)
215 if err != nil {
216 b.Log.Error("Error obtaining server members: ", err)
217 return err
218 }
219 for _, member := range members {
220 if member == nil {
221 b.Log.Warnf("Skipping missing information for a user.")
222 continue
223 }
224 b.userMemberMap[member.User.ID] = member
225 b.nickMemberMap[member.User.Username] = member
226 if member.Nick != "" {
227 b.nickMemberMap[member.Nick] = member
228 }
229 }
230
231 b.c.AddHandler(b.messageCreate)
232 b.c.AddHandler(b.messageTyping)
233 b.c.AddHandler(b.messageUpdate)
234 b.c.AddHandler(b.messageDelete)
235 b.c.AddHandler(b.messageDeleteBulk)
236 b.c.AddHandler(b.memberAdd)
237 b.c.AddHandler(b.memberRemove)
238 b.c.AddHandler(b.memberUpdate)
239 if b.GetInt("debuglevel") == 1 {
240 b.c.AddHandler(b.messageEvent)
241 }
242
243 return nil
244}
245
246func (b *Bdiscord) Disconnect() error {
247 return b.c.Close()
248}
249
250func (b *Bdiscord) JoinChannel(channel config.ChannelInfo) error {
251 b.channelsMutex.Lock()
252 defer b.channelsMutex.Unlock()
253
254 b.channelInfoMap[channel.ID] = &channel
255 return nil
256}
257
258func (b *Bdiscord) Send(msg config.Message) (string, error) {
259 b.Log.Debugf("=> Receiving %#v", msg)
260
261 channelID := b.getChannelID(msg.Channel)
262 if channelID == "" {
263 return "", fmt.Errorf("Could not find channelID for %v", msg.Channel)
264 }
265
266 if msg.Event == config.EventUserTyping {
267 if b.GetBool("ShowUserTyping") {
268 err := b.c.ChannelTyping(channelID)
269 return "", err
270 }
271 return "", nil
272 }
273
274 // Make a action /me of the message
275 if msg.Event == config.EventUserAction {
276 msg.Text = "_" + msg.Text + "_"
277 }
278
279 // Handle prefix hint for unthreaded messages.
280 if msg.ParentNotFound() {
281 msg.ParentID = ""
282 }
283
284 // Use webhook to send the message
285 useWebhooks := b.shouldMessageUseWebhooks(&msg)
286 if useWebhooks && msg.Event != config.EventMsgDelete && msg.ParentID == "" {
287 return b.handleEventWebhook(&msg, channelID)
288 }
289
290 return b.handleEventBotUser(&msg, channelID)
291}
292
293// handleEventDirect handles events via the bot user
294func (b *Bdiscord) handleEventBotUser(msg *config.Message, channelID string) (string, error) {
295 b.Log.Debugf("Broadcasting using token (API)")
296
297 // Delete message
298 if msg.Event == config.EventMsgDelete {
299 if msg.ID == "" {
300 return "", nil
301 }
302 err := b.c.ChannelMessageDelete(channelID, msg.ID)
303 return "", err
304 }
305
306 // Delete a file
307 if msg.Event == config.EventFileDelete {
308 if msg.ID == "" {
309 return "", nil
310 }
311
312 if fi, ok := b.cache.Get(cFileUpload + msg.ID); ok {
313 err := b.c.ChannelMessageDelete(channelID, fi.(string)) // nolint:forcetypeassert
314 b.cache.Remove(cFileUpload + msg.ID)
315 return "", err
316 }
317
318 return "", fmt.Errorf("file %s not found", msg.ID)
319 }
320
321 // Upload a file if it exists
322 if msg.Extra != nil {
323 for _, rmsg := range helper.HandleExtra(msg, b.General) {
324 // TODO: Use ClipOrSplitMessage
325 rmsg.Text = helper.ClipMessage(rmsg.Text, MessageLength, b.GetString("MessageClipped"))
326 if _, err := b.c.ChannelMessageSend(channelID, rmsg.Username+rmsg.Text); err != nil {
327 b.Log.Errorf("Could not send message %#v: %s", rmsg, err)
328 }
329 }
330 // check if we have files to upload (from slack, telegram or mattermost)
331 if len(msg.Extra["file"]) > 0 {
332 return b.handleUploadFile(msg, channelID)
333 }
334 }
335
336 // Edit message
337 if msg.ID != "" {
338 // Exploit that a discord message ID is actually just a large number, and we encode a list of IDs by separating them with ";".
339 msgIds := strings.Split(msg.ID, ";")
340 msgParts := helper.ClipOrSplitMessage(b.replaceUserMentions(msg.Text), MessageLength, b.GetString("MessageClipped"), len(msgIds))
341 for len(msgParts) < len(msgIds) {
342 msgParts = append(msgParts, "((obsoleted by edit))")
343 }
344 for i := range msgParts {
345 // In case of split-messages where some parts remain the same (i.e. only a typo-fix in a huge message), this causes some noop-updates.
346 // TODO: Optimize away noop-updates of un-edited messages
347 // TODO: Use RemoteNickFormat instead of this broken concatenation
348 _, err := b.c.ChannelMessageEdit(channelID, msgIds[i], msg.Username+msgParts[i])
349 if err != nil {
350 return "", err
351 }
352 }
353 return msg.ID, nil
354 }
355
356 msgParts := helper.ClipOrSplitMessage(b.replaceUserMentions(msg.Text), MessageLength, b.GetString("MessageClipped"), b.GetInt("MessageSplitMaxCount"))
357 msgIds := []string{}
358
359 for _, msgPart := range msgParts {
360 m := discordgo.MessageSend{
361 Content: msg.Username + msgPart,
362 AllowedMentions: b.getAllowedMentions(),
363 }
364
365 if msg.ParentValid() {
366 m.Reference = &discordgo.MessageReference{
367 MessageID: msg.ParentID,
368 ChannelID: channelID,
369 GuildID: b.guildID,
370 }
371 }
372
373 // Post normal message
374 res, err := b.c.ChannelMessageSendComplex(channelID, &m)
375 if err != nil {
376 return "", err
377 }
378 msgIds = append(msgIds, res.ID)
379 }
380
381 // Exploit that a discord message ID is actually just a large number, so we encode a list of IDs by separating them with ";".
382 return strings.Join(msgIds, ";"), nil
383}
384
385// handleUploadFile handles native upload of files
386func (b *Bdiscord) handleUploadFile(msg *config.Message, channelID string) (string, error) {
387 for _, f := range msg.Extra["file"] {
388 fi := f.(config.FileInfo)
389 file := discordgo.File{
390 Name: fi.Name,
391 ContentType: "",
392 Reader: bytes.NewReader(*fi.Data),
393 }
394 m := discordgo.MessageSend{
395 Content: msg.Username + fi.Comment,
396 Files: []*discordgo.File{&file},
397 AllowedMentions: b.getAllowedMentions(),
398 }
399 res, err := b.c.ChannelMessageSendComplex(channelID, &m)
400 if err != nil {
401 return "", fmt.Errorf("file upload failed: %s", err)
402 }
403
404 // link file_upload_nativeID (file ID from the original bridge) to our upload id
405 // so that we can remove this later when it eg needs to be deleted
406 b.cache.Add(cFileUpload+fi.NativeID, res.ID)
407 }
408
409 return "", nil
410}
411