From 514688e72b83bb0231be3bbecc7943a10055ccc3 Mon Sep 17 00:00:00 2001 From: Balakrishnan Balasubramanian Date: Sun, 25 Dec 2022 13:40:40 -0500 Subject: [PATCH] some cleanup --- main.go | 63 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/main.go b/main.go index 582a5ba..1942e82 100644 --- a/main.go +++ b/main.go @@ -50,7 +50,8 @@ func main() { } if update.Message != nil { - go sendButtonAndDelete(update.Message.Chat.ID, update.Message.ID, update.Message.Text) + go sendButton(update.Message.Chat.ID, update.Message.ID, update.Message.Text) + go DeleteMessage(update.Message.Chat.ID, update.Message.ID) } else if update.CallbackQuery != nil { go markButtonChecked(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Message.ID, update.CallbackQuery.Data) go answerCallbackQuery(update.CallbackQuery.ID) @@ -86,12 +87,7 @@ func markButtonChecked(chatID int, messageID int, text string) { log.Println(err) return } - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Println(err) - return - } - log.Println(string(body)) + logBody(resp.Body) } func answerCallbackQuery(callbackQueryID string) { @@ -101,27 +97,25 @@ func answerCallbackQuery(callbackQueryID string) { log.Println(err) return } - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Println(err) - return - } - log.Println(string(body)) + logBody(resp.Body) } -func sendButtonAndDelete(chatID int, messageID int, text string) { +func sendButton(chatID int, messageID int, text string) { url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", apiToken) sendMsgFmt := ` { - "chat_id": "%d", - "text": "ok", - "reply_markup": { - "inline_keyboard": [[ - { - "text": "%s", - "callback_data": "%s" - } - ]] + "chat_id": "%d", + "text": "ok", + "reply_markup": { + "inline_keyboard": [ + [ + { + "text": "%s", + "callback_data": "%s" + } + ] + ] + } } ` sendMsgReq := fmt.Sprintf(sendMsgFmt, chatID, text, text) @@ -130,19 +124,26 @@ func sendButtonAndDelete(chatID int, messageID int, text string) { log.Println(err) return } - body, err := io.ReadAll(resp.Body) - if err != nil { - log.Println(err) - return - } - log.Println(string(body)) + logBody(resp.Body) +} +func DeleteMessage(chatID int, messageID int) { deleteUrl := fmt.Sprintf("https://api.telegram.org/bot%s/deleteMessage?chat_id=%d&message_id=%d", apiToken, chatID, messageID) - resp, err = http.Get(deleteUrl) + resp, err := http.Get(deleteUrl) if err != nil { log.Println(err) return } - body, err = io.ReadAll(resp.Body) + logBody(resp.Body) +} + +func logBody(respBody io.ReadCloser) { + defer func() { + err := respBody.Close() + if err != nil { + log.Println(err) + } + }() + body, err := io.ReadAll(respBody) if err != nil { log.Println(err) return