Search code examples
gomattermost

How Do You Send A Direct Message In Mattermost From A Bot Using The Go Driver?


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
    }

}

Solution

  • 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
        }
    
    }