github.com/872409/go-netease-im@v1.0.2-0.20201109080841-fdb3e13691c5/broadcast.go (about) 1 package netease 2 3 import ( 4 "encoding/json" 5 "errors" 6 "strconv" 7 8 jsoniter "github.com/json-iterator/go" 9 ) 10 11 const ( 12 broadcastMessagePoint = neteaseBaseURL + "/msg/broadcastMsg.action" 13 ) 14 15 // BroadcastResult 广播推送结果 16 type BroadcastResult struct { 17 BroadcastID int64 `json:"broadcastId"` 18 ExpireTime int64 `json:"expireTime"` 19 Body string `json:"body"` 20 CreateTime int64 `json:"createTime"` 21 IsOffline bool `json:"isOffline"` 22 TargetOs []string `json:"targetOs"` 23 } 24 25 // BroadcastMsg 发送广播消息 26 /* 27 * *广播消息,可以对应用内的所有用户发送广播消息,广播消息目前暂不支持第三方推送(APNS、小米、华为等) 28 * *广播消息支持离线存储,并可以自定义设置离线存储的有效期,最多保留最近100条离线广播消息 29 * *此接口受频率控制,一个应用一分钟最多调用10次,一天最多调用1000次,超过会返回416状态码 30 * @param body 广播消息内容,最大4096字符 31 * @param fromID(可选) 发送者accid, 用户帐号,最大长度32字符,必须保证一个APP内唯一 32 * @param isOffline(可选) 是否存离线,true或false,默认false 33 * @param targetOs(可选) 目标客户端,默认所有客户端,"ios","aos","pc","web","mac" 34 */ 35 func (c *ImClient) BroadcastMsg(body, fromID string, isOffline *bool, targetOs []string) (msgs *BroadcastResult, err error) { 36 param := map[string]string{"body": body} 37 38 if len(fromID) > 0 { 39 param["from"] = fromID 40 } 41 if isOffline != nil { 42 param["isOffline"] = strconv.FormatBool(*isOffline) 43 } 44 if len(targetOs) > 0 { 45 if param["targetOs"], err = jsonTool.MarshalToString(targetOs); err != nil { 46 return nil, err 47 } 48 } 49 50 client := c.client.R() 51 c.setCommonHead(client) 52 client.SetFormData(param) 53 54 resp, err := client.Post(broadcastMessagePoint) 55 56 var jsonRes map[string]*json.RawMessage 57 err = jsoniter.Unmarshal(resp.Body(), &jsonRes) 58 if err != nil { 59 return nil, err 60 } 61 62 var code int 63 err = json.Unmarshal(*jsonRes["code"], &code) 64 if err != nil { 65 return nil, err 66 } 67 68 if code != 200 { 69 return nil, errors.New(string(resp.Body())) 70 } 71 72 msgs = &BroadcastResult{} 73 err = jsoniter.Unmarshal(*jsonRes["msg"], msgs) 74 if err != nil { 75 return nil, err 76 } 77 78 return msgs, nil 79 }