forked from jshiffer/matterbridge
Clean up code and strengthening (slack) (#519)
Changes include: - Refactor of strings into package-wide constants. - Predeclaration of regexps to be instantiated at package load time. - Checking of unchecked errors. - Structural changes: - Adding verifications to type-casting code. - Remove unnecessary 'len(X) > 0' checks before iterating over X. - Remove unnecessary 'else' clause after 'if' with 'return'. - Unexporting of public fields of Bridge struct. - Formatting: - One-field-per-line struct definitions.
This commit is contained in:
parent
3dd4ec57ff
commit
498377a230
@ -14,7 +14,7 @@ import (
|
|||||||
|
|
||||||
func (b *Bslack) handleSlack() {
|
func (b *Bslack) handleSlack() {
|
||||||
messages := make(chan *config.Message)
|
messages := make(chan *config.Message)
|
||||||
if b.GetString("WebhookBindAddress") != "" {
|
if b.GetString(incomingWebhookConfig) != "" {
|
||||||
b.Log.Debugf("Choosing webhooks based receiving")
|
b.Log.Debugf("Choosing webhooks based receiving")
|
||||||
go b.handleMatterHook(messages)
|
go b.handleMatterHook(messages)
|
||||||
} else {
|
} else {
|
||||||
@ -43,7 +43,7 @@ func (b *Bslack) handleSlack() {
|
|||||||
|
|
||||||
func (b *Bslack) handleSlackClient(messages chan *config.Message) {
|
func (b *Bslack) handleSlackClient(messages chan *config.Message) {
|
||||||
for msg := range b.rtm.IncomingEvents {
|
for msg := range b.rtm.IncomingEvents {
|
||||||
if msg.Type != "user_typing" && msg.Type != "latency_report" {
|
if msg.Type != sUserTyping && msg.Type != sLatencyReport {
|
||||||
b.Log.Debugf("== Receiving event %#v", msg.Data)
|
b.Log.Debugf("== Receiving event %#v", msg.Data)
|
||||||
}
|
}
|
||||||
switch ev := msg.Data.(type) {
|
switch ev := msg.Data.(type) {
|
||||||
@ -61,17 +61,25 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) {
|
|||||||
case *slack.OutgoingErrorEvent:
|
case *slack.OutgoingErrorEvent:
|
||||||
b.Log.Debugf("%#v", ev.Error())
|
b.Log.Debugf("%#v", ev.Error())
|
||||||
case *slack.ChannelJoinedEvent:
|
case *slack.ChannelJoinedEvent:
|
||||||
b.Users, _ = b.sc.GetUsers()
|
var err error
|
||||||
b.Usergroups, _ = b.sc.GetUserGroups()
|
b.users, err = b.sc.GetUsers()
|
||||||
|
if err != nil {
|
||||||
|
b.Log.Errorf("Could not reload users: %#v", err)
|
||||||
|
}
|
||||||
case *slack.ConnectedEvent:
|
case *slack.ConnectedEvent:
|
||||||
var err error
|
var err error
|
||||||
b.channels, _, err = b.sc.GetConversations(&slack.GetConversationsParameters{Limit: 1000, Types: []string{"public_channel,private_channel,mpim,im"}})
|
b.channels, _, err = b.sc.GetConversations(&slack.GetConversationsParameters{
|
||||||
|
Limit: 1000,
|
||||||
|
Types: []string{"public_channel,private_channel,mpim,im"},
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("Channel list failed: %#v", err)
|
b.Log.Errorf("Channel list failed: %#v", err)
|
||||||
}
|
}
|
||||||
b.si = ev.Info
|
b.si = ev.Info
|
||||||
b.Users, _ = b.sc.GetUsers()
|
b.users, err = b.sc.GetUsers()
|
||||||
b.Usergroups, _ = b.sc.GetUserGroups()
|
if err != nil {
|
||||||
|
b.Log.Errorf("Could not reload users: %#v", err)
|
||||||
|
}
|
||||||
case *slack.InvalidAuthEvent:
|
case *slack.InvalidAuthEvent:
|
||||||
b.Log.Fatalf("Invalid Token %#v", ev)
|
b.Log.Fatalf("Invalid Token %#v", ev)
|
||||||
case *slack.ConnectionErrorEvent:
|
case *slack.ConnectionErrorEvent:
|
||||||
@ -88,16 +96,22 @@ func (b *Bslack) handleMatterHook(messages chan *config.Message) {
|
|||||||
if message.UserName == "slackbot" {
|
if message.UserName == "slackbot" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
messages <- &config.Message{Username: message.UserName, Text: message.Text, Channel: message.ChannelName}
|
messages <- &config.Message{
|
||||||
|
Username: message.UserName,
|
||||||
|
Text: message.Text,
|
||||||
|
Channel: message.ChannelName,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var commentRE = regexp.MustCompile(`.*?commented: (.*)`)
|
||||||
|
|
||||||
// handleDownloadFile handles file download
|
// handleDownloadFile handles file download
|
||||||
func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) error {
|
func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) error {
|
||||||
// if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra
|
// if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra
|
||||||
// limit to 1MB for now
|
// limit to 1MB for now
|
||||||
comment := ""
|
comment := ""
|
||||||
results := regexp.MustCompile(`.*?commented: (.*)`).FindAllStringSubmatch(rmsg.Text, -1)
|
results := commentRE.FindAllStringSubmatch(rmsg.Text, -1)
|
||||||
if len(results) > 0 {
|
if len(results) > 0 {
|
||||||
comment = results[0][1]
|
comment = results[0][1]
|
||||||
}
|
}
|
||||||
@ -106,7 +120,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// actually download the file
|
// actually download the file
|
||||||
data, err := helper.DownloadFileAuth(file.URLPrivateDownload, "Bearer "+b.GetString("Token"))
|
data, err := helper.DownloadFileAuth(file.URLPrivateDownload, "Bearer "+b.GetString(tokenConfig))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err)
|
return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err)
|
||||||
}
|
}
|
||||||
@ -116,7 +130,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
// handleUploadFile handles native upload of files
|
// handleUploadFile handles native upload of files
|
||||||
func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string, error) {
|
func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) {
|
||||||
for _, f := range msg.Extra["file"] {
|
for _, f := range msg.Extra["file"] {
|
||||||
fi := f.(config.FileInfo)
|
fi := f.(config.FileInfo)
|
||||||
if msg.Text == fi.Comment {
|
if msg.Text == fi.Comment {
|
||||||
@ -141,37 +155,46 @@ func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string
|
|||||||
b.Log.Errorf("uploadfile %#v", err)
|
b.Log.Errorf("uploadfile %#v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleMessageEvent handles the message events
|
// handleMessageEvent handles the message events
|
||||||
func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, error) {
|
func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
// update the userlist on a channel_join
|
// update the userlist on a channel_join
|
||||||
if ev.SubType == "channel_join" {
|
if ev.SubType == sChannelJoin {
|
||||||
b.Users, _ = b.sc.GetUsers()
|
if b.users, err = b.sc.GetUsers(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit message
|
// Edit message
|
||||||
if !b.GetBool("EditDisable") && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
|
if !b.GetBool(editDisableConfig) && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
|
||||||
b.Log.Debugf("SubMessage %#v", ev.SubMessage)
|
b.Log.Debugf("SubMessage %#v", ev.SubMessage)
|
||||||
ev.User = ev.SubMessage.User
|
ev.User = ev.SubMessage.User
|
||||||
ev.Text = ev.SubMessage.Text + b.GetString("EditSuffix")
|
ev.Text = ev.SubMessage.Text + b.GetString(editSuffixConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
// use our own func because rtm.GetChannelInfo doesn't work for private channels
|
// use our own func because rtm.GetChannelInfo doesn't work for private channels
|
||||||
channel, err := b.getChannelByID(ev.Channel)
|
channelInfo, err := b.getChannelByID(ev.Channel)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
rmsg := config.Message{Text: ev.Text, Channel: channel.Name, Account: b.Account, ID: "slack " + ev.Timestamp, Extra: make(map[string][]interface{})}
|
rmsg := config.Message{
|
||||||
|
Text: ev.Text,
|
||||||
|
Channel: channelInfo.Name,
|
||||||
|
Account: b.Account,
|
||||||
|
ID: "slack " + ev.Timestamp,
|
||||||
|
Extra: map[string][]interface{}{},
|
||||||
|
}
|
||||||
|
|
||||||
if b.UseChannelID {
|
if b.useChannelID {
|
||||||
rmsg.Channel = "ID:" + channel.ID
|
rmsg.Channel = "ID:" + channelInfo.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
// find the user id and name
|
// find the user id and name
|
||||||
if ev.User != "" && ev.SubType != messageDeleted && ev.SubType != "file_comment" {
|
if ev.User != "" && ev.SubType != sMessageDeleted && ev.SubType != sFileComment {
|
||||||
user, err := b.rtm.GetUserInfo(ev.User)
|
user, err := b.rtm.GetUserInfo(ev.User)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -198,7 +221,7 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// when using webhookURL we can't check if it's our webhook or not for now
|
// when using webhookURL we can't check if it's our webhook or not for now
|
||||||
if rmsg.Username == "" && ev.BotID != "" && b.GetString("WebhookURL") == "" {
|
if rmsg.Username == "" && ev.BotID != "" && b.GetString(outgoingWebhookConfig) == "" {
|
||||||
bot, err := b.rtm.GetBotInfo(ev.BotID)
|
bot, err := b.rtm.GetBotInfo(ev.BotID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -226,18 +249,18 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// file comments are set by the system (because there is no username given)
|
// file comments are set by the system (because there is no username given)
|
||||||
if ev.SubType == "file_comment" {
|
if ev.SubType == sFileComment {
|
||||||
rmsg.Username = "system"
|
rmsg.Username = sSystemUser
|
||||||
}
|
}
|
||||||
|
|
||||||
// do we have a /me action
|
// do we have a /me action
|
||||||
if ev.SubType == "me_message" {
|
if ev.SubType == sMeMessage {
|
||||||
rmsg.Event = config.EVENT_USER_ACTION
|
rmsg.Event = config.EVENT_USER_ACTION
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle join/leave
|
// Handle join/leave
|
||||||
if ev.SubType == "channel_leave" || ev.SubType == "channel_join" {
|
if ev.SubType == sChannelLeave || ev.SubType == sChannelJoin {
|
||||||
rmsg.Username = "system"
|
rmsg.Username = sSystemUser
|
||||||
rmsg.Event = config.EVENT_JOIN_LEAVE
|
rmsg.Event = config.EVENT_JOIN_LEAVE
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -247,19 +270,19 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// deleted message event
|
// deleted message event
|
||||||
if ev.SubType == messageDeleted {
|
if ev.SubType == sMessageDeleted {
|
||||||
rmsg.Text = config.EVENT_MSG_DELETE
|
rmsg.Text = config.EVENT_MSG_DELETE
|
||||||
rmsg.Event = config.EVENT_MSG_DELETE
|
rmsg.Event = config.EVENT_MSG_DELETE
|
||||||
rmsg.ID = "slack " + ev.DeletedTimestamp
|
rmsg.ID = "slack " + ev.DeletedTimestamp
|
||||||
}
|
}
|
||||||
|
|
||||||
// topic change event
|
// topic change event
|
||||||
if ev.SubType == "channel_topic" || ev.SubType == "channel_purpose" {
|
if ev.SubType == sChannelTopic || ev.SubType == sChannelPurpose {
|
||||||
rmsg.Event = config.EVENT_TOPIC_CHANGE
|
rmsg.Event = config.EVENT_TOPIC_CHANGE
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only deleted messages can have a empty username and text
|
// Only deleted messages can have a empty username and text
|
||||||
if (rmsg.Text == "" || rmsg.Username == "") && ev.SubType != messageDeleted && len(ev.Files) == 0 {
|
if (rmsg.Text == "" || rmsg.Username == "") && ev.SubType != sMessageDeleted && len(ev.Files) == 0 {
|
||||||
// this is probably a webhook we couldn't resolve
|
// this is probably a webhook we couldn't resolve
|
||||||
if ev.BotID != "" {
|
if ev.BotID != "" {
|
||||||
return nil, fmt.Errorf("probably an incoming webhook we couldn't resolve (maybe ourselves)")
|
return nil, fmt.Errorf("probably an incoming webhook we couldn't resolve (maybe ourselves)")
|
||||||
@ -269,35 +292,33 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er
|
|||||||
|
|
||||||
// save the attachments, so that we can send them to other slack (compatible) bridges
|
// save the attachments, so that we can send them to other slack (compatible) bridges
|
||||||
if len(ev.Attachments) > 0 {
|
if len(ev.Attachments) > 0 {
|
||||||
rmsg.Extra["slack_attachment"] = append(rmsg.Extra["slack_attachment"], ev.Attachments)
|
rmsg.Extra[sSlackAttachment] = append(rmsg.Extra[sSlackAttachment], ev.Attachments)
|
||||||
}
|
}
|
||||||
|
|
||||||
// if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra
|
// if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra
|
||||||
if len(ev.Files) > 0 {
|
|
||||||
for _, f := range ev.Files {
|
for _, f := range ev.Files {
|
||||||
err := b.handleDownloadFile(&rmsg, &f)
|
err := b.handleDownloadFile(&rmsg, &f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Log.Errorf("download failed: %s", err)
|
b.Log.Errorf("download failed: %s", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return &rmsg, nil
|
return &rmsg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// skipMessageEvent skips event that need to be skipped :-)
|
// skipMessageEvent skips event that need to be skipped :-)
|
||||||
func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool {
|
func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool {
|
||||||
if ev.SubType == "channel_leave" || ev.SubType == "channel_join" {
|
if ev.SubType == sChannelLeave || ev.SubType == sChannelJoin {
|
||||||
return b.GetBool("nosendjoinpart")
|
return b.GetBool(noSendJoinConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ignore pinned items
|
// ignore pinned items
|
||||||
if ev.SubType == "pinned_item" || ev.SubType == "unpinned_item" {
|
if ev.SubType == sPinnedItem || ev.SubType == sUnpinnedItem {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// do not send messages from ourself
|
// do not send messages from ourself
|
||||||
if b.GetString("WebhookURL") == "" && b.GetString("WebhookBindAddress") == "" && ev.Username == b.si.User.Name {
|
if b.GetString(outgoingWebhookConfig) == "" && b.GetString(incomingWebhookConfig) == "" && ev.Username == b.si.User.Name {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -308,7 +329,7 @@ func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !b.GetBool("EditDisable") && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
|
if !b.GetBool(editDisableConfig) && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp {
|
||||||
// it seems ev.SubMessage.Edited == nil when slack unfurls
|
// it seems ev.SubMessage.Edited == nil when slack unfurls
|
||||||
// do not forward these messages #266
|
// do not forward these messages #266
|
||||||
if ev.SubMessage.Edited == nil {
|
if ev.SubMessage.Edited == nil {
|
||||||
@ -316,22 +337,17 @@ func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(ev.Files) > 0 {
|
|
||||||
for _, f := range ev.Files {
|
for _, f := range ev.Files {
|
||||||
// if the file is in the cache and isn't older then a minute, skip it
|
// if the file is in the cache and isn't older then a minute, skip it
|
||||||
if ts, ok := b.cache.Get("file" + f.ID); ok && time.Since(ts.(time.Time)) < time.Minute {
|
if ts, ok := b.cache.Get("file" + f.ID); ok && time.Since(ts.(time.Time)) < time.Minute {
|
||||||
b.Log.Debugf("Not downloading file id %s which we uploaded", f.ID)
|
b.Log.Debugf("Not downloading file id %s which we uploaded", f.ID)
|
||||||
return true
|
return true
|
||||||
} else {
|
} else if ts, ok := b.cache.Get("filename" + f.Name); ok && time.Since(ts.(time.Time)) < 10*time.Second {
|
||||||
if ts, ok := b.cache.Get("filename" + f.Name); ok && time.Since(ts.(time.Time)) < time.Second*10 {
|
|
||||||
b.Log.Debugf("Not downloading file name %s which we uploaded", f.Name)
|
b.Log.Debugf("Not downloading file name %s which we uploaded", f.Name)
|
||||||
return true
|
return true
|
||||||
} else {
|
}
|
||||||
b.Log.Debugf("Not skipping %s %s", f.Name, time.Now().String())
|
b.Log.Debugf("Not skipping %s %s", f.Name, time.Now().String())
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
@ -8,8 +8,8 @@ import (
|
|||||||
"github.com/nlopes/slack"
|
"github.com/nlopes/slack"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (b *Bslack) userName(id string) string {
|
func (b *Bslack) getUsername(id string) string {
|
||||||
for _, u := range b.Users {
|
for _, u := range b.users {
|
||||||
if u.ID == id {
|
if u.ID == id {
|
||||||
if u.Profile.DisplayName != "" {
|
if u.Profile.DisplayName != "" {
|
||||||
return u.Profile.DisplayName
|
return u.Profile.DisplayName
|
||||||
@ -17,22 +17,26 @@ func (b *Bslack) userName(id string) string {
|
|||||||
return u.Name
|
return u.Name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
b.Log.Warnf("Could not find user with ID '%s'", id)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bslack) getAvatar(userid string) string {
|
func (b *Bslack) getAvatar(userid string) string {
|
||||||
var avatar string
|
for _, u := range b.users {
|
||||||
if b.Users != nil {
|
|
||||||
for _, u := range b.Users {
|
|
||||||
if userid == u.ID {
|
if userid == u.ID {
|
||||||
return u.Profile.Image48
|
return u.Profile.Image48
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
return ""
|
||||||
return avatar
|
}
|
||||||
|
|
||||||
|
func (b *Bslack) getChannel(channel string) (*slack.Channel, error) {
|
||||||
|
if strings.HasPrefix(channel, "ID:") {
|
||||||
|
return b.getChannelByID(strings.TrimPrefix(channel, "ID:"))
|
||||||
|
}
|
||||||
|
return b.getChannelByName(channel)
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
func (b *Bslack) getChannelByName(name string) (*slack.Channel, error) {
|
func (b *Bslack) getChannelByName(name string) (*slack.Channel, error) {
|
||||||
if b.channels == nil {
|
if b.channels == nil {
|
||||||
return nil, fmt.Errorf("%s: channel %s not found (no channels found)", b.Account, name)
|
return nil, fmt.Errorf("%s: channel %s not found (no channels found)", b.Account, name)
|
||||||
@ -44,7 +48,6 @@ func (b *Bslack) getChannelByName(name string) (*slack.Channel, error) {
|
|||||||
}
|
}
|
||||||
return nil, fmt.Errorf("%s: channel %s not found", b.Account, name)
|
return nil, fmt.Errorf("%s: channel %s not found", b.Account, name)
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|
||||||
func (b *Bslack) getChannelByID(ID string) (*slack.Channel, error) {
|
func (b *Bslack) getChannelByID(ID string) (*slack.Channel, error) {
|
||||||
if b.channels == nil {
|
if b.channels == nil {
|
||||||
@ -58,45 +61,40 @@ func (b *Bslack) getChannelByID(ID string) (*slack.Channel, error) {
|
|||||||
return nil, fmt.Errorf("%s: channel %s not found", b.Account, ID)
|
return nil, fmt.Errorf("%s: channel %s not found", b.Account, ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bslack) getChannelID(name string) string {
|
var (
|
||||||
idcheck := strings.Split(name, "ID:")
|
mentionRE = regexp.MustCompile(`<@([a-zA-Z0-9]+)>`)
|
||||||
if len(idcheck) > 1 {
|
channelRE = regexp.MustCompile(`<#[a-zA-Z0-9]+\|(.+?)>`)
|
||||||
return idcheck[1]
|
variableRE = regexp.MustCompile(`<!((?:subteam\^)?[a-zA-Z0-9]+)(?:\|@?(.+?))?>`)
|
||||||
}
|
urlRE = regexp.MustCompile(`<(.*?)(\|.*?)?>`)
|
||||||
for _, channel := range b.channels {
|
)
|
||||||
if channel.Name == name {
|
|
||||||
return channel.ID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
|
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
|
||||||
func (b *Bslack) replaceMention(text string) string {
|
func (b *Bslack) replaceMention(text string) string {
|
||||||
results := regexp.MustCompile(`<@([a-zA-Z0-9]+)>`).FindAllStringSubmatch(text, -1)
|
replaceFunc := func(match string) string {
|
||||||
for _, r := range results {
|
userID := strings.Trim(match, "@<>")
|
||||||
text = strings.Replace(text, "<@"+r[1]+">", "@"+b.userName(r[1]), -1)
|
if username := b.getUsername(userID); userID != "" {
|
||||||
|
return "@" + username
|
||||||
}
|
}
|
||||||
return text
|
return match
|
||||||
|
}
|
||||||
|
return mentionRE.ReplaceAllStringFunc(text, replaceFunc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
|
// @see https://api.slack.com/docs/message-formatting#linking_to_channels_and_users
|
||||||
func (b *Bslack) replaceChannel(text string) string {
|
func (b *Bslack) replaceChannel(text string) string {
|
||||||
results := regexp.MustCompile(`<#[a-zA-Z0-9]+\|(.+?)>`).FindAllStringSubmatch(text, -1)
|
for _, r := range channelRE.FindAllStringSubmatch(text, -1) {
|
||||||
for _, r := range results {
|
text = strings.Replace(text, r[0], "#"+r[1], 1)
|
||||||
text = strings.Replace(text, r[0], "#"+r[1], -1)
|
|
||||||
}
|
}
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
// @see https://api.slack.com/docs/message-formatting#variables
|
// @see https://api.slack.com/docs/message-formatting#variables
|
||||||
func (b *Bslack) replaceVariable(text string) string {
|
func (b *Bslack) replaceVariable(text string) string {
|
||||||
results := regexp.MustCompile(`<!((?:subteam\^)?[a-zA-Z0-9]+)(?:\|@?(.+?))?>`).FindAllStringSubmatch(text, -1)
|
for _, r := range variableRE.FindAllStringSubmatch(text, -1) {
|
||||||
for _, r := range results {
|
|
||||||
if r[2] != "" {
|
if r[2] != "" {
|
||||||
text = strings.Replace(text, r[0], "@"+r[2], -1)
|
text = strings.Replace(text, r[0], "@"+r[2], 1)
|
||||||
} else {
|
} else {
|
||||||
text = strings.Replace(text, r[0], "@"+r[1], -1)
|
text = strings.Replace(text, r[0], "@"+r[1], 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return text
|
return text
|
||||||
@ -104,12 +102,11 @@ func (b *Bslack) replaceVariable(text string) string {
|
|||||||
|
|
||||||
// @see https://api.slack.com/docs/message-formatting#linking_to_urls
|
// @see https://api.slack.com/docs/message-formatting#linking_to_urls
|
||||||
func (b *Bslack) replaceURL(text string) string {
|
func (b *Bslack) replaceURL(text string) string {
|
||||||
results := regexp.MustCompile(`<(.*?)(\|.*?)?>`).FindAllStringSubmatch(text, -1)
|
for _, r := range urlRE.FindAllStringSubmatch(text, -1) {
|
||||||
for _, r := range results {
|
|
||||||
if len(strings.TrimSpace(r[2])) == 1 { // A display text separator was found, but the text was blank
|
if len(strings.TrimSpace(r[2])) == 1 { // A display text separator was found, but the text was blank
|
||||||
text = strings.Replace(text, r[0], "", -1)
|
text = strings.Replace(text, r[0], "", 1)
|
||||||
} else {
|
} else {
|
||||||
text = strings.Replace(text, r[0], r[1], -1)
|
text = strings.Replace(text, r[0], r[1], 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return text
|
return text
|
||||||
|
@ -2,6 +2,7 @@ package bslack
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@ -18,22 +19,52 @@ type Bslack struct {
|
|||||||
mh *matterhook.Client
|
mh *matterhook.Client
|
||||||
sc *slack.Client
|
sc *slack.Client
|
||||||
rtm *slack.RTM
|
rtm *slack.RTM
|
||||||
Users []slack.User
|
users []slack.User
|
||||||
Usergroups []slack.UserGroup
|
|
||||||
si *slack.Info
|
si *slack.Info
|
||||||
channels []slack.Channel
|
channels []slack.Channel
|
||||||
cache *lru.Cache
|
cache *lru.Cache
|
||||||
UseChannelID bool
|
useChannelID bool
|
||||||
uuid string
|
uuid string
|
||||||
*bridge.Config
|
*bridge.Config
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
const messageDeleted = "message_deleted"
|
const (
|
||||||
|
sChannelJoin = "channel_join"
|
||||||
|
sChannelLeave = "channel_leave"
|
||||||
|
sMessageDeleted = "message_deleted"
|
||||||
|
sSlackAttachment = "slack_attachment"
|
||||||
|
sPinnedItem = "pinned_item"
|
||||||
|
sUnpinnedItem = "unpinned_item"
|
||||||
|
sChannelTopic = "channel_topic"
|
||||||
|
sChannelPurpose = "channel_purpose"
|
||||||
|
sFileComment = "file_comment"
|
||||||
|
sMeMessage = "me_message"
|
||||||
|
sUserTyping = "user_typing"
|
||||||
|
sLatencyReport = "latency_report"
|
||||||
|
sSystemUser = "system"
|
||||||
|
|
||||||
|
tokenConfig = "Token"
|
||||||
|
incomingWebhookConfig = "WebhookBindAddress"
|
||||||
|
outgoingWebhookConfig = "WebhookURL"
|
||||||
|
skipTLSConfig = "SkipTLSVerify"
|
||||||
|
useNickPrefixConfig = "PrefixMessagesWithNick"
|
||||||
|
editDisableConfig = "EditDisable"
|
||||||
|
editSuffixConfig = "EditSuffix"
|
||||||
|
iconURLConfig = "iconurl"
|
||||||
|
noSendJoinConfig = "nosendjoinpart"
|
||||||
|
)
|
||||||
|
|
||||||
func New(cfg *bridge.Config) bridge.Bridger {
|
func New(cfg *bridge.Config) bridge.Bridger {
|
||||||
b := &Bslack{Config: cfg, uuid: xid.New().String()}
|
newCache, err := lru.New(5000)
|
||||||
b.cache, _ = lru.New(5000)
|
if err != nil {
|
||||||
|
cfg.Log.Fatalf("Could not create LRU cache for Slack bridge: %v", err)
|
||||||
|
}
|
||||||
|
b := &Bslack{
|
||||||
|
Config: cfg,
|
||||||
|
uuid: xid.New().String(),
|
||||||
|
cache: newCache,
|
||||||
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,50 +75,54 @@ func (b *Bslack) Command(cmd string) string {
|
|||||||
func (b *Bslack) Connect() error {
|
func (b *Bslack) Connect() error {
|
||||||
b.RLock()
|
b.RLock()
|
||||||
defer b.RUnlock()
|
defer b.RUnlock()
|
||||||
if b.GetString("WebhookBindAddress") != "" {
|
if b.GetString(incomingWebhookConfig) != "" {
|
||||||
if b.GetString("WebhookURL") != "" {
|
if b.GetString(outgoingWebhookConfig) != "" {
|
||||||
b.Log.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)")
|
b.Log.Info("Connecting using webhookurl (sending) and webhookbindaddress (receiving)")
|
||||||
b.mh = matterhook.New(b.GetString("WebhookURL"),
|
b.mh = matterhook.New(b.GetString(outgoingWebhookConfig), matterhook.Config{
|
||||||
matterhook.Config{InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
|
InsecureSkipVerify: b.GetBool(skipTLSConfig),
|
||||||
BindAddress: b.GetString("WebhookBindAddress")})
|
BindAddress: b.GetString(incomingWebhookConfig),
|
||||||
} else if b.GetString("Token") != "" {
|
})
|
||||||
|
} else if b.GetString(tokenConfig) != "" {
|
||||||
b.Log.Info("Connecting using token (sending)")
|
b.Log.Info("Connecting using token (sending)")
|
||||||
b.sc = slack.New(b.GetString("Token"))
|
b.sc = slack.New(b.GetString(tokenConfig))
|
||||||
b.rtm = b.sc.NewRTM()
|
b.rtm = b.sc.NewRTM()
|
||||||
go b.rtm.ManageConnection()
|
go b.rtm.ManageConnection()
|
||||||
b.Log.Info("Connecting using webhookbindaddress (receiving)")
|
b.Log.Info("Connecting using webhookbindaddress (receiving)")
|
||||||
b.mh = matterhook.New(b.GetString("WebhookURL"),
|
b.mh = matterhook.New(b.GetString(outgoingWebhookConfig), matterhook.Config{
|
||||||
matterhook.Config{InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
|
InsecureSkipVerify: b.GetBool(skipTLSConfig),
|
||||||
BindAddress: b.GetString("WebhookBindAddress")})
|
BindAddress: b.GetString(incomingWebhookConfig),
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
b.Log.Info("Connecting using webhookbindaddress (receiving)")
|
b.Log.Info("Connecting using webhookbindaddress (receiving)")
|
||||||
b.mh = matterhook.New(b.GetString("WebhookURL"),
|
b.mh = matterhook.New(b.GetString(outgoingWebhookConfig), matterhook.Config{
|
||||||
matterhook.Config{InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
|
InsecureSkipVerify: b.GetBool(skipTLSConfig),
|
||||||
BindAddress: b.GetString("WebhookBindAddress")})
|
BindAddress: b.GetString(incomingWebhookConfig),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
go b.handleSlack()
|
go b.handleSlack()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if b.GetString("WebhookURL") != "" {
|
if b.GetString(outgoingWebhookConfig) != "" {
|
||||||
b.Log.Info("Connecting using webhookurl (sending)")
|
b.Log.Info("Connecting using webhookurl (sending)")
|
||||||
b.mh = matterhook.New(b.GetString("WebhookURL"),
|
b.mh = matterhook.New(b.GetString(outgoingWebhookConfig), matterhook.Config{
|
||||||
matterhook.Config{InsecureSkipVerify: b.GetBool("SkipTLSVerify"),
|
InsecureSkipVerify: b.GetBool(skipTLSConfig),
|
||||||
DisableServer: true})
|
DisableServer: true,
|
||||||
if b.GetString("Token") != "" {
|
})
|
||||||
|
if b.GetString(tokenConfig) != "" {
|
||||||
b.Log.Info("Connecting using token (receiving)")
|
b.Log.Info("Connecting using token (receiving)")
|
||||||
b.sc = slack.New(b.GetString("Token"))
|
b.sc = slack.New(b.GetString(tokenConfig))
|
||||||
b.rtm = b.sc.NewRTM()
|
b.rtm = b.sc.NewRTM()
|
||||||
go b.rtm.ManageConnection()
|
go b.rtm.ManageConnection()
|
||||||
go b.handleSlack()
|
go b.handleSlack()
|
||||||
}
|
}
|
||||||
} else if b.GetString("Token") != "" {
|
} else if b.GetString(tokenConfig) != "" {
|
||||||
b.Log.Info("Connecting using token (sending and receiving)")
|
b.Log.Info("Connecting using token (sending and receiving)")
|
||||||
b.sc = slack.New(b.GetString("Token"))
|
b.sc = slack.New(b.GetString(tokenConfig))
|
||||||
b.rtm = b.sc.NewRTM()
|
b.rtm = b.sc.NewRTM()
|
||||||
go b.rtm.ManageConnection()
|
go b.rtm.ManageConnection()
|
||||||
go b.handleSlack()
|
go b.handleSlack()
|
||||||
}
|
}
|
||||||
if b.GetString("WebhookBindAddress") == "" && b.GetString("WebhookURL") == "" && b.GetString("Token") == "" {
|
if b.GetString(incomingWebhookConfig) == "" && b.GetString(outgoingWebhookConfig) == "" && b.GetString(tokenConfig) == "" {
|
||||||
return errors.New("no connection method found. See that you have WebhookBindAddress, WebhookURL or Token configured")
|
return errors.New("no connection method found. See that you have WebhookBindAddress, WebhookURL or Token configured")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@ -101,7 +136,7 @@ func (b *Bslack) JoinChannel(channel config.ChannelInfo) error {
|
|||||||
// use ID:channelid and resolve it to the actual name
|
// use ID:channelid and resolve it to the actual name
|
||||||
idcheck := strings.Split(channel.Name, "ID:")
|
idcheck := strings.Split(channel.Name, "ID:")
|
||||||
if len(idcheck) > 1 {
|
if len(idcheck) > 1 {
|
||||||
b.UseChannelID = true
|
b.useChannelID = true
|
||||||
ch, err := b.sc.GetChannelInfo(idcheck[1])
|
ch, err := b.sc.GetChannelInfo(idcheck[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@ -114,7 +149,7 @@ func (b *Bslack) JoinChannel(channel config.ChannelInfo) error {
|
|||||||
|
|
||||||
// we can only join channels using the API
|
// we can only join channels using the API
|
||||||
if b.sc != nil {
|
if b.sc != nil {
|
||||||
if strings.HasPrefix(b.GetString("Token"), "xoxb") {
|
if strings.HasPrefix(b.GetString(tokenConfig), "xoxb") {
|
||||||
// TODO check if bot has already joined channel
|
// TODO check if bot has already joined channel
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -141,11 +176,14 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Use webhook to send the message
|
// Use webhook to send the message
|
||||||
if b.GetString("WebhookURL") != "" {
|
if b.GetString(outgoingWebhookConfig) != "" {
|
||||||
return b.sendWebhook(msg)
|
return b.sendWebhook(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
channelID := b.getChannelID(msg.Channel)
|
channelInfo, err := b.getChannel(msg.Channel)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("could not send message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
// Delete message
|
// Delete message
|
||||||
if msg.Event == config.EVENT_MSG_DELETE {
|
if msg.Event == config.EVENT_MSG_DELETE {
|
||||||
@ -155,7 +193,7 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
}
|
}
|
||||||
// we get a "slack <ID>", split it
|
// we get a "slack <ID>", split it
|
||||||
ts := strings.Fields(msg.ID)
|
ts := strings.Fields(msg.ID)
|
||||||
_, _, err := b.sc.DeleteMessage(channelID, ts[1])
|
_, _, err = b.sc.DeleteMessage(channelInfo.ID, ts[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return msg.ID, err
|
return msg.ID, err
|
||||||
}
|
}
|
||||||
@ -163,14 +201,14 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Prepend nick if configured
|
// Prepend nick if configured
|
||||||
if b.GetBool("PrefixMessagesWithNick") {
|
if b.GetBool(useNickPrefixConfig) {
|
||||||
msg.Text = msg.Username + msg.Text
|
msg.Text = msg.Username + msg.Text
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit message if we have an ID
|
// Edit message if we have an ID
|
||||||
if msg.ID != "" {
|
if msg.ID != "" {
|
||||||
ts := strings.Fields(msg.ID)
|
ts := strings.Fields(msg.ID)
|
||||||
_, _, _, err := b.sc.UpdateMessage(channelID, ts[1], msg.Text)
|
_, _, _, err = b.sc.UpdateMessage(channelInfo.ID, ts[1], msg.Text)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return msg.ID, err
|
return msg.ID, err
|
||||||
}
|
}
|
||||||
@ -179,12 +217,12 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
|
|
||||||
// create slack new post parameters
|
// create slack new post parameters
|
||||||
np := slack.NewPostMessageParameters()
|
np := slack.NewPostMessageParameters()
|
||||||
if b.GetBool("PrefixMessagesWithNick") {
|
if b.GetBool(useNickPrefixConfig) {
|
||||||
np.AsUser = true
|
np.AsUser = true
|
||||||
}
|
}
|
||||||
np.Username = msg.Username
|
np.Username = msg.Username
|
||||||
np.LinkNames = 1 // replace mentions
|
np.LinkNames = 1 // replace mentions
|
||||||
np.IconURL = config.GetIconURL(&msg, b.GetString("iconurl"))
|
np.IconURL = config.GetIconURL(&msg, b.GetString(iconURLConfig))
|
||||||
if msg.Avatar != "" {
|
if msg.Avatar != "" {
|
||||||
np.IconURL = msg.Avatar
|
np.IconURL = msg.Avatar
|
||||||
}
|
}
|
||||||
@ -193,8 +231,8 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
// add file attachments
|
// add file attachments
|
||||||
np.Attachments = append(np.Attachments, b.createAttach(msg.Extra)...)
|
np.Attachments = append(np.Attachments, b.createAttach(msg.Extra)...)
|
||||||
// add slack attachments (from another slack bridge)
|
// add slack attachments (from another slack bridge)
|
||||||
if len(msg.Extra["slack_attachment"]) > 0 {
|
if msg.Extra != nil {
|
||||||
for _, attach := range msg.Extra["slack_attachment"] {
|
for _, attach := range msg.Extra[sSlackAttachment] {
|
||||||
np.Attachments = append(np.Attachments, attach.([]slack.Attachment)...)
|
np.Attachments = append(np.Attachments, attach.([]slack.Attachment)...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -202,16 +240,17 @@ func (b *Bslack) Send(msg config.Message) (string, error) {
|
|||||||
// Upload a file if it exists
|
// Upload a file if it exists
|
||||||
if msg.Extra != nil {
|
if msg.Extra != nil {
|
||||||
for _, rmsg := range helper.HandleExtra(&msg, b.General) {
|
for _, rmsg := range helper.HandleExtra(&msg, b.General) {
|
||||||
b.sc.PostMessage(channelID, rmsg.Username+rmsg.Text, np)
|
_, _, err = b.sc.PostMessage(channelInfo.ID, rmsg.Username+rmsg.Text, np)
|
||||||
|
if err != nil {
|
||||||
|
b.Log.Error(err)
|
||||||
}
|
}
|
||||||
// check if we have files to upload (from slack, telegram or mattermost)
|
|
||||||
if len(msg.Extra["file"]) > 0 {
|
|
||||||
b.handleUploadFile(&msg, channelID)
|
|
||||||
}
|
}
|
||||||
|
// Upload files if necessary (from Slack, Telegram or Mattermost).
|
||||||
|
b.handleUploadFile(&msg, channelInfo.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post normal message
|
// Post normal message
|
||||||
_, id, err := b.sc.PostMessage(channelID, msg.Text, np)
|
_, id, err := b.sc.PostMessage(channelInfo.ID, msg.Text, np)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@ -223,26 +262,36 @@ func (b *Bslack) Reload(cfg *bridge.Config) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bslack) createAttach(extra map[string][]interface{}) []slack.Attachment {
|
func (b *Bslack) createAttach(extra map[string][]interface{}) []slack.Attachment {
|
||||||
var attachs []slack.Attachment
|
var attachements []slack.Attachment
|
||||||
for _, v := range extra["attachments"] {
|
for _, v := range extra["attachments"] {
|
||||||
entry := v.(map[string]interface{})
|
entry := v.(map[string]interface{})
|
||||||
s := slack.Attachment{}
|
s := slack.Attachment{
|
||||||
s.Fallback = entry["fallback"].(string)
|
Fallback: extractStringField(entry, "fallback"),
|
||||||
s.Color = entry["color"].(string)
|
Color: extractStringField(entry, "color"),
|
||||||
s.Pretext = entry["pretext"].(string)
|
Pretext: extractStringField(entry, "pretext"),
|
||||||
s.AuthorName = entry["author_name"].(string)
|
AuthorName: extractStringField(entry, "author_name"),
|
||||||
s.AuthorLink = entry["author_link"].(string)
|
AuthorLink: extractStringField(entry, "author_link"),
|
||||||
s.AuthorIcon = entry["author_icon"].(string)
|
AuthorIcon: extractStringField(entry, "author_icon"),
|
||||||
s.Title = entry["title"].(string)
|
Title: extractStringField(entry, "title"),
|
||||||
s.TitleLink = entry["title_link"].(string)
|
TitleLink: extractStringField(entry, "title_link"),
|
||||||
s.Text = entry["text"].(string)
|
Text: extractStringField(entry, "text"),
|
||||||
s.ImageURL = entry["image_url"].(string)
|
ImageURL: extractStringField(entry, "image_url"),
|
||||||
s.ThumbURL = entry["thumb_url"].(string)
|
ThumbURL: extractStringField(entry, "thumb_url"),
|
||||||
s.Footer = entry["footer"].(string)
|
Footer: extractStringField(entry, "footer"),
|
||||||
s.FooterIcon = entry["footer_icon"].(string)
|
FooterIcon: extractStringField(entry, "footer_icon"),
|
||||||
attachs = append(attachs, s)
|
|
||||||
}
|
}
|
||||||
return attachs
|
attachements = append(attachements, s)
|
||||||
|
}
|
||||||
|
return attachements
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractStringField(data map[string]interface{}, field string) string {
|
||||||
|
if rawValue, found := data[field]; found {
|
||||||
|
if value, ok := rawValue.(string); ok {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// sendWebhook uses the configured WebhookURL to send the message
|
// sendWebhook uses the configured WebhookURL to send the message
|
||||||
@ -252,20 +301,26 @@ func (b *Bslack) sendWebhook(msg config.Message) (string, error) {
|
|||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.GetBool("PrefixMessagesWithNick") {
|
if b.GetBool(useNickPrefixConfig) {
|
||||||
msg.Text = msg.Username + msg.Text
|
msg.Text = msg.Username + msg.Text
|
||||||
}
|
}
|
||||||
|
|
||||||
if msg.Extra != nil {
|
if msg.Extra != nil {
|
||||||
// this sends a message only if we received a config.EVENT_FILE_FAILURE_SIZE
|
// this sends a message only if we received a config.EVENT_FILE_FAILURE_SIZE
|
||||||
for _, rmsg := range helper.HandleExtra(&msg, b.General) {
|
for _, rmsg := range helper.HandleExtra(&msg, b.General) {
|
||||||
iconURL := config.GetIconURL(&rmsg, b.GetString("iconurl"))
|
iconURL := config.GetIconURL(&rmsg, b.GetString(iconURLConfig))
|
||||||
matterMessage := matterhook.OMessage{IconURL: iconURL, Channel: msg.Channel, UserName: rmsg.Username, Text: rmsg.Text}
|
matterMessage := matterhook.OMessage{
|
||||||
b.mh.Send(matterMessage)
|
IconURL: iconURL,
|
||||||
|
Channel: msg.Channel,
|
||||||
|
UserName: rmsg.Username,
|
||||||
|
Text: rmsg.Text,
|
||||||
|
}
|
||||||
|
if err := b.mh.Send(matterMessage); err != nil {
|
||||||
|
b.Log.Errorf("Failed to send message: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// webhook doesn't support file uploads, so we add the url manually
|
// webhook doesn't support file uploads, so we add the url manually
|
||||||
if len(msg.Extra["file"]) > 0 {
|
|
||||||
for _, f := range msg.Extra["file"] {
|
for _, f := range msg.Extra["file"] {
|
||||||
fi := f.(config.FileInfo)
|
fi := f.(config.FileInfo)
|
||||||
if fi.URL != "" {
|
if fi.URL != "" {
|
||||||
@ -273,18 +328,21 @@ func (b *Bslack) sendWebhook(msg config.Message) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// if we have native slack_attachments add them
|
// if we have native slack_attachments add them
|
||||||
var attachs []slack.Attachment
|
var attachs []slack.Attachment
|
||||||
if len(msg.Extra["slack_attachment"]) > 0 {
|
for _, attach := range msg.Extra[sSlackAttachment] {
|
||||||
for _, attach := range msg.Extra["slack_attachment"] {
|
|
||||||
attachs = append(attachs, attach.([]slack.Attachment)...)
|
attachs = append(attachs, attach.([]slack.Attachment)...)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
iconURL := config.GetIconURL(&msg, b.GetString("iconurl"))
|
iconURL := config.GetIconURL(&msg, b.GetString(iconURLConfig))
|
||||||
matterMessage := matterhook.OMessage{IconURL: iconURL, Attachments: attachs, Channel: msg.Channel, UserName: msg.Username, Text: msg.Text}
|
matterMessage := matterhook.OMessage{
|
||||||
|
IconURL: iconURL,
|
||||||
|
Attachments: attachs,
|
||||||
|
Channel: msg.Channel,
|
||||||
|
UserName: msg.Username,
|
||||||
|
Text: msg.Text,
|
||||||
|
}
|
||||||
if msg.Avatar != "" {
|
if msg.Avatar != "" {
|
||||||
matterMessage.IconURL = msg.Avatar
|
matterMessage.IconURL = msg.Avatar
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user