wework

package module
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2022 License: MIT Imports: 13 Imported by: 0

README

wework

golang企业微信sdk

特性

  • wework对象参数均可自定义修改
  • access token自动处理 (支持另起goroutine)
  • 支持插入handler方法去hook所有请求response(如需在handler内向其他服务发送消息建议使用goroutine)
  • 一个wework对象一个应用
  • 扩展接口极为方便
  • 可以使用IsWeworkError()方法判断返回的err是否为企业微信报错

示例

注: 使用New初始化时已自带返回错误码为 42001(token过期)/41001(token为空)/40014(token不合法)/-1(系统繁忙) 时的自动重试handler

package main

import (
	"log"
    
	"github.com/oxtiger/wework-sdk"
)

func exampleHandler(wx *wework.Client, api string, code int, data *[]byte) bool  {
	log.Printf("api_path: %s, errCode: %d, response: %b\n", api, code, data)
	if code != 0 {
		log.Fatalf("api response code: %d != 0\n", code)
		// retry this request
		return true
	}
	if api == wework.ApiUserSend {
		log.Printf("call user push api")
	}
	return false
}

func main()  {
	corpId := "id" // 企业ID
	corpSecret := "secret" // 企业secret
	var agentId int64 = 1 // "应用id"
	wx, err := wework.New(corpId, corpSecret, agentId)
	if err != nil {
		log.Fatalln(err)
	}
	// 增加自定义handler
	wx.Use(exampleHandler)
	// 设置handler返回true后的最大重试次数
	wx.SetRetry(3)

	invalidUser, err := wx.UserTextPush("user_id", "hello world")
	if err != nil {
		log.Fatalln(err)
	}
	if invalidUser != "" {
		log.Fatalf("failed to push message to: %s", invalidUser)
	}

	err = wx.ChatTextPush("chat_id", "hello world")
	if err != nil {
		log.Fatalln(err)
	}

	// 每小时更新一次token
	go wx.LoopUpdateToken()
}

Documentation

Index

Constants

View Source
const (
	ApiGetToken         = "/cgi-bin/gettoken"        // 获取token
	ApiGetUserByID      = "/cgi-bin/user/get"        // 获取用户信息
	ApiGetUsersByDeptID = "/cgi-bin/user/list"       // 获取用户列表
	ApiGetDept          = "/cgi-bin/department/list" // 获取部门列表
	ApiUserSend         = "/cgi-bin/message/send"    // 私信推送
	ApiChatSend         = "/cgi-bin/appchat/send"    // 群消息推送
	ApiCreateChat       = "/cgi-bin/appchat/create"  // 创建群聊
	ApiUpdateChat       = "/cgi-bin/appchat/update"  // 更新群聊
	ApiGetChat          = "/cgi-bin/appchat/get"     // 获取群聊详情
	ApiVerifyToken      = "/cgi-bin/menu/get"        // 获取应用菜单, 用来验证token有效性
)

非get即post

View Source
const (
	DefaultHost = "https://qyapi.weixin.qq.com"

	ErrorTokenExpired  = 42001 // 没有token
	ErrorTokenNotFound = 41001 // 没有token
	ErrorToken         = 40014 // token不合法
	ErrorSystemBusy    = -1    // 系统繁忙
)

企业微信错误码

Variables

This section is empty.

Functions

func IsWeworkError

func IsWeworkError(err interface{}) bool

func NewWeworkError

func NewWeworkError(format string, a ...interface{}) weworkError

func RobotPushFile added in v1.0.2

func RobotPushFile(robotId string, mediaId string) error

RobotPushFile 推送文件消息 robotId 机器人id mediaId 文件id

func RobotPushMarkdown

func RobotPushMarkdown(robotId string, content string) error

RobotPushMarkdown 推送markdown消息 robotId 机器人id content 消息内容 atUser 需要@的user_id

func RobotPushText

func RobotPushText(robotId string, content string, atUser ...string) error

RobotPushText 推送文本消息 robotId 机器人id content 消息内容 atUser 需要@的user_id

func RobotUploadFile added in v1.0.2

func RobotUploadFile(robotId, filepath, filename string) (string, error)

RobotUploadFile 上传文件至机器人空间, 返回media_id robotId 机器人id filename 文件路径

func SystemBusyHandler

func SystemBusyHandler(wx *Client, api string, code int, data *[]byte) bool

SystemBusyHandler 企业微信服务器繁忙重试

func TokenHandler

func TokenHandler(wx *Client, api string, code int, data *[]byte) bool

TokenHandler token异常则重新获取token并重试

Types

type ChatInfo

type ChatInfo struct {
	ChatId   string   `json:"chatid"`
	Name     string   `json:"name"`
	Owner    string   `json:"owner"`
	UserList []string `json:"userlist"`
}

ChatInfo 群聊详情

type ChatMarkdownMsg

type ChatMarkdownMsg struct {
	Markdown struct {
		Content string `json:"content"`
	} `json:"markdown"`
	// contains filtered or unexported fields
}

ChatMarkdownMsg 群聊Markdown消息推送参数

type ChatResponse

type ChatResponse struct {
	Errcode   int      `json:"errcode"`
	Errmsg    string   `json:"errmsg"`
	ChatInfos ChatInfo `json:"chat_info"`
}

ChatResponse chat api response

type ChatTextMsg

type ChatTextMsg struct {
	Text struct {
		Content string `json:"content"`
	} `json:"text"`
	// contains filtered or unexported fields
}

ChatTextMsg 群聊文本消息推送参数

type Client

type Client struct {
	Token tokenInfo // 应用token
	// contains filtered or unexported fields
}

Client 企业微信client

func New

func New(corpID, corpSecret string, agentID int64) (*Client, error)

New TODO 实现一个infof() errorf()标准logger interface New 初始化一个企业微信client

func (*Client) AllDept

func (wx *Client) AllDept() ([]Department, error)

AllDept 获取企业所有部门

func (*Client) ChatMarkdownPush

func (wx *Client) ChatMarkdownPush(ChatId, content string) error

ChatMarkdownPush 群聊Markdown消息推送

func (*Client) ChatTextPush

func (wx *Client) ChatTextPush(ChatId, content string) error

ChatTextPush 群聊文本消息推送

func (*Client) CreateChat

func (wx *Client) CreateChat(name, chatId string, users []string) error

CreateChat 创建群聊

func (*Client) DeptByID

func (wx *Client) DeptByID(departmentID string) ([]Department, error)

DeptByID 通过部门id获取部门详情

func (*Client) Get

func (wx *Client) Get(api string, params ...string) ([]byte, error)

Get get请求企微api

func (*Client) GetChat

func (wx *Client) GetChat(chatId string) (ChatInfo, error)

GetChat 获取群聊信息

func (*Client) LoopUpdateToken

func (wx *Client) LoopUpdateToken()

LoopUpdateToken 异步循环更新token

func (*Client) Post

func (wx *Client) Post(api string, data []byte) ([]byte, error)

Post post请求企微api

func (*Client) SetHost

func (wx *Client) SetHost(host string)

SetHost 设置企业微信api host

func (*Client) SetHttpClient

func (wx *Client) SetHttpClient(client *http.Client)

SetHttpClient 设置自定义的http client以支持更高级的姿势或兼容企业内部框架

func (*Client) SetRetry

func (wx *Client) SetRetry(reTry int) *Client

SetRetry 设置重试次数, handFunc返回重试的情况下最大可重试次数, 建议三次以内

func (*Client) UpdateChat

func (wx *Client) UpdateChat(name, chatId, owner string, addUsers, delUsers []string) error

UpdateChat 更新群聊

func (*Client) Use

func (wx *Client) Use(handlerFunc ...HandlerFunc) *Client

Use 增加返回错误码处理中间件

func (*Client) UserByID

func (wx *Client) UserByID(userID string) (UserDetail, error)

UserByID 通过user_id获取用户详情

func (*Client) UserMarkdownPush

func (wx *Client) UserMarkdownPush(users, content string) (string, error)

UserMarkdownPush 私信Markdown消息推送

func (*Client) UserTextPush

func (wx *Client) UserTextPush(users, content string) (string, error)

UserTextPush 私信文本消息推送

func (*Client) UsersByDeptID

func (wx *Client) UsersByDeptID(departmentID string) ([]UserDetail, error)

UsersByDeptID 通过部门id获取用户详情

type Department

type Department struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	NameEn   string `json:"name_en"`
	ParentID int    `json:"parentid"`
	Order    int    `json:"order"`
}

Department 部门详情

type DepartmentList

type DepartmentList struct {
	Errcode    int          `json:"errcode"`
	Errmsg     string       `json:"errmsg"`
	Department []Department `json:"department"`
}

DepartmentList 部门详情列表

type HandlerFunc

type HandlerFunc func(wx *Client, api string, code int, data *[]byte) bool

HandlerFunc api response 钩子函数

type HandlersChan

type HandlersChan []HandlerFunc

HandlersChan api response 钩子函数数组

type Result

type Result struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
	Error   error  `json:"-"`
}

Result 函数错误返回结构

func NewResult

func NewResult(errCode int, errMsg string, err error) *Result

type RobotFileMsg

type RobotFileMsg struct {
	MsgType string `json:"msgtype"`
	File    struct {
		MediaId string `json:"media_id"`
	} `json:"file"`
}

RobotFileMsg 推送文件

type RobotImageMsg

type RobotImageMsg struct {
	MsgType string `json:"msgtype"`
	Image   struct {
		Base64 string `json:"base64"` // 图片base64 不超过2M
		Md5    string `json:"md5"`
	} `json:"image"`
}

RobotImageMsg 推送图片消息

type RobotMarkdownMsg

type RobotMarkdownMsg struct {
	MsgType  string `json:"msgtype"`
	Markdown struct {
		Content string `json:"content"`
	} `json:"markdown"`
}

RobotMarkdownMsg 推送markdown消息

type RobotTextMsg

type RobotTextMsg struct {
	MsgType string `json:"msgtype"`
	Text    struct {
		Content             string   `json:"content"`
		MentionedList       []string `json:"mentioned_list"`
		MentionedMobileList []string `json:"mentioned_mobile_list"`
	} `json:"text"`
}

RobotTextMsg 推送文本消息

type RobotUploadResponse

type RobotUploadResponse struct {
	ErrCode   int    `json:"errcode"`
	ErrMsg    string `json:"errmsg"`
	Type      string `json:"type"`
	MediaId   string `json:"media_id"`
	CreatedAt string `json:"created_at"`
}

RobotUploadResponse 文件上传

type UserDetail

type UserDetail struct {
	ErrCode        int    `json:"errcode"`
	ErrMsg         string `json:"errmsg"`
	Userid         string `json:"userid" `
	Name           string `json:"name"`
	Department     []int  `json:"department"`
	Order          []int  `json:"order"`
	Position       string `json:"position"`
	Mobile         string `json:"mobile"`
	Gender         string `json:"gender"`
	Email          string `json:"email"`
	IsLeaderInDept []int  `json:"is_leader_in_dept"`
	Avatar         string `json:"avatar"`
	ThumbAvatar    string `json:"thumb_avatar"`
	Telephone      string `json:"telephone"`
	Alias          string `json:"alias"`
	Address        string `json:"address"`
	OpenUserid     string `json:"open_userid"`
	MainDepartment int    `json:"main_department"`
	ExtAttr        struct {
		Attrs []struct {
			Type int    `json:"type"`
			Name string `json:"name"`
			Text struct {
				Value string `json:"value"`
			} `json:"text,omitempty"`
			Web struct {
				Url   string `json:"url"`
				Title string `json:"title"`
			} `json:"web,omitempty"`
		} `json:"attrs"`
	} `json:"extattr"`
	Status           int    `json:"status"`
	QrCode           string `json:"qr_code"`
	ExternalPosition string `json:"external_position"`
	ExternalProfile  struct {
		ExternalCorpName string `json:"external_corp_name"`
		WechatChannels   struct {
			Nickname string `json:"nickname"`
			Status   int    `json:"status"`
		} `json:"wechat_channels"`
		ExternalAttr []struct {
			Type int    `json:"type"`
			Name string `json:"name"`
			Text struct {
				Value string `json:"value"`
			} `json:"text,omitempty"`
			Web struct {
				Url   string `json:"url"`
				Title string `json:"title"`
			} `json:"web,omitempty"`
			MiniProgram struct {
				Appid    string `json:"appid"`
				Pagepath string `json:"pagepath"`
				Title    string `json:"title"`
			} `json:"miniprogram,omitempty"`
		} `json:"external_attr"`
	} `json:"external_profile"`
}

UserDetail 用户详情

type UserListResponse

type UserListResponse struct {
	ErrCode  int          `json:"errcode"`
	ErrMsg   string       `json:"errmsg"`
	UserList []UserDetail `json:"userlist"`
}

UserListResponse 用户详情列表

type UserMarkdownMsg

type UserMarkdownMsg struct {
	Markdown struct {
		Content string `json:"content"`
	} `json:"markdown"`
	// contains filtered or unexported fields
}

UserMarkdownMsg 用户私信Markdown消息参数

type UserPushResponse

type UserPushResponse struct {
	ErrCode      int    `json:"errcode"`
	ErrMsg       string `json:"errmsg"`
	InvalidUser  string `json:"invaliduser"`
	InvalidParty string `json:"invalidparty"`
	InvalidTag   string `json:"invalidtag"`
	MsgId        string `json:"msgid"`
	ResponseCode string `json:"response_code"`
}

type UserTextMsg

type UserTextMsg struct {
	Text struct {
		Content string `json:"content"`
	} `json:"text"`
	// contains filtered or unexported fields
}

UserTextMsg 用户私信文本消息参数

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL