2

Using Mattermost's Go Driver, is it possible to send a Direct Message from a bot account to a user? I have been trying this method below, but I keep getting the error: "You do not have the appropriate permissions.," I've checked the permissions of the bot multiple times, and it should be able to send the message. I've confirmed that it can also send the message to public channels, so what am I doing wrong?

package main

import (
    "github.com/mattermost/mattermost-server/v5/model"
)

func main() {

    client := model.NewAPIv4Client("https://server.name.here")
    client.SetToken("Bots-Token-Here")
    bot, resp := client.GetUserByUsername("NameOf.BotSendingMessage", "")
    if resp.Error != nil {
        return
    }

    user, resp := client.GetUserByUsername("UsernameOf.UserToMessage", "")
    if resp.Error != nil {
        return
    }

    channelId := model.GetDMNameFromIds(bot.Id, user.Id)

    post := &model.Post{}
    post.ChannelId = channelId
    post.Message = "some message"

    if _, resp := client.CreatePost(post); resp.Error != nil {
        return
    }

}
Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28

1 Answers1

1

It is possible, but you have to create the channel, not just the Channel ID. The snippet that does this looks like this:

channel, resp := client.CreateDirectChannel("firstId", "secondId")
if resp.Error != nil {
    return
}

A working version of the code can be seen here:

package main

import (
    "github.com/mattermost/mattermost-server/v5/model"
)

func main() {

    client := model.NewAPIv4Client("https://server.name.here")
    client.SetToken("Bots-Token-Here")
    bot, resp := client.GetUserByUsername("NameOf.BotSendingMessage", "")
    if resp.Error != nil {
        return
    }

    user, resp := client.GetUserByUsername("UsernameOf.UserToMessage", "")
    if resp.Error != nil {
        return
    }

    channel, resp := client.CreateDirectChannel(bot.Id, user.Id)
    if resp.Error != nil {
        return
    }
    post := &model.Post{}
    post.ChannelId = channel.Id
    post.Message = "some message"

    if _, resp := client.CreatePost(post); resp.Error != nil {
        return
    }

}
Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
  • Can you help me please in similar question, can't send message to user https://stackoverflow.com/questions/75566584/sending-message-from-mattermost-golang-bot-to-any-user – mocart Feb 26 '23 at 10:56