Skip to content

Commit

Permalink
add godotenv to allow using '.env' file for bot
Browse files Browse the repository at this point in the history
  • Loading branch information
Divkix committed Jun 12, 2023
1 parent 8b69120 commit 5f00719
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 98 deletions.
4 changes: 4 additions & 0 deletions alita/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path"
"runtime"

"github.com/joho/godotenv"
log "github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -39,6 +40,9 @@ func init() {
},
)

// load goenv config
godotenv.Load()

// set necessary variables
Debug = typeConvertor{str: os.Getenv("DEBUG")}.Bool()
DropPendingUpdates = typeConvertor{str: os.Getenv("DROP_PENDING_UPDATES")}.Bool()
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/dustin/go-humanize v1.0.1
github.com/eko/gocache/v3 v3.1.2
github.com/google/uuid v1.3.0
github.com/joho/godotenv v1.5.1
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.16.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
Expand Down
115 changes: 17 additions & 98 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
package main

import (
"crypto/sha512"
"embed"
"encoding/hex"
"encoding/json"
"fmt"

log "github.com/sirupsen/logrus"

"github.com/divideprojects/Alita_Robot/alita/config"
"github.com/divideprojects/Alita_Robot/alita/i18n"
"github.com/divideprojects/Alita_Robot/alita/utils/helpers"
"github.com/divideprojects/Alita_Robot/alita/utils/parsemode"

"github.com/PaulSonOfLars/gotgbot/v2"
Expand Down Expand Up @@ -84,28 +80,9 @@ func main() {
}
log.Info("[Polling] Started Polling...!")

// list modules from modules dir
log.Infof(
fmt.Sprintf(
"[Modules] Loaded modules: %s", bot.ListModules(),
),
)

// Log the message that bot started
log.Infof("[Bot] %s has been started...", b.Username)

// send message to log group
_, err = b.SendMessage(config.MessageDump,
fmt.Sprintf("<b>Started Bot!</b>\n<b>Mode:</b> %s\n<b>Loaded Modules:</b>\n%s", config.WorkingMode, bot.ListModules()),
&gotgbot.SendMessageOpts{
ParseMode: parsemode.HTML,
},
)
if err != nil {
log.Errorf("[Bot] Failed to send message to log group: %v", err)
log.Fatal(err)
}

// Set Commands of Bot
log.Info("Setting Custom Commands for PM...!")
_, err = b.SetMyCommands(
Expand All @@ -125,83 +102,25 @@ func main() {
// Loading Modules
bot.LoadModules(dispatcher)

// Idle, to keep updates coming in, and avoid bot stopping.
updater.Idle()
}

// function to handle dispatcher errors
func dispatcherErrorHandler(b *gotgbot.Bot, ctx *ext.Context, err error) ext.DispatcherAction {
chat := ctx.EffectiveChat
tgErr := err.(*gotgbot.TelegramError)

// these two just makes sure that errors are not logged and passed
// as these are predefined by library
if err == ext.ContinueGroups {
return ext.DispatcherActionContinueGroups
}

if err == ext.EndGroups {
return ext.DispatcherActionEndGroups
}

// if bot is not able to send any message to chat, it will leave the group
if tgErr.Description == "Bad Request: have no rights to send a message" {
_, _ = b.LeaveChat(chat.Id, nil)
return ext.DispatcherActionEndGroups
}

update := ctx.Update
uMsg := update.Message
errorJson, _ := json.MarshalIndent(tgErr, "", " ")
updateJson, _ := json.Marshal(update)

hash := func() string {
// Generate a new Sha1 Hash
shaHash := sha512.New()
shaHash.Write([]byte(string(errorJson) + string(updateJson)))
return hex.EncodeToString(shaHash.Sum(nil))
}()

pasted, logUrl := helpers.PasteToNekoBin("Error Report" + string(errorJson) + "\n" + string(updateJson) + "\n" + tgErr.Error())

if pasted {
// Send Message to Log Group
_, _ = b.SendMessage(
config.MessageDump,
"⚠️ An ERROR Occurred ⚠️\n\n"+
"An exception was raised while handling an update."+
"\n\n"+
fmt.Sprintf("<b>Error ID:</b> <code>%s</code>", hash)+
"\n"+
fmt.Sprintf("<b>Chat ID:</b> <code>%d</code>", uMsg.Chat.Id)+
"\n"+
fmt.Sprintf("<b>Command:</b> <code>%s</code>", uMsg.Text)+
"\n"+
fmt.Sprintf("<b>Error Log:</b> https://nekobin.com/%s", logUrl)+
"\n\n"+
"Please Check logs ASAP!",
parsemode.Shtml(),
)
} else {
_, _ = b.SendMessage(
config.MessageDump,
"Failed to paste error message to nekobin, please check logs!"+
fmt.Sprintf("\n<b>Error ID:</b> <code>%s</code>", hash),
parsemode.Shtml(),
)
}
// list modules from modules dir
log.Infof(
fmt.Sprintf(
"[Modules] Loaded modules: %s", bot.ListModules(),
),
)

// log stuff
log.WithFields(
log.Fields{
"ErrorId": hash,
"TelegramError": string(errorJson),
"Update": string(updateJson),
"LogURL": logUrl,
// send message to log group
_, err = b.SendMessage(config.MessageDump,
fmt.Sprintf("<b>Started Bot!</b>\n<b>Mode:</b> %s\n<b>Loaded Modules:</b>\n%s", config.WorkingMode, bot.ListModules()),
&gotgbot.SendMessageOpts{
ParseMode: parsemode.HTML,
},
).Error(
tgErr.Error(),
)
if err != nil {
log.Errorf("[Bot] Failed to send message to log group: %v", err)
log.Fatal(err)
}

return ext.DispatcherActionNoop
// Idle, to keep updates coming in, and avoid bot stopping.
updater.Idle()
}

0 comments on commit 5f00719

Please sign in to comment.