From e726a4fe011447b605ca1a8af94fd80e1826648b Mon Sep 17 00:00:00 2001 From: Balakrishnan Balasubramanian Date: Wed, 28 Dec 2022 13:59:06 -0500 Subject: [PATCH] Save MessageID from send response --- main.go | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/main.go b/main.go index 474211e..d0682f3 100644 --- a/main.go +++ b/main.go @@ -143,11 +143,29 @@ func handleTextAdded(gl *glist.GList, text string) { gl.Mutex.Lock() defer gl.Mutex.Unlock() if count == gl.AllMsgCounter { - sendList(gl, "sendMessage") + resp := sendList(gl, "sendMessage") + if resp == nil { + return + } + response := struct { + Ok bool `json:"ok"` + Result struct { + MessageID int `json:"message_id"` + } `json:"result"` + }{} + if err := json.Unmarshal(resp, &response); err != nil { + log.Println(err) + return + } + if !response.Ok { + log.Println("not ok") + return + } + if gl.MessageID != nil { deleteMessage(gl.ChatID, *gl.MessageID) - gl.MessageID = nil } + gl.MessageID = &response.Result.MessageID } }) } @@ -171,19 +189,19 @@ func handleButtonClick(gl *glist.GList, messageID int, text string) { } } -func sendList(gl *glist.GList, method string) { +func sendList(gl *glist.GList, method string) []byte { url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", apiToken, method) sendMsgReq, err := gl.GenSendListReq() if err != nil { log.Println(err) - return + return nil } resp, err := http.Post(url, "application/json", bytes.NewReader(sendMsgReq)) if err != nil { log.Println(err) - return + return nil } - logBody(resp.Body) + return logBody(resp.Body) } func answerCallbackQuery(callbackQueryID string) { @@ -206,7 +224,7 @@ func deleteMessage(chatID int, messageID int) { logBody(resp.Body) } -func logBody(respBody io.ReadCloser) { +func logBody(respBody io.ReadCloser) []byte { defer func() { err := respBody.Close() if err != nil { @@ -216,9 +234,10 @@ func logBody(respBody io.ReadCloser) { body, err := io.ReadAll(respBody) if err != nil { log.Println(err) - return + return nil } log.Println(string(body)) + return body } func loadData(dataPath string, chats *sync.Map) error {