
administrator.
AI_SECRET_KEY).@RBT#.curl -d '{"UserID":"@RBT#001","Nick":"MyRobot"}' "https://adminapisgp.im.qcloud.com/v4/openim_robot_http_svc/create_robot?sdkappid= {}&identifier=administrator&usersig={}&random=123456789&contenttype=json"
sdkappid={} and usersig={} in the command above with your SDKAppID and the UserSig generated based on the Tencent Chat key. For more information, see Generating UserSig. After you run the command in Linux, the Tencent server returns the following information:{"ActionStatus": "OK", "ErrorCode": 0, "ErrorInfo": ""}
@RBT#001 with the nickname MyRobot was created successfully.
user1 user sends the "hello" message to the chatbot @RBT#001.user1, message recipient @RBT#001, and message content hello.sendmsg for a one-to-one chat and API send_group_msg for a group chat) to send the reply message to user1 as @RBT#001.
/im URL that handles all requests sent to http://im. All webhook requests sent by Tencent Chat contain a CallbackCommand parameter, with different values representing different webhook commands. The handler performs processing according to the CallbackCommand parameter set by Tencent Chat.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": // Chatbot’s webhook command word for a one-to-one messagedealC2c(context.Background(), reqbody)rspbody = []byte("{\\"ActionStatus\\": \\"OK\\", \\"ErrorCode\\": 0, \\"ErrorInfo\\": \\"\\"}")default:rspbody = []byte("invalid CallbackCommand.")}w.Write(rspbody)}func main() { // Register a handler to process the webhook command sent to the application backendhttp.HandleFunc("/im", handler)http.ListenAndServe(":80", nil)}
askAI to request the AI service.func dealC2c(ctx context.Context, reqbody []byte) error {root, _ := simplejson.NewJson(reqbody)jFromAccount := root.Get("From_Account")fromAccount, _ = jFromAccount.String()// Check the sender's ID to avoid processing requests sent by one chatbot to another chatbot, which leads to infinite loops.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}
completion API that does not contain the context of the conversation, and you can see the MiniMax documentation for details on other APIs as needed.type MiniMaxRsp struct {Reply string `json:"reply"`}// Send a request to MiniMax and get a replyfunc 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) // Send the content replied by the AI service to the user}
sendmsg RESTful API of Tencent Chat to simulate the chatbot to reply to the user, specifying the sender of the message as @RBT#001 and the recipient as user1.// Send a RESTful API requestfunc 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)}// Call the RESTful API of Tencent Chat to reply to the userfunc reply(ctx context.Context, text string) {rsp := make(map[string]interface{})msgbody := []map[string]interface{}{{"MsgType": "TIMTextElem","MsgContent": map[string]interface{}{"Text": text},}}// For the implementation of `GenUserSig`, see the Tencent documentation.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))}

askAI function with the corresponding API call from that AI service provider. For group chat chatbots, only the implementation of the Bot.OnGroupMessage webhook command processing needs to be supplemented.Feedback