[原创]Golang一行代码给钉钉群推送消息

[原创]Golang一行代码给钉钉群推送消息

钉钉本来就是工具,只是boss把你变成了工具. — 麦·卡隆

今天朋友扔给我个某签到脚本,让我做推送功能.

我迅速从吃灰收藏夹里掏出Sever酱,结果...似乎它经历了一些可怕的事情...

总之,每天推送最多5条.

(咱也不差这几个money,买个会员支持一下呗)

为了照顾互联网最大帮派白嫖党,我决定再找一个新的解决方案.


需求:

  1. 主流平台推送
  2. 直接调用
  3. 兼容各种平台
  4. 甲方满意

经过伟大的一番科学发现,终于让我找到合适的解决方案.

最终选择:钉钉群聊机器人

参考钉钉官方文档:https://developers.dingtalk.com/document/robots/custom-robot-access

发现是纯API调用,直接POST万事大吉.

第一步 创建并获取自定义机器人Webhook

(以下文字Copy官方文档)

  1. 选择需要添加机器人的群聊,然后依次单击群设置 > 智能群助手。

image

  1. 在机器人管理页面选择自定义机器人,输入机器人名字并选择要发送消息的群,同时可以为机器人设置机器人头像。
    image

  2. 完成必要的安全设置,勾选我已阅读并同意《自定义机器人服务及免责条款》,然后单击完成。
    image
    (我还没写完密钥方式发送的代码,可以先用着别人的包)

  3. 完成安全设置后,复制出机器人的Webhook地址,可用于向这个群发送消息,格式如下:

https://oapi.dingtalk.com/robot/send?access_token=XXXXXX
然后,我决定用Golang写个史诗级懒人调用包

第二步 写DingBot包

第一步,Goland直接一键导入全部json转结构体:

点击查看神必代码
package dingbot

// Text 文本json
type dText struct {
	At struct {
		AtMobiles []string `json:"atMobiles"`
		AtUserIds []string `json:"atUserIds"`
		IsAtAll   bool     `json:"isAtAll"`
	} `json:"at"`
	Text struct {
		Content string `json:"content"`
	} `json:"text"`
	Msgtype string `json:"msgtype"`
}

//Link Link型json
type dLink struct {
	Msgtype string `json:"msgtype"`
	Link    struct {
		Text       string `json:"text"`
		Title      string `json:"title"`
		PicUrl     string `json:"picUrl"`
		MessageUrl string `json:"messageUrl"`
	} `json:"link"`
}

//MD Markdown型json
type dMD struct {
	Msgtype  string `json:"msgtype"`
	Markdown struct {
		Title string `json:"title"`
		Text  string `json:"text"`
	} `json:"markdown"`
	At struct {
		AtMobiles []string `json:"atMobiles"`
		AtUserIds []string `json:"atUserIds"`
		IsAtAll   bool     `json:"isAtAll"`
	} `json:"at"`
}

// AActionCard 整体跳转ActionCard类型
type dAActionCard struct {
	ActionCard struct {
		Title          string `json:"title"`
		Text           string `json:"text"`
		BtnOrientation string `json:"btnOrientation"`
		SingleTitle    string `json:"singleTitle"`
		SingleURL      string `json:"singleURL"`
	} `json:"actionCard"`
	Msgtype string `json:"msgtype"`
}

// DActionCard 独立跳转ActionCard类型
type dDActionCard struct {
	Msgtype    string `json:"msgtype"`
	ActionCard struct {
		Title          string `json:"title"`
		Text           string `json:"text"`
		BtnOrientation string `json:"btnOrientation"`
		Btns           []struct {
			Title     string `json:"title"`
			ActionURL string `json:"actionURL"`
		} `json:"btns"`
	} `json:"actionCard"`
}

// FeedCard FeedCard类型
type dFeedCard struct {
	Msgtype  string `json:"msgtype"`
	FeedCard struct {
		Links []struct {
			Title      string `json:"title"`
			MessageURL string `json:"messageURL"`
			PicURL     string `json:"picURL"`
		} `json:"links"`
	} `json:"feedCard"`
}

// ErrorReport 返回的错误
type dErrorReport struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

可以非常清楚的看到机器人一共有6种(准确说是5种)方式发送消息.

然后,用最蠢方式再Copy个Post代码:

点击查看更神必的代码
package dingbot

// from https://github.com/CatchZeng/dingtalk

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const httpTimoutSecond = time.Duration(30) * time.Second

func send(message []byte, pushURL string) (*dErrorReport, error) {
	res := &dErrorReport{}

	reqBytes := message

	req, err := http.NewRequest(http.MethodPost, pushURL, bytes.NewReader(reqBytes))
	if err != nil {
		return res, err
	}
	req.Header.Add("Accept-Charset", "utf8")
	req.Header.Add("Content-Type", "application/json")

	client := new(http.Client)
	client.Timeout = httpTimoutSecond
	resp, err := client.Do(req)
	if err != nil {
		return res, err
	}
	defer resp.Body.Close()

	resultByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return res, err
	}

	err = json.Unmarshal(resultByte, &res)
	if err != nil {
		return res, fmt.Errorf("unmarshal http response body from json error = %w", err)
	}

	if res.Errcode != 0 {
		return res, fmt.Errorf("send message to dingtalk error = %s", res.Errmsg)
	}

	return res, nil
}

感谢前辈CatchZeng的Dingtalk包.

最后,闭眼写个函数实现:

const URL = "https://oapi.dingtalk.com/robot/send?access_token="

// Text 推送文本
func Text(token string, content string, AtMobiles []string, AtUserIds []string, IsAtAll bool) error {
	t := new(dText)
	t.Text = struct {
		Content string `json:"content"`
	}(struct{ Content string }{Content: content})
	t.At = struct {
		AtMobiles []string `json:"atMobiles"`
		AtUserIds []string `json:"atUserIds"`
		IsAtAll   bool     `json:"isAtAll"`
	}(struct {
		AtMobiles []string
		AtUserIds []string
		IsAtAll   bool
	}{AtMobiles: AtMobiles, AtUserIds: AtUserIds, IsAtAll: IsAtAll})
	t.Msgtype = "text"
	if jsonByte, err := json.Marshal(t); err != nil {
		return err
	} else if _, err := send(jsonByte, URL+token); err != nil {
		return err
	}
	return nil

大功告成!来试试一行代码调用

//func Text(token string, content string, AtMobiles []string, AtUserIds []string, IsAtAll bool) error
dingbot.Text("123","hello",[]string{},[]string{},false)

效果还是很不错的
image
image

因为我的钉钉里有一些不可描述的东西,这次就不截图啦!

源码地址:https://github.com/EldersJavas/EsDingTalkBot_Go

Go文档:https://pkg.go.dev/github.com/EldersJavas/EsDingTalkBot_Go

作者:麦卡隆
转载带上链接哦!

posted @ 2021-09-20 16:07  Maicarons  阅读(719)  评论(0编辑  收藏  举报
商务邮箱:maicarons#outlook.com