Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Commit

Permalink
change telegram client to have []*log.Logger with io.Writer as telegr…
Browse files Browse the repository at this point in the history
…am writer
  • Loading branch information
rutesantos4 committed Jan 7, 2023
1 parent 3f29d25 commit c025575
Showing 1 changed file with 13 additions and 30 deletions.
43 changes: 13 additions & 30 deletions pkg/telegramclient.go
Original file line number Diff line number Diff line change
@@ -1,49 +1,32 @@
package pkg

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"log"
)

const messageType = "application/json"

type TelegramClient struct {
url string
chatId string
logs []string
loggers []*log.Logger
}

func NewTelegramClient(botToken, chatId string) TelegramClient {

url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", botToken)

return TelegramClient{
url: url,
logs: levelPrefix,
chatId: chatId,
tw := TelegramWriter{
botToken: botToken,
chatId: chatId,
}
}

func (tc TelegramClient) Write(ar Record) {
log := tc.logs[ar.Level]

body, err := json.Marshal(map[string]string{
"chat_id": tc.chatId,
"text": fmt.Sprintf("%s%s", log, ar.Message),
})
loggers := make([]*log.Logger, len(levelPrefix))

if err != nil {
return
for i, v := range levelPrefix {
loggers[i] = log.New(tw, v, defaultLoggerFlag)
}

response, err := http.Post(tc.url, messageType, bytes.NewBuffer(body))

if err != nil {
return
return TelegramClient{
loggers: loggers,
}
}

defer response.Body.Close()

func (tc TelegramClient) Write(ar Record) {
tc.loggers[ar.Level].Println(ar.Message)
}

0 comments on commit c025575

Please sign in to comment.