您如何使用 Go 驱动程序从机器人发送 Mattermost 中的直接消息?

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

使用 Mattermost 的 Go 驱动程序,是否可以从机器人帐户向用户发送直接消息?我一直在尝试下面的这种方法,但我一直收到错误:“您没有适当的权限。”我已经多次检查了机器人的权限,它应该能够发送消息。我已经确认它也可以将消息发送到 public 个频道,所以我做错了什么?

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
    }

}

可以,但您必须创建频道,而不仅仅是频道 ID。执行此操作的代码段如下所示:

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

可以在此处查看代码的工作版本:

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
    }

}