From 328b69ae1df52fe31ccc38cb6ef28adaf98f9457 Mon Sep 17 00:00:00 2001
From: Ashok Bishnoi
Date: Sun, 18 Aug 2024 14:14:04 +0530
Subject: [PATCH] nil but ...
* add how to deploy on VPS
* improve connect with Redis and MongoDB
* typo's
---
README.md | 59 +++++++++++++++++++++++++-----------
alita/config/config.go | 26 +++++-----------
alita/config/types.go | 4 +--
alita/db/admin_db.go | 3 +-
alita/db/antiflood_db.go | 3 +-
alita/db/blacklists_db.go | 3 +-
alita/db/channels_db.go | 5 +--
alita/db/chats_db.go | 3 +-
alita/db/connections_db.go | 5 +--
alita/db/db.go | 62 ++++++++++++++++++++------------------
alita/db/devs_db.go | 3 +-
alita/db/disable_db.go | 5 +--
alita/db/filters_db.go | 3 +-
alita/db/locks_db.go | 3 +-
alita/db/notes_db.go | 5 +--
alita/db/pin_db.go | 3 +-
alita/db/reports_db.go | 5 +--
alita/db/rules_db.go | 3 +-
alita/db/user_db.go | 5 +--
alita/db/warns_db.go | 7 +++--
alita/modules/antiflood.go | 2 +-
alita/utils/cache/cache.go | 39 ++++++++++++------------
go.mod | 6 ++--
go.sum | 4 +++
main.go | 10 +++---
sample.env | 3 +-
26 files changed, 157 insertions(+), 122 deletions(-)
diff --git a/README.md b/README.md
index d1752187..0425d8f9 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
-
+
@@ -17,17 +17,16 @@
-
+
-
+
-Alita is a Telegram Group managment bot made using **[Gotgbot](https://github.com/PaulSonOfLars/gotgbot)** and **[Go](https://go.dev)**, which makes it modern and faster than most of the exisitng Telegram Chat Managers.
+Alita is a Telegram Group Managment bot made using **[Gotgbot](https://github.com/PaulSonOfLars/gotgbot)** and **[Go](https://go.dev)**, which makes it modern and faster than most of the exisitng Telegram Chat Managers.
**Alita's features over other bots:**
- Modern
- Fast
-- Fully asynchronous
- Fully open-source
- Frequently updated
- Multi Language Support
@@ -35,12 +34,12 @@ Alita is a Telegram Group managment bot made using **[Gotgbot](https://github.co
Can be found on Telegram as [@Alita_Robot](https://t.me/Alita_Robot)
-Alita is currently available in 1 Language as of now:
+Alita is currently available in one Language as of now:
- **US English**
More languages can be managed in the _locales_ folder. Although we have added support for languages in bot, we still need contributors to translate the bot to other languages.
-More langauges have been added to locales folder but need some configuration.
+More languages have been added to the locales folder but need some configuration.
Help us bring more languages to the bot by contributing to the project on [Crowdin](https://crowdin.com/project/alitarobot)
@@ -50,27 +49,26 @@ Help us bring more languages to the bot by contributing to the project on [Crowd
- Linux/Windows machine (Ubuntu/Debain-based OS Preferred or Windows 10/Server2016 and later)
or
-- Docker (Easiest way to setup the bot)
+- Docker (Easiest way to set up the bot)
## How to setup
First Step!
- Star **⭐** the repository!!
-- Fork **🔱** the repository before deploying and make changes in the fork.
+- Fork **🔱** the repository before deploying and making changes in the fork.
It really motivates me to continue this project further.
-### Deploy to Heroku
-- Get your `API_ID` and `API_HASH` from [here](https://my.telegram.org/)
+### Deploy to Heroku:
- Get your Bot Token from [@BotFather](https://t.me/BotFather)
-**Note:** As it is banned with an unknown reason in heroku, follow the below steps carefully!
+**Note:** As it is banned for an unknown reason in heroku, follow the below steps carefully!
- First Fork this repo `:)`
- secondly, create an empty app in the Heroku, with a custom app name; and select Europe region for faster speed.
-- Now go to the deploy tab of your app and under deployment method select GitHub and connect it.
-- after that, type the forked repo name and select it now select main branch and enable auto deploy, at last click on deploy now button!
-
-
+- Now go to the deploy tab of your app and under deployment method, select GitHub and connect it.
+- after that, type the forked repo name and select it now select the main branch and enable auto deploy, at last click on deploy now button!
+
+
- Lastly, you must fill up all the vars in heroku (if using heroku) as directed in app.json file and now turn on the worker dyno to run it `:)`
@@ -78,6 +76,31 @@ It really motivates me to continue this project further.
- `DB_URI` : Get one from [mongodb](https://cloud.mongodb.com/)
- `OWNER_ID` : your telegram id
- `MESSAGE_DUMP` : must be start with `-100` or your bot added in as **admin**
+
+### Deploy to VPS:
+#### 1. Install Go
+Follow the instructions to install Go on your system: [Go Installation Guide](https://golang.org/doc/install)
+
+#### 2. Clone the repository
+```bash
+git clone https://github.com/divideprojects/Alita_Robot.git
+cd Alita_Robot
+```
+
+#### 3. Set up the environment
+Copy the sample environment file and edit it as needed:
+```shell
+cp sample.env .env
+vi .env
+```
+
+#### 4. Build and run the bot
+```bash
+go build -o alita_robot main.go
+./alita_robot
+```
+
+
### Traditional
- Download a binary from [releases](https://github.com/divideprojects/Alita_Robot/releases) page specific to your PC.
@@ -91,7 +114,7 @@ We currently publish a `ghcr.io/divideprojects/alita_robot` Docker image based o
Set the Environmental vars using the `-e` flag in while running the container.
-If all works well, bot should send message to the **MESSAGE_DUMP** Group!
+If all works well, bot should send a message to the **MESSAGE_DUMP** Group!
### Other
@@ -130,5 +153,5 @@ gpg --verify alita_robot_2.0.1_darwin_amd64.tar.gz.sig alita_robot_2.0.1_darwin_
### Copyright & License
-* Copyright (C) 2020-2023 by [Divkix](https://divkix.me) ❤️️
+* Copyright © 2020–2024 by [Divkix](https://divkix.me) ❤️️
* Licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 29 June 2007](https://github.com/divideprojects/Alita_Robot/blob/master/LICENSE)
diff --git a/alita/config/config.go b/alita/config/config.go
index 0074ca7d..24558af3 100644
--- a/alita/config/config.go
+++ b/alita/config/config.go
@@ -16,16 +16,14 @@ var (
BotToken string
DatabaseURI string
MainDbName string
- BotVersion string = "2.1.3"
+ BotVersion = "2.1.3"
ApiServer string
WorkingMode = "worker"
Debug = false
DropPendingUpdates = true
OwnerId int64
MessageDump int64
- RedisAddress string
- RedisPassword string
- RedisDB int
+ RedisURI string
)
// init initializes the config variables.
@@ -43,10 +41,10 @@ func init() {
},
)
- // load goenv config
- godotenv.Load()
+ // load dotenv config
+ _ = godotenv.Load()
- // set necessary variables
+ // set the necessary variables
Debug = typeConvertor{str: os.Getenv("DEBUG")}.Bool()
DropPendingUpdates = typeConvertor{str: os.Getenv("DROP_PENDING_UPDATES")}.Bool()
DatabaseURI = os.Getenv("DB_URI")
@@ -93,16 +91,8 @@ func init() {
}
// redis config
- RedisAddress = os.Getenv("REDIS_ADDRESS")
- if os.Getenv("REDIS_ADDRESS") == "" {
- RedisAddress = "localhost:6379"
- }
- RedisPassword = os.Getenv("REDIS_PASSWORD")
- if os.Getenv("REDIS_PASSWORD") == "" {
- RedisPassword = ""
- }
- RedisDB = typeConvertor{str: os.Getenv("REDIS_DB")}.Int()
- if os.Getenv("REDIS_DB") == "" {
- RedisDB = 0
+ RedisURI = os.Getenv("REDIS_URI")
+ if RedisURI == "" {
+ RedisURI = "redis://localhost:6379"
}
}
diff --git a/alita/config/types.go b/alita/config/types.go
index 797bd257..109a84e0 100644
--- a/alita/config/types.go
+++ b/alita/config/types.go
@@ -19,13 +19,13 @@ func (t typeConvertor) StringArray() []string {
return allUpdates
}
-// IntArray will return an int array from a comma separated string
+// Int Array will return an int array from a comma separated string
func (t typeConvertor) Int() int {
val, _ := strconv.Atoi(t.str)
return val
}
-// Int64Array will return an int64 array from a comma separated string
+// Int64 Array will return an int64 array from a comma separated string
func (t typeConvertor) Int64() int64 {
val, _ := strconv.ParseInt(t.str, 10, 64)
return val
diff --git a/alita/db/admin_db.go b/alita/db/admin_db.go
index bcee2531..2e26e42e 100644
--- a/alita/db/admin_db.go
+++ b/alita/db/admin_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -23,7 +24,7 @@ func checkAdminSetting(chatID int64) (adminSrc *AdminSettings) {
defaultAdminSrc := &AdminSettings{ChatId: chatID, AnonAdmin: false}
err := findOne(adminSettingsColl, bson.M{"_id": chatID}).Decode(&adminSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
adminSrc = defaultAdminSrc
err := updateOne(adminSettingsColl, bson.M{"_id": chatID}, defaultAdminSrc)
if err != nil {
diff --git a/alita/db/antiflood_db.go b/alita/db/antiflood_db.go
index f86a982a..d1174f51 100644
--- a/alita/db/antiflood_db.go
+++ b/alita/db/antiflood_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -28,7 +29,7 @@ func checkFloodSetting(chatID int64) (floodSrc *FloodSettings) {
defaultFloodSrc := &FloodSettings{ChatId: chatID, Limit: 0, Mode: defaultFloodsettingsMode}
err := findOne(antifloodSettingsColl, bson.M{"_id": chatID}).Decode(&floodSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
floodSrc = defaultFloodSrc
err := updateOne(antifloodSettingsColl, bson.M{"_id": chatID}, defaultFloodSrc)
if err != nil {
diff --git a/alita/db/blacklists_db.go b/alita/db/blacklists_db.go
index 1ba98e4b..5a5ea4b4 100644
--- a/alita/db/blacklists_db.go
+++ b/alita/db/blacklists_db.go
@@ -2,6 +2,7 @@ package db
import (
"context"
+ "errors"
"strings"
log "github.com/sirupsen/logrus"
@@ -26,7 +27,7 @@ func checkBlacklistSetting(chatID int64) (blSrc *BlacklistSettings) {
Reason: "Automated Blacklisted word %s",
}
errS := findOne(blacklistsColl, bson.M{"_id": chatID}).Decode(&blSrc)
- if errS == mongo.ErrNoDocuments {
+ if errors.Is(errS, mongo.ErrNoDocuments) {
blSrc = defaultBlacklistSrc
err := updateOne(blacklistsColl, bson.M{"_id": chatID}, defaultBlacklistSrc)
if err != nil {
diff --git a/alita/db/channels_db.go b/alita/db/channels_db.go
index 6dc97b1c..249c72d4 100644
--- a/alita/db/channels_db.go
+++ b/alita/db/channels_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -15,7 +16,7 @@ type Channel struct {
func GetChannelSettings(channelId int64) (channelSrc *Channel) {
err := findOne(channelColl, bson.M{"_id": channelId}).Decode(&channelSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
channelSrc = nil
} else if err != nil {
log.Errorf("[Database] getChannelSettings: %v - %d ", err, channelId)
@@ -52,7 +53,7 @@ func UpdateChannel(channelId int64, channelName, username string) {
func GetChannelIdByUserName(username string) int64 {
var cuids *Channel
err := findOne(channelColl, bson.M{"username": username}).Decode(&cuids)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
return 0
} else if err != nil {
log.Errorf("[Database] GetChannelByUserName: %v - %d", err, cuids.ChannelId)
diff --git a/alita/db/chats_db.go b/alita/db/chats_db.go
index 3d9f2cf7..b71f303a 100644
--- a/alita/db/chats_db.go
+++ b/alita/db/chats_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"github.com/divideprojects/Alita_Robot/alita/utils/string_handling"
@@ -19,7 +20,7 @@ type Chat struct {
func GetChatSettings(chatId int64) (chatSrc *Chat) {
err := findOne(chatColl, bson.M{"_id": chatId}).Decode(&chatSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
chatSrc = &Chat{}
} else if err != nil {
log.Errorf("[Database] getChatSettings: %v - %d ", err, chatId)
diff --git a/alita/db/connections_db.go b/alita/db/connections_db.go
index 498ee463..39efacea 100644
--- a/alita/db/connections_db.go
+++ b/alita/db/connections_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -30,7 +31,7 @@ func ToggleAllowConnect(chatID int64, pref bool) {
func GetChatConnectionSetting(chatID int64) (connectionSrc *ConnectionSettings) {
defaultConnectionSrc := &ConnectionSettings{ChatId: chatID, AllowConnect: false}
errF := findOne(connectionSettingsColl, bson.M{"_id": chatID}).Decode(&connectionSrc)
- if errF == mongo.ErrNoDocuments {
+ if errors.Is(errF, mongo.ErrNoDocuments) {
connectionSrc = defaultConnectionSrc
err := updateOne(connectionSettingsColl, bson.M{"_id": chatID}, connectionSrc)
if err != nil {
@@ -46,7 +47,7 @@ func GetChatConnectionSetting(chatID int64) (connectionSrc *ConnectionSettings)
func getUserConnectionSetting(userID int64) (connectionSrc *Connections) {
defaultConnectionSrc := &Connections{UserId: userID, Connected: false}
errF := findOne(connectionColl, bson.M{"_id": userID}).Decode(&connectionSrc)
- if errF == mongo.ErrNoDocuments {
+ if errors.Is(errF, mongo.ErrNoDocuments) {
connectionSrc = defaultConnectionSrc
err := updateOne(connectionColl, bson.M{"_id": userID}, connectionSrc)
if err != nil {
diff --git a/alita/db/db.go b/alita/db/db.go
index 1222c6a3..9400e138 100644
--- a/alita/db/db.go
+++ b/alita/db/db.go
@@ -60,46 +60,48 @@ var (
notesSettingsColl *mongo.Collection
)
-// dbInstance func
+// dbInstance initializes the MongoDB client and collections
func init() {
- mongoClient, err := mongo.NewClient(
- options.Client().ApplyURI(config.DatabaseURI),
- )
+ // Create a new MongoDB client
+ mongoClient, err := mongo.NewClient(options.Client().ApplyURI(config.DatabaseURI))
if err != nil {
- log.Errorf("[Database][Client]: %v", err)
+ log.Fatalf("[Database][Client]: %v", err)
}
ctx, cancel := context.WithTimeout(bgCtx, 10*time.Second)
defer cancel()
- err = mongoClient.Connect(ctx)
- if err != nil {
- log.Errorf("[Database][Connect]: %v", err)
+ if err = mongoClient.Connect(ctx); err != nil {
+ log.Fatalf("[Database][Connect]: %v", err)
}
- // Open Connections to Collections
+ // Get the database reference
+ db := mongoClient.Database(config.MainDbName)
+
+ // Initialize collections
log.Info("Opening Database Collections...")
- adminSettingsColl = mongoClient.Database(config.MainDbName).Collection("admin")
- blacklistsColl = mongoClient.Database(config.MainDbName).Collection("blacklists")
- pinColl = mongoClient.Database(config.MainDbName).Collection("pins")
- userColl = mongoClient.Database(config.MainDbName).Collection("users")
- reportChatColl = mongoClient.Database(config.MainDbName).Collection("report_chat_settings")
- reportUserColl = mongoClient.Database(config.MainDbName).Collection("report_user_settings")
- devsColl = mongoClient.Database(config.MainDbName).Collection("devs")
- chatColl = mongoClient.Database(config.MainDbName).Collection("chats")
- channelColl = mongoClient.Database(config.MainDbName).Collection("channels")
- antifloodSettingsColl = mongoClient.Database(config.MainDbName).Collection("antiflood_settings")
- connectionColl = mongoClient.Database(config.MainDbName).Collection("connection")
- connectionSettingsColl = mongoClient.Database(config.MainDbName).Collection("connection_settings")
- disableColl = mongoClient.Database(config.MainDbName).Collection("disable")
- rulesColl = mongoClient.Database(config.MainDbName).Collection("rules")
- warnSettingsColl = mongoClient.Database(config.MainDbName).Collection("warns_settings")
- warnUsersColl = mongoClient.Database(config.MainDbName).Collection("warns_users")
- greetingsColl = mongoClient.Database(config.MainDbName).Collection("greetings")
- lockColl = mongoClient.Database(config.MainDbName).Collection("locks")
- filterColl = mongoClient.Database(config.MainDbName).Collection("filters")
- notesColl = mongoClient.Database(config.MainDbName).Collection("notes")
- notesSettingsColl = mongoClient.Database(config.MainDbName).Collection("notes_settings")
+ adminSettingsColl = db.Collection("admin")
+ blacklistsColl = db.Collection("blacklists")
+ pinColl = db.Collection("pins")
+ userColl = db.Collection("users")
+ reportChatColl = db.Collection("report_chat_settings")
+ reportUserColl = db.Collection("report_user_settings")
+ devsColl = db.Collection("devs")
+ chatColl = db.Collection("chats")
+ channelColl = db.Collection("channels")
+ antifloodSettingsColl = db.Collection("antiflood_settings")
+ connectionColl = db.Collection("connection")
+ connectionSettingsColl = db.Collection("connection_settings")
+ disableColl = db.Collection("disable")
+ rulesColl = db.Collection("rules")
+ warnSettingsColl = db.Collection("warns_settings")
+ warnUsersColl = db.Collection("warns_users")
+ greetingsColl = db.Collection("greetings")
+ lockColl = db.Collection("locks")
+ filterColl = db.Collection("filters")
+ notesColl = db.Collection("notes")
+ notesSettingsColl = db.Collection("notes_settings")
+
log.Info("Done opening all database collections!")
}
diff --git a/alita/db/devs_db.go b/alita/db/devs_db.go
index 6c37fdc6..40a6eff6 100644
--- a/alita/db/devs_db.go
+++ b/alita/db/devs_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
"fmt"
"runtime"
@@ -14,7 +15,7 @@ import (
func GetTeamMemInfo(userID int64) (devrc *Team) {
defaultTeamMember := &Team{UserId: userID, Dev: false, Sudo: false}
err := findOne(devsColl, bson.M{"_id": userID}).Decode(&devrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
devrc = defaultTeamMember
} else if err != nil {
devrc = defaultTeamMember
diff --git a/alita/db/disable_db.go b/alita/db/disable_db.go
index c78dc7e9..9ec2b572 100644
--- a/alita/db/disable_db.go
+++ b/alita/db/disable_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -19,7 +20,7 @@ type DisableCommand struct {
func checkDisableSettings(chatID int64) (disSrc *DisableCommand) {
defaultDisrc := &DisableCommand{ChatID: chatID, Commands: make([]string, 0), ShouldDelete: false}
errS := findOne(disableColl, bson.M{"_id": chatID}).Decode(&disSrc)
- if errS == mongo.ErrNoDocuments {
+ if errors.Is(errS, mongo.ErrNoDocuments) {
disSrc = defaultDisrc
err := updateOne(disableColl, bson.M{"_id": chatID}, defaultDisrc)
if err != nil {
@@ -62,7 +63,7 @@ func IsCommandDisabled(chatId int64, cmd string) bool {
return string_handling.FindInStringSlice(GetChatDisabledCMDs(chatId), cmd)
}
-// ToggleDel Toogle Command Deleting
+// ToggleDel Toggle Command Deleting
func ToggleDel(chatId int64, pref bool) {
disableCmd := checkDisableSettings(chatId)
disableCmd.ShouldDelete = pref
diff --git a/alita/db/filters_db.go b/alita/db/filters_db.go
index 813ac0eb..c888f3a4 100644
--- a/alita/db/filters_db.go
+++ b/alita/db/filters_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
"strings"
log "github.com/sirupsen/logrus"
@@ -22,7 +23,7 @@ type ChatFilters struct {
func GetFilter(chatID int64, keyword string) (filtSrc *ChatFilters) {
err := findOne(filterColl, bson.M{"chat_id": chatID, "keyword": keyword}).Decode(&filtSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
filtSrc = &ChatFilters{}
} else if err != nil {
log.Errorf("[Database] GetFilter: %v - %d", err, chatID)
diff --git a/alita/db/locks_db.go b/alita/db/locks_db.go
index d1238eb2..a6129cf3 100644
--- a/alita/db/locks_db.go
+++ b/alita/db/locks_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
@@ -43,7 +44,7 @@ type Restrictions struct {
func checkChatLocks(chatID int64) (lockrc *Locks) {
defaultLockrc := &Locks{ChatId: chatID, Permissions: &Permissions{}, Restrictions: &Restrictions{}}
errS := findOne(lockColl, bson.M{"_id": chatID}).Decode(&lockrc)
- if errS == mongo.ErrNoDocuments {
+ if errors.Is(errS, mongo.ErrNoDocuments) {
lockrc = defaultLockrc
err := updateOne(lockColl, bson.M{"_id": chatID}, lockrc)
if err != nil {
diff --git a/alita/db/notes_db.go b/alita/db/notes_db.go
index 72de87b5..f4fbe47d 100644
--- a/alita/db/notes_db.go
+++ b/alita/db/notes_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
@@ -31,7 +32,7 @@ type ChatNotes struct {
func getNotesSettings(chatID int64) (noteSrc *NoteSettings) {
defaultNotesSrc := &NoteSettings{ChatId: chatID, PrivateNotesEnabled: false}
err := findOne(notesSettingsColl, bson.M{"_id": chatID}).Decode(¬eSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
noteSrc = defaultNotesSrc
err := updateOne(notesSettingsColl, bson.M{"_id": chatID}, noteSrc)
if err != nil {
@@ -56,7 +57,7 @@ func GetNotes(chatID int64) *NoteSettings {
func GetNote(chatID int64, keyword string) (noteSrc *ChatNotes) {
err := findOne(notesColl, bson.M{"chat_id": chatID, "note_name": keyword}).Decode(¬eSrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
noteSrc = nil
} else if err != nil {
log.Errorf("[Database] getNotesSettings: %v - %d", err, chatID)
diff --git a/alita/db/pin_db.go b/alita/db/pin_db.go
index 9cea6f04..af74f66b 100644
--- a/alita/db/pin_db.go
+++ b/alita/db/pin_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -16,7 +17,7 @@ type Pins struct {
func GetPinData(chatID int64) (pinrc *Pins) {
defaultPinrc := &Pins{ChatId: chatID, AntiChannelPin: false, CleanLinked: false}
err := findOne(pinColl, bson.M{"_id": chatID}).Decode(&pinrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
pinrc = defaultPinrc
err = updateOne(pinColl, bson.M{"_id": chatID}, pinrc)
if err != nil {
diff --git a/alita/db/reports_db.go b/alita/db/reports_db.go
index dfff7380..9db2eab2 100644
--- a/alita/db/reports_db.go
+++ b/alita/db/reports_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"github.com/divideprojects/Alita_Robot/alita/utils/string_handling"
@@ -28,7 +29,7 @@ func GetChatReportSettings(chatID int64) (reportsrc *ChatReportSettings) {
}
err := findOne(reportChatColl, bson.M{"_id": chatID}).Decode(&reportsrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
reportsrc = defReportSettings
err := updateOne(reportChatColl, bson.M{"_id": chatID}, reportsrc)
if err != nil {
@@ -87,7 +88,7 @@ func GetUserReportSettings(userId int64) (reportsrc *UserReportSettings) {
}
err := findOne(reportUserColl, bson.M{"_id": userId}).Decode(&reportsrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
reportsrc = defReportSettings
err := updateOne(reportUserColl, bson.M{"_id": userId}, reportsrc)
if err != nil {
diff --git a/alita/db/rules_db.go b/alita/db/rules_db.go
index 0bcb3590..42080419 100644
--- a/alita/db/rules_db.go
+++ b/alita/db/rules_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -18,7 +19,7 @@ type Rules struct {
func checkRulesSetting(chatID int64) (rulesrc *Rules) {
defRulesSrc := &Rules{ChatId: chatID, Rules: "", Private: false}
errS := findOne(rulesColl, bson.M{"_id": chatID}).Decode(&rulesrc)
- if errS == mongo.ErrNoDocuments {
+ if errors.Is(errS, mongo.ErrNoDocuments) {
rulesrc = defRulesSrc
err := updateOne(rulesColl, bson.M{"_id": chatID}, rulesrc)
if err != nil {
diff --git a/alita/db/user_db.go b/alita/db/user_db.go
index 6a1d39a1..a2d47fcd 100644
--- a/alita/db/user_db.go
+++ b/alita/db/user_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"github.com/PaulSonOfLars/gotgbot/v2"
@@ -27,7 +28,7 @@ func EnsureBotInDb(b *gotgbot.Bot) {
func checkUserInfo(userId int64) (userc *User) {
defaultUser := &User{UserId: userId}
errS := findOne(userColl, bson.M{"_id": userId}).Decode(&userc)
- if errS == mongo.ErrNoDocuments {
+ if errors.Is(errS, mongo.ErrNoDocuments) {
userc = nil
} else if errS != nil {
log.Errorf("[Database] checkUserInfo: %v - %d", errS, userId)
@@ -64,7 +65,7 @@ func UpdateUser(userId int64, username, name string) {
func GetUserIdByUserName(username string) int64 {
var guids *User
err := findOne(userColl, bson.M{"username": username}).Decode(&guids)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
return 0
} else if err != nil {
log.Errorf("[Database] GetUserIdByUserName: %v - %d", err, guids.UserId)
diff --git a/alita/db/warns_db.go b/alita/db/warns_db.go
index e85349d4..a8abeaca 100644
--- a/alita/db/warns_db.go
+++ b/alita/db/warns_db.go
@@ -1,6 +1,7 @@
package db
import (
+ "errors"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson"
@@ -23,7 +24,7 @@ type Warns struct {
func checkWarnSettings(chatID int64) (warnrc *WarnSettings) {
defaultWarnSettings := &WarnSettings{ChatId: chatID, WarnLimit: 3, WarnMode: "mute"}
err := findOne(warnSettingsColl, bson.M{"_id": chatID}).Decode(&warnrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
warnrc = defaultWarnSettings
err := updateOne(warnSettingsColl, bson.M{"_id": chatID}, warnrc)
if err != nil {
@@ -39,7 +40,7 @@ func checkWarnSettings(chatID int64) (warnrc *WarnSettings) {
func checkWarns(userId, chatId int64) (warnrc *Warns) {
defaultWarnSrc := &Warns{UserId: userId, ChatId: chatId, NumWarns: 0, Reasons: make([]string, 0)}
err := findOne(warnUsersColl, bson.M{"user_id": userId, "chat_id": chatId}).Decode(&warnrc)
- if err == mongo.ErrNoDocuments {
+ if errors.Is(err, mongo.ErrNoDocuments) {
warnrc = defaultWarnSrc
err := updateOne(warnUsersColl, bson.M{"user_id": userId, "chat_id": chatId}, warnrc)
if err != nil {
@@ -55,7 +56,7 @@ func checkWarns(userId, chatId int64) (warnrc *Warns) {
func WarnUser(userId, chatId int64, reason string) (int, []string) {
warnrc := checkWarns(userId, chatId)
- warnrc.NumWarns++ // Increment warns - Add 1 warn
+ warnrc.NumWarns++ // Increment warns - to Add 1 warn
// Add reason if it exists
if reason != "" {
diff --git a/alita/modules/antiflood.go b/alita/modules/antiflood.go
index 317d78fd..d157184b 100644
--- a/alita/modules/antiflood.go
+++ b/alita/modules/antiflood.go
@@ -378,7 +378,7 @@ func (m *moduleStruct) setFloodDeleter(b *gotgbot.Bot, ctx *ext.Context) error {
go db.SetFloodMsgDel(chat.Id, true)
text = tr.GetString("strings." + m.moduleName + ".flood_deleter.enabled")
case "off", "no":
- go db.SetFloodMsgDel(chat.Id, true)
+ go db.SetFloodMsgDel(chat.Id, false)
text = tr.GetString("strings." + m.moduleName + ".flood_deleter.disabled")
default:
text = tr.GetString("strings." + m.moduleName + ".flood_deleter.invalid_option")
diff --git a/alita/utils/cache/cache.go b/alita/utils/cache/cache.go
index e6758f3a..7d747861 100644
--- a/alita/utils/cache/cache.go
+++ b/alita/utils/cache/cache.go
@@ -2,21 +2,21 @@ package cache
import (
"context"
+ "github.com/divideprojects/Alita_Robot/alita/config"
+ log "github.com/sirupsen/logrus"
"github.com/PaulSonOfLars/gotgbot/v2"
"github.com/dgraph-io/ristretto"
- "github.com/divideprojects/Alita_Robot/alita/config"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/marshaler"
- redis_store "github.com/eko/gocache/store/redis/v4"
- ristretto_store "github.com/eko/gocache/store/ristretto/v4"
+ redisstore "github.com/eko/gocache/store/redis/v4"
+ ristrettostore "github.com/eko/gocache/store/ristretto/v4"
"github.com/redis/go-redis/v9"
)
var (
Context = context.Background()
Marshal *marshaler.Marshaler
- Manager *cache.ChainCache[any]
)
type AdminCache struct {
@@ -27,24 +27,25 @@ type AdminCache struct {
// InitCache initializes the cache.
func InitCache() {
- redisClient := redis.NewClient(&redis.Options{
- Addr: config.RedisAddress,
- Password: config.RedisPassword, // no password set
- DB: config.RedisDB, // use default DB
- })
- ristrettoCache, err := ristretto.NewCache(&ristretto.Config{
- NumCounters: 1000,
- MaxCost: 100,
- BufferItems: 64,
- })
+ opt, err := redis.ParseURL(config.RedisURI)
+ if err != nil {
+ log.Fatalf("failed to parse redis url: %v", err)
+ }
+
+ redisClient := redis.NewClient(opt)
+ if err = redisClient.Ping(Context).Err(); err != nil {
+ log.Fatalf("failed to ping redis: %v", err)
+ }
+
+ ristrettoCache, err := ristretto.NewCache(&ristretto.Config{NumCounters: 1000, MaxCost: 100, BufferItems: 64})
if err != nil {
- panic(err)
+ log.Fatalf("failed to create ristretto cache: %v", err)
}
- // initialize cache manager
- redisStore := redis_store.NewRedis(redisClient)
- ristrettoStore := ristretto_store.NewRistretto(ristrettoCache)
- cacheManager := cache.NewChain[any](cache.New[any](ristrettoStore), cache.New[any](redisStore))
+ cacheManager := cache.NewChain[any](
+ cache.New[any](ristrettostore.NewRistretto(ristrettoCache)),
+ cache.New[any](redisstore.NewRedis(redisClient)),
+ )
// Initializes marshaler
Marshal = marshaler.New(cacheManager)
diff --git a/go.mod b/go.mod
index 6e0d3cf9..04685b90 100644
--- a/go.mod
+++ b/go.mod
@@ -1,6 +1,6 @@
module github.com/divideprojects/Alita_Robot
-// +heroku goVersion go1.19
+// +heroku goVersion go1.22
go 1.22.0
toolchain go1.22.5
@@ -18,8 +18,8 @@ require (
github.com/redis/go-redis/v9 v9.6.1
github.com/sirupsen/logrus v1.9.3
github.com/spf13/viper v1.19.0
- go.mongodb.org/mongo-driver v1.16.0
- golang.org/x/text v0.16.0
+ go.mongodb.org/mongo-driver v1.16.1
+ golang.org/x/text v0.17.0
)
require (
diff --git a/go.sum b/go.sum
index 76f38a62..3bdce81d 100644
--- a/go.sum
+++ b/go.sum
@@ -127,6 +127,8 @@ github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver v1.16.0 h1:tpRsfBJMROVHKpdGyc1BBEzzjDUWjItxbVSZ8Ls4BQ4=
go.mongodb.org/mongo-driver v1.16.0/go.mod h1:oB6AhJQvFQL4LEHyXi6aJzQJtBiTQHiAd83l0GdFaiw=
+go.mongodb.org/mongo-driver v1.16.1 h1:rIVLL3q0IHM39dvE+z2ulZLp9ENZKThVfuvN/IiN4l8=
+go.mongodb.org/mongo-driver v1.16.1/go.mod h1:oB6AhJQvFQL4LEHyXi6aJzQJtBiTQHiAd83l0GdFaiw=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -168,6 +170,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
+golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
+golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
diff --git a/main.go b/main.go
index 76e50ea3..e375d9a8 100644
--- a/main.go
+++ b/main.go
@@ -48,7 +48,7 @@ func main() {
// Create updater and dispatcher.
dispatcher := ext.NewDispatcher(&ext.DispatcherOpts{
- // If an error is returned by a handler, log it and continue going.
+ // If a handler returns an error, log it and continue going.
Error: func(_ *gotgbot.Bot, _ *ext.Context, err error) ext.DispatcherAction {
log.Println("an error occurred while handling update:", err.Error())
return ext.DispatcherActionNoop
@@ -74,6 +74,7 @@ func main() {
if err != nil {
log.Fatalf("[Polling] Failed to start polling: %v", err)
}
+
log.Info("[Polling] Started Polling...!")
// Log the message that bot started
@@ -92,7 +93,7 @@ func main() {
},
)
if err != nil {
- log.Fatal(err)
+ log.Fatalf("[Bot] Failed to set commands: %v", err)
}
// Loading Modules
@@ -105,7 +106,7 @@ func main() {
),
)
- // send message to log group
+ // send a message to log group
_, err = b.SendMessage(config.MessageDump,
fmt.Sprintf("Started Bot!\nMode: %s\nLoaded Modules:\n%s", config.WorkingMode, alita.ListModules()),
&gotgbot.SendMessageOpts{
@@ -113,8 +114,7 @@ func main() {
},
)
if err != nil {
- log.Errorf("[Bot] Failed to send message to log group: %v", err)
- log.Fatal(err)
+ log.Fatalf("[Bot] Failed to send message to log group: %v", err)
}
// Idle, to keep updates coming in, and avoid bot stopping.
diff --git a/sample.env b/sample.env
index 58972a05..f08efa6c 100644
--- a/sample.env
+++ b/sample.env
@@ -5,6 +5,5 @@ DB_URI=
ENABLED_LOCALES=
MESSAGE_DUMP=
OWNER_ID=
-REDIS_ADDRESS=
-REDIS_PASSWORD=
+REDIS_URI=
USE_WEBHOOKS=