logging changes

This commit is contained in:
watn3y 2023-12-29 07:54:27 +01:00
parent be0cc403b9
commit 02c9f2af6b
14 changed files with 96 additions and 77 deletions

View file

@ -15,9 +15,7 @@ RUN go mod download
RUN mkdir /tmp/build/output RUN mkdir /tmp/build/output
ARG CGO_ENABLED=1 ARG CGO_ENABLED=0
ENV COMMIT=${COMMIT}
RUN go build -o /tmp/build/output/bloaterbot RUN go build -o /tmp/build/output/bloaterbot
@ -31,6 +29,8 @@ RUN apk add --no-cache ffmpeg python3 py3-pip
RUN pip3 install --upgrade yt-dlp RUN pip3 install --upgrade yt-dlp
ENV COMMIT=${COMMIT}
WORKDIR /app WORKDIR /app
COPY --from=build /tmp/build/output/bloaterbot /app/bloaterbot COPY --from=build /tmp/build/output/bloaterbot /app/bloaterbot

9
bot.go
View file

@ -17,17 +17,20 @@ func bot() {
go notify.NotifyHandler(bot) go notify.NotifyHandler(bot)
for update := range updates { for update := range updates {
log.Debug().Interface("update", update).Msg("Recieved update") log.Trace().Interface("update", update).Msg("Received update")
if update.InlineQuery != nil && update.Message == nil { if update.InlineQuery != nil && update.Message == nil {
nenefoot.Nenefoot(update, bot) nenefoot.Nenefoot(update, bot)
continue continue
} }
if update.Message != nil { if update.Message != nil && update.Message.Text != "" {
if update.Message.Time().UTC().Unix() < time.Now().UTC().Unix() { if update.Message.Time().UTC().Unix() < time.Now().UTC().Unix() {
continue continue
} }
log.Info().Int64("ChatID",update.Message.Chat.ID).Int64("UserID",update.Message.From.ID).Str("Text", update.Message.Text).Msg("Recieved Message")
if update.Message.IsCommand() { if update.Message.IsCommand() {
commands.Commands(update, bot) commands.Commands(update, bot)
} else { } else {
@ -37,7 +40,7 @@ func bot() {
} }
log.Info().Interface("update", update).Msg("Unable to parse update") log.Trace().Interface("update", update).Msg("Unable to parse update")
} }
} }

View file

@ -10,19 +10,18 @@ import (
"watn3y.de/bloaterbot/commands/download" "watn3y.de/bloaterbot/commands/download"
"watn3y.de/bloaterbot/commands/gaypoints" "watn3y.de/bloaterbot/commands/gaypoints"
"watn3y.de/bloaterbot/commands/notify" "watn3y.de/bloaterbot/commands/notify"
"watn3y.de/bloaterbot/commonlogic"
"watn3y.de/bloaterbot/config" "watn3y.de/bloaterbot/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
//TODO logging
func Commands(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Commands(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
cmd := strings.ToLower(update.Message.Command()) cmd := strings.ToLower(update.Message.Command())
log.Debug().Str("cmd", cmd).Msg("Matching command") log.Trace().Str("cmd", cmd).Msg("Matching command")
switch cmd { switch cmd {
case "shutup": case "shutup":
@ -93,13 +92,13 @@ func info(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
if commit == "" { if commit == "" {
commit = "not available" commit = "not available"
} }
//TODO calculate total size
info, _ := os.Stat("data/db/gaypoints.db")
dbSizeInKiloBytes := info.Size() / 1000
textInfo := "<b>" + me.FirstName + "</b>" + "\n\n" + textInfo := "<b>" + me.FirstName + "</b>" + "\n\n" +
"<b>Commit:</b> " + "<code>" + commit + "</code>" + "\n" + "<b>Commit:</b> " + "<code>" + commit + "</code>" + "\n" +
"<b>DB Size:</b> " + "<code>" + strconv.FormatInt(dbSizeInKiloBytes, 10) + "KB" + "</code>" "<b>DB Size:</b> " + "\n" +
"gaypoints.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/gaypoints.db"), 10) + " Bytes" + "</code>" + "\n" +
"notify.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/notify.db"), 10) + " Bytes" + "</code>" + "\n" +
"nenefoot.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/nenefoot.db"), 10) + " Bytes" + "</code>" + "\n"
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},

View file

@ -11,7 +11,6 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv"
"strings" "strings"
"time" "time"
@ -23,8 +22,9 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
//TODO logging // TODO logging
// TODO error handling
// TODO rewrite
func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Int64("chat", update.Message.Chat.ID).Int64("user", update.Message.From.ID).Msg("starting download") log.Debug().Int64("chat", update.Message.Chat.ID).Int64("user", update.Message.From.ID).Msg("starting download")
@ -92,8 +92,7 @@ func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
botIO.EditMessage(message, bot) botIO.EditMessage(message, bot)
serveMedia(update, bot, downloadTarget, files[0].Name()) serveMedia(update, bot, downloadTarget, files[0].Name())
log2.Println("[download] Served URL " + update.Message.CommandArguments() + " for " + strconv.FormatInt(update.Message.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10)) log.Debug().Str("URL", update.Message.CommandArguments()).Int64("user", update.Message.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Served Video")
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
log.Info().Msg("downloaded file") log.Info().Msg("downloaded file")
@ -148,8 +147,8 @@ func runYTDL(URL string, targetDir string) (success bool) {
func matchURL(URL string) (matchedURL string) { func matchURL(URL string) (matchedURL string) {
parsedURL, err := url.Parse(URL) parsedURL, err := url.Parse(URL)
if err != nil { if err != nil {
log2.Fatal(err) log.Err(err).Msg("Failed to parse URL")
return ""
} }
var domainRegex = regexp.MustCompile(`(youtube\.com$)|(youtu\.be$)`) var domainRegex = regexp.MustCompile(`(youtube\.com$)|(youtu\.be$)`)
@ -167,7 +166,8 @@ func matchURL(URL string) (matchedURL string) {
func shortURL(URL string) (shorturl string) { func shortURL(URL string) (shorturl string) {
resp, err := http.Get(config.BotConfig.Download.Yourls.APIPath + "?signature=" + config.BotConfig.Download.Yourls.Signature + "&action=shorturl&format=simple&url=" + URL) resp, err := http.Get(config.BotConfig.Download.Yourls.APIPath + "?signature=" + config.BotConfig.Download.Yourls.Signature + "&action=shorturl&format=simple&url=" + URL)
if err != nil { if err != nil {
log2.Fatal(err) log.Err(err).Msg("Failed to get shortURL")
return ""
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -175,7 +175,8 @@ func shortURL(URL string) (shorturl string) {
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
log2.Fatal(err) log.Err(err).Msg("Failed to get shortURL")
return ""
} }
return string(body) return string(body)

View file

@ -12,18 +12,20 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
// TODO logging
func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Int64("chat", update.Message.Chat.ID).Int64("user", update.Message.From.ID).Msg("getting gaypoints") log.Trace().Int64("ChatID",update.Message.Chat.ID).Msg(("Getting Gaypoints"))
if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) { if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) {
log.Debug().Int64("chat", update.Message.Chat.ID).Ints64("enabledChats", config.BotConfig.GayPoints.EnabledChats).Msg("not getting gaypoints, chat not enabled") log.Debug().Int64("chat", update.Message.Chat.ID).Ints64("enabledChats", config.BotConfig.GayPoints.EnabledChats).Msg("Not getting Gaypoints, Chat not enabled")
return return
} }
if update.Message.ReplyToMessage != nil { if update.Message.ReplyToMessage != nil {
log.Debug().Msg("ReplyToMessage not empty, getting gaypoints for individual user") log.Trace().Msg("ReplyToMessage not empty, getting Gaypoints for individual user")
points := sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID) points := sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID)
errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: update.Message.ReplyToMessage.From.ID}, bot) errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: update.Message.ReplyToMessage.From.ID}, bot)
@ -42,7 +44,7 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
} else { } else {
log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("error getting details for user") log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Error getting Details for User")
messagetext = "Something went wrong :( Forward me a message from the user and try again. This might fix it." messagetext = "Something went wrong :( Forward me a message from the user and try again. This might fix it."
} }
@ -56,7 +58,7 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} }
log.Debug().Msg("ReplyToMessage is empty, getting gaypoints for whole chat") log.Debug().Msg("ReplyToMessage is empty, getting Gaypoints for whole chat")
gps := sqlGetAllGP(update.Message.Chat.ID) gps := sqlGetAllGP(update.Message.Chat.ID)
@ -64,14 +66,14 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
for _, gaypointInfo := range gps { for _, gaypointInfo := range gps {
errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: gaypointInfo.userID}, bot) errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: gaypointInfo.userID}, bot)
if errorGettingUser { if errorGettingUser {
log.Error().Int64("user", update.Message.From.ID).Int64("chat", update.Message.Chat.ID).Msg("error getting details for user") log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Error getting Details for User")
continue continue
} }
currentName := currentUser.User.FirstName currentName := currentUser.User.FirstName
if currentUser.User.UserName != "" { if currentUser.User.UserName != "" {
currentName = currentUser.User.UserName currentName = currentUser.User.UserName
} }
log.Debug().Int64("user", gaypointInfo.userID).Int64("chat", update.Message.Chat.ID).Int64("gp", gaypointInfo.gaypoints).Msg("got details for user")
text := `<a href="` + `tg://user?id=` + strconv.FormatInt(gaypointInfo.userID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(gaypointInfo.gaypoints, 10) + `</b>` + ` gaypoints` + "\n" text := `<a href="` + `tg://user?id=` + strconv.FormatInt(gaypointInfo.userID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(gaypointInfo.gaypoints, 10) + `</b>` + ` gaypoints` + "\n"
messagetext = messagetext + text messagetext = messagetext + text
@ -208,7 +210,7 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
Text: messagetext, Text: messagetext,
} }
log.Info().Int64("oldGP", currentPoints).Int64("newGP", finalgp).Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Int64("changedBy", update.Message.From.ID).Msg("setting gaypoints") log.Info().Int64("oldGP", currentPoints).Int64("newGP", finalgp).Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Int64("changedBy", update.Message.From.ID).Msg("Set Gaypoints")
sqlSetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID, finalgp) sqlSetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID, finalgp)
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)

View file

@ -12,12 +12,11 @@ var gpSelectChat *sql.Stmt
var gpSet *sql.Stmt var gpSet *sql.Stmt
// TODO logging
// TODO switch to SQL
func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) { func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) {
rows, err := gpSelectChat.Query(chatid) rows, err := gpSelectChat.Query(chatid)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to execute SQL to get get gaypoints for chat") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get gaypoints for chat")
return return
} }
@ -31,11 +30,12 @@ func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) {
gaypoints: b, gaypoints: b,
}) })
default: default:
log.Error().Err(err).Msg("failed to parse SQL to get get gaypoints for chat") log.Error().Err(err).Msg("Failed to parse SQL Result. Can't get gaypoints for chat")
return return
} }
log.Debug().Msg("executed SQL to get gaypoints for chat")
log.Trace().Int64("ChatID", chatid).Interface("GP", gaypoints).Msg(("SQL: got SQL for Chat"))
} }
return gaypoints return gaypoints
@ -51,26 +51,25 @@ func sqlGetGP(chatid int64, userid int64) (gaypoints int64) {
case nil: case nil:
break break
default: default:
log.Error().Err(err).Msg("failed to execute SQL to get get gaypoints for user") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get gaypoints for User")
return return
} }
log.Debug().Msg("executed SQL to get gaypoints for user") log.Trace().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: got SQL for User"))
return gaypoints return gaypoints
} }
func sqlSetGP(chatid int64, userid int64, gaypoints int64) { func sqlSetGP(chatid int64, userid int64, gaypoints int64) {
_, err := gpSet.Exec(chatid, userid, gaypoints) _, err := gpSet.Exec(chatid, userid, gaypoints)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to execute SQL to get set gaypoints for user") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't set gaypoints for User")
return return
} }
log.Debug().Msg("executed SQL to set gaypoints for user") log.Info().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: set SQL for User"))
} }
func InitDB() { func InitDB() {
const dbPath string = "data/db/gaypoints.db" const dbPath string = "data/db/gaypoints.db"
log.Info().Str("dbpath", dbPath).Msg("init database")
db, err := sql.Open("sqlite", dbPath) db, err := sql.Open("sqlite", dbPath)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("failed to open sqlite database") log.Panic().Err(err).Msg("failed to open sqlite database")
@ -99,5 +98,5 @@ func InitDB() {
log.Panic().Err(err).Msg("failed to create sql statement") log.Panic().Err(err).Msg("failed to create sql statement")
} }
log.Info().Msg("init database: done") log.Info().Str("dbpath", dbPath).Msg("Database prepared and connected")
} }

View file

@ -12,10 +12,10 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
//TODO logging
func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Str("args", update.Message.CommandArguments()).Msg("parsing new reminder")
log.Trace().Str("args", update.Message.CommandArguments()).Msg(("Parsing new Reminder"))
commandArgs := strings.Fields(update.Message.CommandArguments()) commandArgs := strings.Fields(update.Message.CommandArguments())
var timeArg string var timeArg string
@ -25,7 +25,9 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
timeArg = strings.ToLower(commandArgs[0]) timeArg = strings.ToLower(commandArgs[0])
textArg = strings.Replace(update.Message.CommandArguments(), timeArg, "", 1) textArg = strings.Replace(update.Message.CommandArguments(), timeArg, "", 1)
} else { } else {
log.Error().Str("args", update.Message.CommandArguments()).Msg("invalid new reminder")
log.Error().Str("CommandArgs", update.Message.CommandArguments()).Msg("Failed to add Reminder. Unable to parse reminder")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
@ -39,7 +41,9 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
isValidFormat := regexp.MustCompile(`(?m)^\d{1,3}[mhd]$`) isValidFormat := regexp.MustCompile(`(?m)^\d{1,3}[mhd]$`)
if !isValidFormat.MatchString(timeArg) { if !isValidFormat.MatchString(timeArg) {
log.Error().Str("args", update.Message.CommandArguments()).Msg("invalid new reminder")
log.Error().Str("CommandArgs", update.Message.CommandArguments()).Msg("Failed to add Reminder. Unable to parse reminder")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
@ -78,8 +82,6 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
reminderText: textArg, reminderText: textArg,
} }
log.Info().Int("ID", reminder.updateID).Int64("chat", reminder.chatID).Int64("user", reminder.userID).Int64("time", reminder.notifyTime).Msg("adding new reminder")
sqlAddReminder(reminder) sqlAddReminder(reminder)
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
@ -89,12 +91,15 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
Text: "Set reminder for " + notifyTime.Format("02.01.2006") + " at " + notifyTime.Format("15:04") + " UTC ", Text: "Set reminder for " + notifyTime.Format("02.01.2006") + " at " + notifyTime.Format("15:04") + " UTC ",
} }
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
log.Info().Int("ID", reminder.updateID).Int64("chat", reminder.chatID).Int64("user", reminder.userID).Int64("time", reminder.notifyTime).Msg("Added new Reminder")
return return
} }
func NotifyHandler(bot *tgbotapi.BotAPI) { func NotifyHandler(bot *tgbotapi.BotAPI) {
log.Info().Msg("Handling Reminders")
for { for {
reminders := sqlGetReminders() reminders := sqlGetReminders()
@ -109,11 +114,11 @@ func NotifyHandler(bot *tgbotapi.BotAPI) {
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Reminder: " + details.reminderText, Text: "Reminder: " + details.reminderText,
} }
log.Info().Int64("chat", details.chatID).Int64("user", details.userID).Str("text", details.reminderText).Msg("sent reminder")
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
sqlDeleteReminder(updateID) sqlDeleteReminder(updateID)
log.Info().Int64("chat", details.chatID).Int64("user", details.userID).Str("text", details.reminderText).Msg("Sent Reminder")
} }
} }

View file

@ -11,11 +11,8 @@ var notifyGetReminders *sql.Stmt
var notifyGetReminderDetails *sql.Stmt var notifyGetReminderDetails *sql.Stmt
var notifyDeleteReminder *sql.Stmt var notifyDeleteReminder *sql.Stmt
// TODO logging
// TODO switch to SQL
func InitDB() { func InitDB() {
const dbPath string = "data/db/notify.db" const dbPath string = "data/db/notify.db"
log.Info().Str("dbpath", dbPath).Msg("init database")
db, err := sql.Open("sqlite", dbPath) db, err := sql.Open("sqlite", dbPath)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("failed to open sqlite database") log.Panic().Err(err).Msg("failed to open sqlite database")
@ -50,33 +47,32 @@ func InitDB() {
log.Panic().Err(err).Msg("failed to create sql statement") log.Panic().Err(err).Msg("failed to create sql statement")
} }
log.Info().Msg("init database: done") log.Info().Str("dbpath", dbPath).Msg("Database prepared and connected")
} }
func sqlDeleteReminder(updateID int) { func sqlDeleteReminder(updateID int) {
_, err := notifyDeleteReminder.Exec(updateID) _, err := notifyDeleteReminder.Exec(updateID)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to execute SQL to delete reminder") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't delete Reminder")
return return
} }
log.Debug().Msg("executed SQL to delete reminder") log.Trace().Int("ID", updateID).Msg(("SQL: deleted reminder"))
} }
func sqlAddReminder(reminder reminderConfig) { func sqlAddReminder(reminder reminderConfig) {
_, err := notifySetReminder.Exec(reminder.updateID, reminder.notifyTime, reminder.chatID, reminder.userID, reminder.messageToReplyToID, reminder.reminderText) _, err := notifySetReminder.Exec(reminder.updateID, reminder.notifyTime, reminder.chatID, reminder.userID, reminder.messageToReplyToID, reminder.reminderText)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to execute SQL to add reminder") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't add Reminder")
return return
} }
log.Trace().Interface("Reminder", reminder).Msg(("SQL: added Reminder"))
log.Debug().Msg("executed SQL to add reminder")
} }
func sqlGetReminders() (reminders map[int]int64) { func sqlGetReminders() (reminders map[int]int64) {
rows, err := notifyGetReminders.Query() rows, err := notifyGetReminders.Query()
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to execute SQL to get reminder") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get Reminders")
return return
} }
@ -88,13 +84,13 @@ func sqlGetReminders() (reminders map[int]int64) {
case nil: case nil:
reminders[c] = b reminders[c] = b
default: default:
log.Error().Err(err).Msg("failed to parse SQL to get reminder") log.Error().Err(err).Msg("Failed to parse SQL Result. Can't get Reminders")
return return
} }
} }
log.Debug().Msg("executed SQL to get reminders") log.Trace().Interface("Reminders", reminders).Msg(("SQL: got Reminders"))
return reminders return reminders
} }
@ -105,10 +101,10 @@ func sqlGetReminderDetails(updateID int) (reminder reminderConfig) {
case nil: case nil:
break break
default: default:
log.Error().Err(err).Msg("failed to execute SQL to get reminder details") log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get Reminder Details")
return return
} }
log.Debug().Msg("executed SQL to get reminder details") log.Trace().Interface("Reminder", reminder).Msg(("SQL: got Reminder Details"))
return reminder return reminder
} }

View file

@ -1,5 +1,10 @@
package commonlogic package commonlogic
import (
"github.com/rs/zerolog/log"
"os"
)
func ContainsInt64(a []int64, b int64) bool { func ContainsInt64(a []int64, b int64) bool {
for _, v := range a { for _, v := range a {
if v == b { if v == b {
@ -19,3 +24,12 @@ func ContainsString(a []string, b string) bool {
return false return false
} }
func GetFileSize(path string) (size int64) {
file, err := os.Stat(path)
if err != nil {
log.Error().Err(err).Msg("Failed to stat " + path)
return 0
}
return file.Size()
}

View file

@ -28,8 +28,8 @@ func LoadConfig() {
zerolog.SetGlobalLevel(zerolog.InfoLevel) zerolog.SetGlobalLevel(zerolog.InfoLevel)
} }
log.Info().Msg("loaded config file") log.Info().Msg("Loaded config")
log.Debug().Interface("config", BotConfig).Msg("") log.Trace().Interface("config", BotConfig).Msg("")
} }
@ -78,16 +78,16 @@ func EncodeToml() {
f, err := os.Create("data/config.toml.example") f, err := os.Create("data/config.toml.example")
if err != nil { if err != nil {
log.Panic().Err(err).Msg("error encoding config file. Cannot open data/config.toml.example") log.Panic().Err(err).Msg("Error encoding Config File. Cannot open data/config.toml.example")
} }
if err := toml.NewEncoder(f).Encode(exampleConfig); err != nil { if err := toml.NewEncoder(f).Encode(exampleConfig); err != nil {
log.Panic().Err(err).Msg("error encoding config file") log.Panic().Err(err).Msg("Error encoding Config File")
} }
if err := f.Close(); err != nil { if err := f.Close(); err != nil {
log.Panic().Err(err).Msg("error encoding config file. Cannot close data/config.toml.example") log.Panic().Err(err).Msg("Error encoding Config File. Cannot close data/config.toml.example")
} }
log.Info().Msg("Wrote example config to data/config.toml.example. Bye Bye") log.Info().Msg("Writing example config to data/config.toml.example. Bye Bye")
} }

View file

@ -17,6 +17,7 @@ import (
func main() { func main() {
fmt.Println("Starting bloaterbot...") fmt.Println("Starting bloaterbot...")
configureLogger() configureLogger()
encodeConfig := flag.Bool("generate-example-config", false, "Generates a example config to config.toml.example") encodeConfig := flag.Bool("generate-example-config", false, "Generates a example config to config.toml.example")
@ -44,8 +45,8 @@ func configureLogger() {
log.Logger = zerolog.New(output).With().Timestamp().Caller().Logger() log.Logger = zerolog.New(output).With().Timestamp().Caller().Logger()
//! note that we overwrite the loglevel after loading the config in config/config.go:53. This is just the default //! note that we overwrite the loglevel after loading the config in config/config.go:53. This is just the default
zerolog.SetGlobalLevel(zerolog.DebugLevel) zerolog.SetGlobalLevel(zerolog.TraceLevel)
log.Info().Msg("Started zerolog logger") log.Info().Msg("Started logger")
} }

View file

@ -7,7 +7,6 @@ import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
) )
//TODO logging
func Balonlyl(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Balonlyl(update tgbotapi.Update, bot *tgbotapi.BotAPI) {

View file

@ -15,7 +15,7 @@ import (
// TODO logging // TODO logging
func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Starting text matcher") log.Debug().Str("Text", update.Message.Text).Msg("Starting text matcher")
if time.Since(config.BotConfig.Shutup[update.Message.Chat.ID]) <= time.Minute*60 { if time.Since(config.BotConfig.Shutup[update.Message.Chat.ID]) <= time.Minute*60 {
log.Debug().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Aborting due to shut-up") log.Debug().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Aborting due to shut-up")
@ -30,7 +30,7 @@ func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
} }
if isBalonlyl { if isBalonlyl {
log.Debug().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Matched Balonlyl meme") log.Info().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Matched text in message")
go balonlyl.Balonlyl(update, bot) go balonlyl.Balonlyl(update, bot)
} }

View file

@ -16,14 +16,14 @@ func RunServer() {
http.Handle("/", videos) http.Handle("/", videos)
http.Handle("/nenefoot/", nenefoot) http.Handle("/nenefoot/", nenefoot)
log.Info().Str("port", config.BotConfig.Webserver.Port).Msg("Starting webserver") log.Info().Str("port", config.BotConfig.Webserver.Port).Msg("Started webserver")
err := http.ListenAndServe(":"+config.BotConfig.Webserver.Port, nil) err := http.ListenAndServe(":"+config.BotConfig.Webserver.Port, nil)
if err != nil { if err != nil {
log.Panic().Err(err).Msg("Failed to start webserver") log.Panic().Err(err).Msg("Failed to start webserver")
} }
} }
/*func handle204(w http.ResponseWriter, r *http.Request) { /*func handle204(w http.ResponseWriter, r *http.Request) {