curl -d '{"UserID":"@RBT#001","Nick":"MyRobot"}' "https://console.tim.qq.com/v4/openim_robot_http_svc/create_robot?sdkappid= {}&identifier=administrator&usersig={}&random=123456789&contenttype=json"
{"ActionStatus": "OK", "ErrorCode": 0, "ErrorInfo": ""}
http:///im
的请求都会被 handler 处理。所有云IM发送的回调请求都带有 CallbackCommand 参数,不同的值代表不同的回调命令。在 handler 中,根据云 IM 设置的参数 CallbackCommand 进行对应的处理。func handler(w http.ResponseWriter, r *http.Request) {command := r.URL.Query().Get("CallbackCommand")reqbody, _ := io.ReadAll(r.Body)var rspbody []byteswitch command {case "Bot.OnC2CMessage": // 机器人C2C回调命令字dealC2c(context.Background(), reqbody)rspbody = []byte("{\\"ActionStatus\\": \\"OK\\", \\"ErrorCode\\": 0, \\"ErrorInfo\\": \\"\\"}")default:rspbody = []byte("invalid CallbackCommand.")}w.Write(rspbody)}func main() { // 注册一个handler,处理发送给App后台的回调命令http.HandleFunc("/im", handler)http.ListenAndServe(":80", nil)}
func dealC2c(ctx context.Context, reqbody []byte) error {root, _ := simplejson.NewJson(reqbody)jFromAccount := root.Get("From_Account")fromAccount, _ = jFromAccount.String()// 检查发送方ID,不处理机器人发送给机器人的请求,防止无限循环if strings.HasPrefix(fromAccount, "@RBT#") {return nil}jToAccount := root.Get("To_Account")toAccount, _ := jToAccount.String()msgBodyList, _ := root.Get("MsgBody").Array()for _, m := range msgBodyList {msgBody, _ := m.(map[string]interface{})msgType, _ := msgBody["MsgType"].(string)if msgType != "TIMTextElem" {continue}msgContent, _ := msgBody["MsgContent"].(map[string]interface{})text, _ := msgContent["Text"].(string)ctx = context.WithValue(ctx, "from", fromAccount)ctx = context.WithValue(ctx, "to", toAccount)go askAI(ctx, text)}return nil}
type MiniMaxRsp struct {Reply string `json:"reply"`}// 请求MiniMax并得到回复func askAI(ctx context.Context, prompt string) {url := "https://api.minimax.chat/v1/text/completion"var reqData = []byte(`{"model": "abab5-completion","prompt": prompt}`)request, _ := http.NewRequest("POST", url, bytes.NewBuffer(reqData))request.Header.Set("Content-Type", "application/json; charset=UTF-8request.Header.Set("Authorization", API_SECRET_KEY)client := &http.Client{}response, _ := client.Do(request)defer response.Body.Close()body, _ := ioutil.ReadAll(response.Body)rsp := &MiniMaxRsp{}json.Unmarshal(body, rsp)reply(ctx, rsp.Reply) // 将AI回复的内容发送给用户}
// 发送一个REST API请求func doRestAPI(host string, sdkappid int, admin, usersig, command, body string) {url := fmt.Sprintf("https://%s/v4/%s?sdkappid=%d&identifier=%s&usersig=%s&random=%d&contenttype=json",host, command, sdkappid, admin, usersig, rand.Uint32())req, _ := http.NewRequest("POST", url, bytes.NewBufferString(body))req.Header.Set("Content-Type", "application/json")cli := &http.Client{}rsp, err := cli.Do(req)if err != nil {log.Printf("REST API failed. %s", err.Error())return}defer rsp.Body.Close()rsptext, _ := io.ReadAll(rsp.Body)log.Printf("rsp:%s", rsptext)}// 调用腾讯云IM的REST API,回复用户func reply(ctx context.Context, text string) {rsp := make(map[string]interface{})msgbody := []map[string]interface{}{{"MsgType": "TIMTextElem","MsgContent": map[string]interface{}{"Text": text},}}// GenUserSig 的实现可以参考腾讯云文档usersig, _ := GenUserSig(IM_SDKAPPID, IM_KEY, "administrator", 60)rsp["From_Account"] = ctx.Value("to").(string) //"@RBT#001"rsp["To_Account"] = ctx.Value("from").(string)rsp["SyncOtherMachine"] = 2rsp["MsgLifeTime"] = 60 * 60 * 24 * 7rsp["MsgSeq"] = rand.Uint32()rsp["MsgRandom"] = rand.Uint32()rsp["MsgBody"] = msgbodyrspbody, _ := json.Marshal(rsp)doRestAPI("console.tim.qq.com", IM_SDKAPPID, "administrator", usersig, "openim/sendmsg", string(rspbody))}
本页内容是否解决了您的问题?