From 7be913579de4c87e41b2008deff8777494f538f0 Mon Sep 17 00:00:00 2001 From: totanvix Date: Wed, 5 Jul 2023 16:03:58 +0000 Subject: [PATCH] refactor: refactor all commands --- api/hook/index.go | 5 +- utils/bitcoin/bitcoin.go | 19 +- utils/bot/bot.go | 73 ++------ utils/bot/reply.go | 195 +++++++++++++++++++++ utils/{kqxs/kqxs.go => lottery/lottery.go} | 36 ++-- utils/lunar/lunar.go | 35 ++-- utils/qr/qr.go | 19 +- utils/quote/quote.go | 16 +- utils/random/random.go | 32 ---- utils/shortener/shortener.go | 26 +-- utils/telegram/telegram.go | 18 +- utils/weather/weather.go | 40 +---- 12 files changed, 270 insertions(+), 244 deletions(-) create mode 100644 utils/bot/reply.go rename utils/{kqxs/kqxs.go => lottery/lottery.go} (50%) delete mode 100644 utils/random/random.go diff --git a/api/hook/index.go b/api/hook/index.go index 3ae04b6..3aad416 100644 --- a/api/hook/index.go +++ b/api/hook/index.go @@ -5,6 +5,7 @@ import ( "net/http" "zeril-bot/utils/bot" "zeril-bot/utils/structs" + "zeril-bot/utils/telegram" ) func Handler(w http.ResponseWriter, r *http.Request) { @@ -14,7 +15,9 @@ func Handler(w http.ResponseWriter, r *http.Request) { panic(err) } - bot := bot.NewBot(data) + telegram := telegram.New(&http.Client{}) + + bot := bot.NewBot(telegram, data) res := make(map[string]string) err = bot.ResolveHook() diff --git a/utils/bitcoin/bitcoin.go b/utils/bitcoin/bitcoin.go index bbd649d..916559d 100644 --- a/utils/bitcoin/bitcoin.go +++ b/utils/bitcoin/bitcoin.go @@ -7,41 +7,36 @@ import ( "net/http" "strconv" "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" "github.com/leekchan/accounting" ) -func SendBitcoinPrice(data structs.DataTele) error { +func GetBitcoinPrice() (string, error) { acUsd := accounting.Accounting{Symbol: "$", Precision: 2} acVnd := accounting.Accounting{Symbol: "", Precision: 0, Thousand: "."} - btc, err := getBitcoinPrice() + btc, err := getCurrentPrice() if err != nil { - return err + return "", err } p, err := strconv.ParseFloat(btc.Price, 64) if err != nil { - return err + return "", err } usd := acUsd.FormatMoney(p) v, err := exchangeUsdToVnd(p) if err != nil { - return err + return "", err } vnd := acVnd.FormatMoney(*v) + " đ" - message := fmt.Sprintf("1 Bitcoin = %s (%s)", usd, vnd) - - data.ReplyMessage = message - - return telegram.SendMessage(data) + return fmt.Sprintf("1 Bitcoin = %s (%s)", usd, vnd), nil } -func getBitcoinPrice() (*structs.Btc, error) { +func getCurrentPrice() (*structs.Btc, error) { res, err := http.Get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT") if err != nil { return nil, err diff --git a/utils/bot/bot.go b/utils/bot/bot.go index 7900654..34ffdfd 100644 --- a/utils/bot/bot.go +++ b/utils/bot/bot.go @@ -2,26 +2,18 @@ package bot import ( "errors" - "fmt" "log" "strings" "time" - "zeril-bot/utils/bitcoin" - "zeril-bot/utils/kqxs" - "zeril-bot/utils/lunar" - "zeril-bot/utils/qr" - "zeril-bot/utils/quote" - "zeril-bot/utils/random" - "zeril-bot/utils/shortener" "zeril-bot/utils/structs" "zeril-bot/utils/telegram" - "zeril-bot/utils/weather" ) type Bot struct { HookData structs.HookData rCh chan rChannel + Telegram *telegram.Telegram } type rChannel struct { @@ -30,9 +22,9 @@ type rChannel struct { const numberOfCh = 2 -func NewBot(hookData structs.HookData) *Bot { +func NewBot(telegram *telegram.Telegram, hookData structs.HookData) *Bot { ch := make(chan rChannel, numberOfCh) - return &Bot{HookData: hookData, rCh: ch} + return &Bot{Telegram: telegram, HookData: hookData, rCh: ch} } func (b Bot) ResolveHook() error { @@ -102,23 +94,23 @@ func (b Bot) resolveCommand() error { case "/help", "/help@zerill_bot": err = b.sendHelpMessage(data) case "/quote", "/quote@zerill_bot": - err = quote.SendAQuote(data) + err = b.sendAQuote(data) case "/groupid", "/groupid@zerill_bot": err = b.sendGroupId(data) case "/lunar", "/lunar@zerill_bot": - err = lunar.SendLunarDateNow(data) + err = b.sendLunarDateNow(data) case "/weather", "/weather@zerill_bot": - err = weather.SendForecastOfWeather(data) + err = b.sendForecastOfWeather(data) case "/bitcoin", "/bitcoin@zerill_bot": - err = bitcoin.SendBitcoinPrice(data) + err = b.sendBitcoinPrice(data) case "/qr", "/qr@zerill_bot": - err = qr.SendQRImage(data) + err = b.sendQRImage(data) case "/random", "/random@zerill_bot": - err = random.RandomElements(data) + err = b.sendSelectedElement(data) case "/kqxs", "/kqxs@zerill_bot": - err = kqxs.Send(data) + err = b.sendLottery(data) case "/shortener", "/shortener@zerill_bot": - shortener.Generate(data) + err = b.generateShortenerURL(data) default: err = b.invalidCommand(data) } @@ -131,16 +123,15 @@ func (b Bot) resolveCallbackCommand() error { defer func() { b.rCh <- rChannel{err: err} - close(b.rCh) }() data := b.getTelegramData() switch data.Command { case "/weather": - err = weather.SendForecastOfWeather(data) + err = b.sendForecastOfWeather(data) case "/kqxs": - err = kqxs.Send(data) + err = b.sendLottery(data) } return err @@ -203,44 +194,6 @@ func (b Bot) getFirstName() string { return b.HookData.Message.From.FirstName } -func (b Bot) sendStartMessage(data structs.DataTele) error { - message := fmt.Sprintf("Xin chào %s \n\nGõ /help để xem danh sách các lệnh mà bot hỗ trợ nhé.\n\nBạn cũng có thể truy cập nhanh các chức năng bằng cách nhấn nút Menu bên dưới.", data.FirstName) - data.ReplyMessage = message - return telegram.SendMessage(data) -} - -func (b Bot) sendHelpMessage(data structs.DataTele) error { - messages := "" - botCommands, err := b.getBotCommands() - - if err != nil { - return err - } - - for _, command := range botCommands.Result { - messages += fmt.Sprintf("/%s - %s\n\n", command.Command, command.Description) - } - - data.ReplyMessage = messages - - return telegram.SendMessage(data) -} - func (b Bot) getBotCommands() (*structs.BotCommands, error) { return telegram.GetBotCommands() } - -func (b Bot) sendGroupId(data structs.DataTele) error { - if data.ChatType == "group" { - data.ReplyMessage = fmt.Sprintf("Group ID: %v", data.ChatId) - } else { - data.ReplyMessage = "Không tìm thấy nhóm, bạn cần thêm bot vào nhóm trước khi thực hiện lệnh này !" - } - - return telegram.SendMessage(data) -} - -func (b Bot) invalidCommand(data structs.DataTele) error { - data.ReplyMessage = "Tôi không hiểu câu lệnh của bạn !!!" - return telegram.SendMessage(data) -} diff --git a/utils/bot/reply.go b/utils/bot/reply.go new file mode 100644 index 0000000..c9296c6 --- /dev/null +++ b/utils/bot/reply.go @@ -0,0 +1,195 @@ +package bot + +import ( + "fmt" + "math/rand" + "strings" + "unicode" + "zeril-bot/utils/bitcoin" + "zeril-bot/utils/lottery" + "zeril-bot/utils/lunar" + "zeril-bot/utils/qr" + "zeril-bot/utils/quote" + "zeril-bot/utils/shortener" + "zeril-bot/utils/structs" + "zeril-bot/utils/weather" +) + +func (b Bot) sendStartMessage(data structs.DataTele) error { + message := fmt.Sprintf("Xin chào %s \n\nGõ /help để xem danh sách các lệnh mà bot hỗ trợ nhé.\n\nBạn cũng có thể truy cập nhanh các chức năng bằng cách nhấn nút Menu bên dưới.", data.FirstName) + data.ReplyMessage = message + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendHelpMessage(data structs.DataTele) error { + messages := "" + botCommands, err := b.getBotCommands() + + if err != nil { + return err + } + + for _, command := range botCommands.Result { + messages += fmt.Sprintf("/%s - %s\n\n", command.Command, command.Description) + } + + data.ReplyMessage = messages + + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendGroupId(data structs.DataTele) error { + if data.ChatType == "group" { + data.ReplyMessage = fmt.Sprintf("Group ID: %v", data.ChatId) + } else { + data.ReplyMessage = "Không tìm thấy nhóm, bạn cần thêm bot vào nhóm trước khi thực hiện lệnh này !" + } + + return b.Telegram.SendMessage(data) +} + +func (b Bot) invalidCommand(data structs.DataTele) error { + data.ReplyMessage = "Tôi không hiểu câu lệnh của bạn !!!" + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendAQuote(data structs.DataTele) error { + quote, err := quote.GetAQuote() + if err != nil { + return err + } + + quoteFormat := fmt.Sprintf(""%s" - %s", quote.Quote, quote.Author) + data.ReplyMessage = quoteFormat + + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendLunarDateNow(data structs.DataTele) error { + path, err := lunar.DownloadAndCropImage() + if err != nil { + return err + } + + return b.Telegram.SendPhoto(data, path) +} + +func (b Bot) sendForecastOfWeather(data structs.DataTele) error { + text := data.RawMessage + text = strings.TrimSpace(text) + arr := strings.Fields(text) + args := arr[1:] + + if len(args) == 0 { + message, buttons := weather.GetSuggestForecast(data) + data.ReplyMessage = message + return b.Telegram.SendMessageWithReplyMarkup(data, buttons) + } + + cityName := text[9:] + wData, err := weather.GetWeather(cityName) + if err != nil { + data.ReplyMessage = "Không tìm thấy thông tin thời tiết" + return b.Telegram.SendMessage(data) + } + + data.ReplyMessage = fmt.Sprintf("🏙 Thời tiết hiện tại ở %s\n\n🌡 Nhiệt độ: %.2f°C\n\n💧 Độ ẩm: %v%\n\nℹ️ Tổng quan: %s", wData.Name, wData.Main.Temp, wData.Main.Humidity, wData.Weather[0].Description) + + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendBitcoinPrice(data structs.DataTele) error { + message, err := bitcoin.GetBitcoinPrice() + if err != nil { + return err + } + + data.ReplyMessage = message + + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendQRImage(data structs.DataTele) error { + text := data.RawMessage + arr := strings.Fields(text) + args := arr[1:] + if len(args) == 0 { + data.ReplyMessage = "Sử dụng cú pháp /qr nội dung để tạo mã QR." + return b.Telegram.SendMessage(data) + } + + content := text[4:] + path, err := qr.CreateImage(content) + if err != nil { + return err + } + + return b.Telegram.SendPhoto(data, path) +} + +func (b Bot) sendSelectedElement(data structs.DataTele) error { + text := data.RawMessage + arr := strings.Fields(text) + + if len(arr[1:]) == 0 { + data.ReplyMessage = "Sử dụng cú pháp /random A, B, C để chọn phần tử ngẫu nhiên" + return b.Telegram.SendMessage(data) + + } + + f := func(c rune) bool { + return unicode.IsPunct(c) == unicode.IsPunct(',') + } + + els := strings.FieldsFunc(text[8:], f) + el := els[rand.Intn(len(els))] + + data.ReplyMessage = fmt.Sprintf("Phần từ được chọn sau khi random: %v", strings.TrimSpace(el)) + + return b.Telegram.SendMessage(data) +} + +func (b Bot) sendLottery(data structs.DataTele) error { + text := data.RawMessage + text = strings.TrimSpace(text) + arr := strings.Fields(text) + args := arr[1:] + + if len(args) != 1 { + message, buttons := lottery.GetSuggest(data) + data.ReplyMessage = message + return b.Telegram.SendMessageWithReplyMarkup(data, buttons) + } + + zone := text[6:] + + message, err := lottery.GetDataLottery(zone) + if err != nil { + return err + } + + data.ReplyMessage = message + + return b.Telegram.SendMessage(data) +} + +func (b Bot) generateShortenerURL(data structs.DataTele) error { + text := data.RawMessage + arr := strings.Fields(text) + args := arr[1:] + + if len(args) == 0 { + data.ReplyMessage = "Sử dụng cú pháp /shortener https://example.com/ để tạo rút gọn liên kết" + return b.Telegram.SendMessage(data) + } + + url := text[11:] + message, err := shortener.Generate(url) + if err != nil { + return err + } + + data.ReplyMessage = message + + return b.Telegram.SendMessage(data) +} diff --git a/utils/kqxs/kqxs.go b/utils/lottery/lottery.go similarity index 50% rename from utils/kqxs/kqxs.go rename to utils/lottery/lottery.go index 323f176..dad6883 100644 --- a/utils/kqxs/kqxs.go +++ b/utils/lottery/lottery.go @@ -1,31 +1,22 @@ -package kqxs +package lottery import ( "fmt" "strings" "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" "github.com/mmcdole/gofeed" ) -func Send(data structs.DataTele) error { - text := data.RawMessage - text = strings.TrimSpace(text) - arr := strings.Fields(text) - args := arr[1:] - - if len(args) != 1 { - return SendSuggest(data) - } - - zone := text[6:] - +func GetDataLottery(zone string) (string, error) { switch zone { case "mien-nam-xsmn", "mien-bac-xsmb", "mien-trung-xsmt": fp := gofeed.NewParser() - feed, _ := fp.ParseURL(fmt.Sprintf("https://xosothienphu.com/ket-qua-xo-so-%s.rss", zone)) - fmt.Println(feed.Items[0].Description) + feed, err := fp.ParseURL(fmt.Sprintf("https://xosothienphu.com/ket-qua-xo-so-%s.rss", zone)) + + if err != nil { + return "", nil + } message := strings.Replace(feed.Items[0].Description, "Giải", "\nGiải", -1) message = strings.Replace(message, "[", "\n\n[", -1) @@ -33,16 +24,13 @@ func Send(data structs.DataTele) error { if zone == "mien-bac-xsmb" { message = strings.Replace(message, "ĐB:", "\n\nĐB:", -1) } - - data.ReplyMessage = feed.Items[0].Title + message - return telegram.SendMessage(data) + return feed.Items[0].Title + message, nil default: - data.ReplyMessage = "Tôi không hiểu câu lệnh của bạn !!!" - return telegram.SendMessage(data) + return "Tôi không hiểu câu lệnh của bạn !!!", nil } } -func SendSuggest(data structs.DataTele) error { +func GetSuggest(data structs.DataTele) (string, []structs.ButtonCallback) { var buttons []structs.ButtonCallback var btn1, btn2, btn3 structs.ButtonCallback @@ -59,7 +47,7 @@ func SendSuggest(data structs.DataTele) error { buttons = append(buttons, btn2) buttons = append(buttons, btn3) - data.ReplyMessage = "Hãy chọn khu vực muốn xem kết quả xổ số" - return telegram.SendMessageWithReplyMarkup(data, buttons) + message := "Hãy chọn khu vực muốn xem kết quả xổ số" + return message, buttons } diff --git a/utils/lunar/lunar.go b/utils/lunar/lunar.go index 86c22a7..9f1d061 100644 --- a/utils/lunar/lunar.go +++ b/utils/lunar/lunar.go @@ -7,47 +7,36 @@ import ( "net/http" "os" "time" - "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" "github.com/oliamb/cutter" ) -func SendLunarDateNow(data structs.DataTele) error { +func DownloadAndCropImage() (string, error) { y, m, d := time.Now().Date() - path := "/tmp/lunar.jpg" - - err := downloadAndCropImage(fmt.Sprintf("https://licham365.vn/images/lich-am-ngay-%v-thang-%v-nam-%v.jpg", d, int(m), y), path) - if err != nil { - return err - } - - return telegram.SendPhoto(data, path) -} - -func downloadAndCropImage(URL, fileName string) error { + url := fmt.Sprintf("https://licham365.vn/images/lich-am-ngay-%v-thang-%v-nam-%v.jpg", d, int(m), y) //Get the response bytes from the url - response, err := http.Get(URL) + response, err := http.Get(url) if err != nil { - return err + return "", err } defer response.Body.Close() if response.StatusCode != 200 { - return errors.New("Received non 200 response code") + return "", errors.New("Received non 200 response code") } + path := "/tmp/lunar.jpg" //Create a empty file - file, err := os.Create(fileName) + file, err := os.Create(path) if err != nil { - return err + return "", err } defer file.Close() img, err := jpeg.Decode(response.Body) if err != nil { - return err + return "", err } cImg, err := cutter.Crop(img, cutter.Config{ @@ -59,14 +48,14 @@ func downloadAndCropImage(URL, fileName string) error { }) if err != nil { - return err + return "", err } if err := jpeg.Encode(file, cImg, &jpeg.Options{ Quality: 100, }); err != nil { - return err + return "", err } - return nil + return path, nil } diff --git a/utils/qr/qr.go b/utils/qr/qr.go index ccd2e7f..c8c4a38 100644 --- a/utils/qr/qr.go +++ b/utils/qr/qr.go @@ -1,28 +1,15 @@ package qr import ( - "strings" - "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" - "github.com/skip2/go-qrcode" ) -func SendQRImage(data structs.DataTele) error { - text := data.RawMessage - arr := strings.Fields(text) - args := arr[1:] - if len(args) == 0 { - data.ReplyMessage = "Sử dụng cú pháp /qr nội dung để tạo mã QR." - return telegram.SendMessage(data) - } - - content := text[4:] +func CreateImage(content string) (string, error) { path := "/tmp/qr.png" err := qrcode.WriteFile(content, qrcode.Medium, 256, path) if err != nil { - return err + return "", err } - return telegram.SendPhoto(data, path) + return path, nil } diff --git a/utils/quote/quote.go b/utils/quote/quote.go index 1edbd78..6a7a2ad 100644 --- a/utils/quote/quote.go +++ b/utils/quote/quote.go @@ -2,26 +2,12 @@ package quote import ( "encoding/json" - "fmt" "io/ioutil" "net/http" "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" ) -func SendAQuote(data structs.DataTele) error { - quote, err := getAQuote() - if err != nil { - return err - } - - quoteFormat := fmt.Sprintf(""%s" - %s", quote.Quote, quote.Author) - data.ReplyMessage = quoteFormat - - return telegram.SendMessage(data) -} - -func getAQuote() (*structs.QuoteData, error) { +func GetAQuote() (*structs.QuoteData, error) { res, err := http.Get("https://zenquotes.io/api/random") if err != nil { return nil, err diff --git a/utils/random/random.go b/utils/random/random.go deleted file mode 100644 index 1b06028..0000000 --- a/utils/random/random.go +++ /dev/null @@ -1,32 +0,0 @@ -package random - -import ( - "fmt" - "math/rand" - "strings" - "unicode" - "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" -) - -func RandomElements(data structs.DataTele) error { - text := data.RawMessage - arr := strings.Fields(text) - - if len(arr[1:]) == 0 { - data.ReplyMessage = "Sử dụng cú pháp /random A, B, C để chọn phần tử ngẫu nhiên" - return telegram.SendMessage(data) - - } - - f := func(c rune) bool { - return unicode.IsPunct(c) == unicode.IsPunct(',') - } - - els := strings.FieldsFunc(text[8:], f) - el := els[rand.Intn(len(els))] - - data.ReplyMessage = fmt.Sprintf("Phần từ được chọn sau khi random: %v", strings.TrimSpace(el)) - - return telegram.SendMessage(data) -} diff --git a/utils/shortener/shortener.go b/utils/shortener/shortener.go index 1a49d96..a691bcd 100644 --- a/utils/shortener/shortener.go +++ b/utils/shortener/shortener.go @@ -2,48 +2,30 @@ package shortener import ( "fmt" - "log" "net/url" "os" - "strings" "time" "zeril-bot/utils/redis" - "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" gonanoid "github.com/matoous/go-nanoid" ) const rawAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" -func Generate(data structs.DataTele) error { - text := data.RawMessage - arr := strings.Fields(text) - args := arr[1:] - fmt.Println(args) - - if len(args) == 0 { - data.ReplyMessage = "Sử dụng cú pháp /shortener https://example.com/ để tạo rút gọn liên kết" - return telegram.SendMessage(data) - } - - url := text[11:] +func Generate(url string) (string, error) { if !isUrl(url) { - data.ReplyMessage = "URL không đúng định dạng" - return telegram.SendMessage(data) + return "URL không đúng định dạng", nil } id, err := gonanoid.Generate(rawAlphabet, 6) if err != nil { - log.Panic(err) + return "", err } redis.Set(id, url, time.Hour) - shortUrl := fmt.Sprintf("%s/url/%s", os.Getenv("APP_URL"), id) - data.ReplyMessage = fmt.Sprintf("URL sau khi rút gọn: %s", shortUrl, shortUrl) - return telegram.SendMessage(data) + return fmt.Sprintf("URL sau khi rút gọn: %s", shortUrl, shortUrl), nil } func isUrl(str string) bool { diff --git a/utils/telegram/telegram.go b/utils/telegram/telegram.go index 894ab61..f05c7bf 100644 --- a/utils/telegram/telegram.go +++ b/utils/telegram/telegram.go @@ -15,7 +15,13 @@ import ( "zeril-bot/utils/structs" ) -var API_URL string = "https://api.telegram.org/bot" + os.Getenv("TELE_BOT_TOKEN") +type Telegram struct { + client *http.Client +} + +func New(http *http.Client) *Telegram { + return &Telegram{http} +} func getApiURL(t string) string { url := "https://api.telegram.org/bot" + os.Getenv("TELE_BOT_TOKEN") @@ -34,7 +40,7 @@ func getApiURL(t string) string { } } -func SendMessage(data structs.DataTele) error { +func (t Telegram) SendMessage(data structs.DataTele) error { message := data.ReplyMessage if data.ChatType == "group" { message += "\n@" + data.Username @@ -54,9 +60,7 @@ func SendMessage(data structs.DataTele) error { req.URL.RawQuery = q.Encode() - client := &http.Client{} - - res, err := client.Do(req) + res, err := t.client.Do(req) if err != nil { return err @@ -85,7 +89,7 @@ func SendMessage(data structs.DataTele) error { return errors.New(string(body)) } -func SendPhoto(data structs.DataTele, path string) error { +func (t Telegram) SendPhoto(data structs.DataTele, path string) error { file, _ := os.Open(path) defer file.Close() @@ -133,7 +137,7 @@ func SendPhoto(data structs.DataTele, path string) error { return errors.New(string(body)) } -func SendMessageWithReplyMarkup(data structs.DataTele, replyMark []structs.ButtonCallback) error { +func (t Telegram) SendMessageWithReplyMarkup(data structs.DataTele, replyMark []structs.ButtonCallback) error { var markup structs.BodyReplyMarkup markup.ReplyMarkup.InlineKeyboard = append(markup.ReplyMarkup.InlineKeyboard, replyMark) marshalled, err := json.Marshal(markup) diff --git a/utils/weather/weather.go b/utils/weather/weather.go index cda2f5a..71a4af7 100644 --- a/utils/weather/weather.go +++ b/utils/weather/weather.go @@ -3,43 +3,18 @@ package weather import ( "encoding/json" "errors" - "fmt" "io/ioutil" "log" "net/http" "os" - "strings" "zeril-bot/utils/structs" - "zeril-bot/utils/telegram" ) const API_URL = "https://api.openweathermap.org" var APP_ID = os.Getenv("OPEN_WEATHER_MAP_APP_ID") -func SendForecastOfWeather(data structs.DataTele) error { - text := data.RawMessage - fmt.Println(text) - text = strings.TrimSpace(text) - arr := strings.Fields(text) - args := arr[1:] - - if len(args) == 0 { - return SendSuggestForecast(data) - } - - cityName := text[9:] - wData, err := GetWeather(cityName) - if err != nil { - data.ReplyMessage = "Không tìm thấy thông tin thời tiết" - return telegram.SendMessage(data) - } - - data.ReplyMessage = fmt.Sprintf("🏙 Thời tiết hiện tại ở %s\n\n🌡 Nhiệt độ: %.2f°C\n\n💧 Độ ẩm: %v%\n\nℹ️ Tổng quan: %s", wData.Name, wData.Main.Temp, wData.Main.Humidity, wData.Weather[0].Description) - return telegram.SendMessage(data) -} - -func SendSuggestForecast(data structs.DataTele) error { +func GetSuggestForecast(data structs.DataTele) (string, []structs.ButtonCallback) { var buttons []structs.ButtonCallback var btn1, btn2, btn3 structs.ButtonCallback @@ -56,8 +31,9 @@ func SendSuggestForecast(data structs.DataTele) error { buttons = append(buttons, btn2) buttons = append(buttons, btn3) - data.ReplyMessage = "Sử dụng cú pháp /weather tên thành phố hoặc chọn các gợi ý bên dưới để xem thời tiết" - return telegram.SendMessageWithReplyMarkup(data, buttons) + message := "Sử dụng cú pháp /weather tên thành phố hoặc chọn các gợi ý bên dưới để xem thời tiết" + + return message, buttons } func GetWeather(cityName string) (structs.WeatherData, error) { @@ -65,7 +41,7 @@ func GetWeather(cityName string) (structs.WeatherData, error) { req, err := http.NewRequest("GET", uri, nil) if err != nil { - log.Panic(err) + return structs.WeatherData{}, err } q := req.URL.Query() @@ -81,7 +57,7 @@ func GetWeather(cityName string) (structs.WeatherData, error) { res, err := client.Do(req) if err != nil { - log.Panic(err) + return structs.WeatherData{}, err } defer res.Body.Close() @@ -89,7 +65,7 @@ func GetWeather(cityName string) (structs.WeatherData, error) { body, err := ioutil.ReadAll(res.Body) if err != nil { - log.Panic(err) + return structs.WeatherData{}, err } var data structs.WeatherData @@ -101,7 +77,7 @@ func GetWeather(cityName string) (structs.WeatherData, error) { err = json.Unmarshal(body, &data) if err != nil { - log.Panic(err) + return structs.WeatherData{}, err } log.Println("GetWeather OK")