From 6d594e944d1dff7eb41cc360025a6c6f3c7d6600 Mon Sep 17 00:00:00 2001 From: Ashok Bishnoi Date: Wed, 24 Jul 2024 22:51:49 +0530 Subject: [PATCH] Refine: allFunc --- FallenSub/dispatcher/dispatcher.go | 6 +- FallenSub/modules/fSub.go | 124 ++++++++++++++--------------- FallenSub/modules/loadModules.go | 1 - FallenSub/modules/start.go | 34 +++----- FallenSub/modules/watcher.go | 6 +- api/bot.go | 2 +- 6 files changed, 78 insertions(+), 95 deletions(-) diff --git a/FallenSub/dispatcher/dispatcher.go b/FallenSub/dispatcher/dispatcher.go index 76c13c0..10c6ccc 100644 --- a/FallenSub/dispatcher/dispatcher.go +++ b/FallenSub/dispatcher/dispatcher.go @@ -5,10 +5,10 @@ import ( "github.com/PaulSonOfLars/gotgbot/v2/ext" ) -var Dispatcher = NewDispatcher() +var Dispatcher = newDispatcher() -// NewDispatcher creates a new dispatcher and loads modules. -func NewDispatcher() *ext.Dispatcher { +// newDispatcher creates a new dispatcher and loads modules. +func newDispatcher() *ext.Dispatcher { dispatcher := ext.NewDispatcher(nil) modules.LoadModules(dispatcher) diff --git a/FallenSub/modules/fSub.go b/FallenSub/modules/fSub.go index 56707b2..f5c2526 100644 --- a/FallenSub/modules/fSub.go +++ b/FallenSub/modules/fSub.go @@ -8,96 +8,90 @@ import ( "github.com/PaulSonOfLars/gotgbot/v2/ext" ) -// SetFSub enables or disables the force sub setting in a group. +// SetFSub enables or disables Force Sub in the chat. func setFSub(b *gotgbot.Bot, ctx *ext.Context) error { - chat := ctx.EffectiveChat - msg := ctx.EffectiveMessage - user := ctx.EffectiveUser - - args := ctx.Args() - var text string - - if chat.Type == gotgbot.ChatTypePrivate { - _, _ = msg.Reply(b, "This command is only available in groups.", &gotgbot.SendMessageOpts{}) + if ctx.EffectiveChat.Type == gotgbot.ChatTypePrivate { + _, _ = ctx.EffectiveMessage.Reply(b, "This command is only available in groups.", nil) return ext.EndGroups } - userMember, _ := chat.GetMember(b, user.Id, nil) - mem := userMember.MergeChatMember() - - if mem.Status == "member" && config.OwnerId != user.Id { - _, _ = msg.Reply(b, "You must be an admin to use this command.", &gotgbot.SendMessageOpts{}) + if !isAdmin(ctx.EffectiveChat, ctx.EffectiveUser, b) { + _, _ = ctx.EffectiveMessage.Reply(b, "You must be an admin to use this command.", nil) return ext.EndGroups } - fSub := db.GetFSubSetting(chat.Id) - - repliedMsg := msg.ReplyToMessage + if repliedMsg := ctx.EffectiveMessage.ReplyToMessage; repliedMsg != nil && repliedMsg.ForwardOrigin != nil { + return handleForwardedMessage(ctx, b, repliedMsg) + } - if repliedMsg != nil && repliedMsg.ForwardOrigin != nil { - msgOrigen := msg.ReplyToMessage.ForwardOrigin.MergeMessageOrigin() - if msgOrigen.Chat.Type == gotgbot.ChatTypeChannel { - _, err := b.GetChatMember(msgOrigen.Chat.Id, b.Id, nil) - if err != nil { - _, _ = msg.Reply(b, fmt.Sprintf("Looks like I am not admin in %s [%d]", msgOrigen.Chat.Title, msgOrigen.Chat.Id), &gotgbot.SendMessageOpts{}) - config.ErrorLog.Printf("[setFSub]Error getting chat member: %s", err) - return err - } + return handleCommand(ctx, b) +} - go db.SetFSubChannel(chat.Id, msgOrigen.Chat.Id) - text = fmt.Sprintf("Force Sub enabled in %s.\nChannelID: %d", chat.Title, msgOrigen.Chat.Id) - } else { - text = "Reply to a forwarded message from a channel." - } +// isAdmin checks if the user is an admin in the chat or the owner of the bot. +func isAdmin(chat *gotgbot.Chat, user *gotgbot.User, b *gotgbot.Bot) bool { + userMember, _ := chat.GetMember(b, user.Id, nil) + return userMember.GetStatus() == "administrator" || config.OwnerId == user.Id || userMember.GetStatus() == "creator" +} - _, err := msg.Reply(b, text, &gotgbot.SendMessageOpts{}) - if err != nil { - config.ErrorLog.Printf("[setFSub]Error sending message: %s", err) - return err - } +// handleForwardedMessage enables Force Sub in the chat using a forwarded message. +func handleForwardedMessage(ctx *ext.Context, b *gotgbot.Bot, repliedMsg *gotgbot.Message) error { + msgOrigen := repliedMsg.ForwardOrigin.MergeMessageOrigin() + if msgOrigen.Chat.Type != gotgbot.ChatTypeChannel { + _, _ = ctx.EffectiveMessage.Reply(b, "Reply to a forwarded message from a channel.", nil) return ext.EndGroups } - if len(args) == 1 { - if fSub.ForceSub { - text = fmt.Sprintf("Force Sub is enabled in %s.\nChannelID: %d", chat.Title, fSub.ForceSubChannel) - } else { - text = fmt.Sprintf("Force Sub is disabled in %s.", chat.Title) - } + botMember, err := msgOrigen.Chat.GetMember(b, b.Id, nil) + if err != nil || botMember.GetStatus() != "administrator" { + _, _ = ctx.EffectiveMessage.Reply(b, fmt.Sprintf("I must be an admin in the %s to use this command.", msgOrigen.Chat.Title), nil) + return err + } + + go db.SetFSubChannel(ctx.EffectiveChat.Id, msgOrigen.Chat.Id) + db.SetFSub(ctx.EffectiveChat.Id, true) + + text := fmt.Sprintf("Force Sub enabled in %s.\nChannelID: %d", ctx.EffectiveChat.Title, msgOrigen.Chat.Id) + _, err = ctx.EffectiveMessage.Reply(b, text, nil) + return err +} + +// handleCommand enables or disables Force Sub in the chat. +func handleCommand(ctx *ext.Context, b *gotgbot.Bot) error { + fSub := db.GetFSubSetting(ctx.EffectiveChat.Id) + var text string + + if len(ctx.Args()) == 1 { + text = fmt.Sprintf("Force Sub is %s in %s.", onOff(fSub.ForceSub), ctx.EffectiveChat.Title) } else { - switch args[1] { + switch ctx.Args()[1] { case "enable", "on", "true", "y", "yes": - if fSub.ForceSub { - text = "Force Sub is already enabled." - } else { - go db.SetFSub(chat.Id, true) + if !fSub.ForceSub { + go db.SetFSub(ctx.EffectiveChat.Id, true) text = "Force Sub enabled." + } else { + text = "Force Sub is already enabled." } case "disable", "off", "false", "n", "no": - if !fSub.ForceSub { - text = "Force Sub is already disabled." - } else { - go db.SetFSub(chat.Id, false) + if fSub.ForceSub { + go db.SetFSub(ctx.EffectiveChat.Id, false) text = "Force Sub disabled." + } else { + text = "Force Sub is already disabled." } - case "unmuteall", "clear": - return unMuteAll(b, ctx) default: - text = fmt.Sprintf("Invalid argument. Use /fsub on or /fsub off; got %s\nelse reply to a forwarded msg from a channel /fsub.", args[1]) + text = "Invalid argument. Use /fsub on or /fsub off." } } - _, err := msg.Reply(b, text, &gotgbot.SendMessageOpts{}) - if err != nil { - config.ErrorLog.Printf("[setFSub]Error sending message: %s", err) - return err - } - return ext.EndGroups + _, err := ctx.EffectiveMessage.Reply(b, text, nil) + return err } -func unMuteAll(_ *gotgbot.Bot, _ *ext.Context) error { - // Todo: implement unmute all - - return ext.EndGroups +// onOff returns "enabled" if state is true, "disabled" otherwise. +func onOff(state bool) string { + if state { + return "enabled" + } + return "disabled" } diff --git a/FallenSub/modules/loadModules.go b/FallenSub/modules/loadModules.go index fb57175..4f1816e 100644 --- a/FallenSub/modules/loadModules.go +++ b/FallenSub/modules/loadModules.go @@ -12,7 +12,6 @@ func LoadModules(d *ext.Dispatcher) { d.AddHandler(handlers.NewCommand("start", start)) d.AddHandler(handlers.NewCommand("ping", ping)) d.AddHandler(handlers.NewCommand("fsub", setFSub)) - d.AddHandlerToGroup(handlers.NewMessage(message.All, fSubWatcher), 0) d.AddHandler(handlers.NewCallback(callbackquery.Prefix("unmuteMe_"), unMuteMe)) } diff --git a/FallenSub/modules/start.go b/FallenSub/modules/start.go index 34b7bb4..36a8656 100644 --- a/FallenSub/modules/start.go +++ b/FallenSub/modules/start.go @@ -8,23 +8,17 @@ import ( "time" ) -// start sends a welcome message to the user. +// start is the handler for the /start command func start(b *gotgbot.Bot, ctx *ext.Context) error { - msg := ctx.EffectiveMessage - text := fmt.Sprintf("Hello, %s!\n\nI am a bot that can help you manage your group by forcing users to join a channel before they can send messages in the group.\n\nTo get started, add me to your group and make me an admin with ban users permission. Then, set the channel that you want users to join using /fsub command.\n\nFor more information, click the button below.", msg.From.FirstName) + text := fmt.Sprintf("Hello, %s!\n\nI am a bot that can help you manage your group by forcing users to join a channel before they can send messages in the group.\n\nTo get started, add me to your group and make me an admin with ban users permission. Then, set the channel that you want users to join using /fsub command.\n\nFor more information, click the button below.", ctx.EffectiveMessage.From.FirstName) button := gotgbot.InlineKeyboardMarkup{ - InlineKeyboard: [][]gotgbot.InlineKeyboardButton{ - { - { - Text: "Help", - Url: "https://abishnoi69.github.io/Force-Sub-Bot/", - }, - }, - }, + InlineKeyboard: [][]gotgbot.InlineKeyboardButton{{{ + Text: "Help", + Url: "https://abishnoi69.github.io/Force-Sub-Bot/", + }}}, } - _, err := msg.Reply(b, text, &gotgbot.SendMessageOpts{ReplyMarkup: button}) - if err != nil { + if _, err := ctx.EffectiveMessage.Reply(b, text, &gotgbot.SendMessageOpts{ReplyMarkup: button}); err != nil { config.ErrorLog.Printf("[Start] Error sending message - %v", err) return err } @@ -32,20 +26,14 @@ func start(b *gotgbot.Bot, ctx *ext.Context) error { return ext.EndGroups } -// ping responds to a ping command with "Pong!" and the latency. +// ping is the handler for the /ping command func ping(b *gotgbot.Bot, ctx *ext.Context) error { startTime := time.Now() - msg, err := ctx.EffectiveMessage.Reply(b, "Pong!", nil) - if err != nil { + + if msg, err := ctx.EffectiveMessage.Reply(b, "Pong!", nil); err != nil { config.ErrorLog.Printf("[Ping] Error sending message - %v", err) return err - } - - // Calculate the latency - latency := time.Since(startTime) - - _, _, err = msg.EditText(b, "Pong! "+latency.String(), nil) - if err != nil { + } else if _, _, err := msg.EditText(b, "Pong! "+time.Since(startTime).String(), nil); err != nil { config.ErrorLog.Printf("[Ping] Error editing message - %v", err) return err } diff --git a/FallenSub/modules/watcher.go b/FallenSub/modules/watcher.go index 4dbf81c..f5e0b1c 100644 --- a/FallenSub/modules/watcher.go +++ b/FallenSub/modules/watcher.go @@ -32,11 +32,13 @@ func fSubWatcher(b *gotgbot.Bot, ctx *ext.Context) error { return ext.EndGroups } - if fSub.ForceSubChannel == 0 || user.IsBot || user.Id == 777000 || user.Id == 1087968824 || user.Id == config.OwnerId || ctx.EffectiveSender.IsAnonymousAdmin() { + if fSub.ForceSubChannel == 0 || user.IsBot || user.Id == 777000 || user.Id == 1087968824 || ctx.EffectiveSender.IsAnonymousAdmin() { return ext.EndGroups } - // Todo: check if the user is an admin + if isAdmin(ctx.EffectiveChat, ctx.EffectiveUser, b) { + return ext.EndGroups + } member, err := b.GetChatMember(fSub.ForceSubChannel, user.Id, nil) if err != nil { diff --git a/api/bot.go b/api/bot.go index 7d677b3..9d418c4 100644 --- a/api/bot.go +++ b/api/bot.go @@ -40,7 +40,7 @@ func Bot(w http.ResponseWriter, r *http.Request) { // Delete the webhook in case token is unauthorized. if lenAllowedTokens > 0 && allowedTokens[0] != "" && !config.FindInStringSlice(allowedTokens, botToken) { - _, _ = bot.DeleteWebhook(&gotgbot.DeleteWebhookOpts{}) // It doesn't matter if it errors + _, _ = bot.DeleteWebhook(&gotgbot.DeleteWebhookOpts{DropPendingUpdates: true}) // It doesn't matter if it errors w.WriteHeader(statusCodeSuccess) return }