Skip to content

Commit

Permalink
Refine: allFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
AshokShau committed Jul 24, 2024
1 parent 20b401f commit 6d594e9
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 95 deletions.
6 changes: 3 additions & 3 deletions FallenSub/dispatcher/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
124 changes: 59 additions & 65 deletions FallenSub/modules/fSub.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
1 change: 0 additions & 1 deletion FallenSub/modules/loadModules.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
34 changes: 11 additions & 23 deletions FallenSub/modules/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,32 @@ 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
}

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
}
Expand Down
6 changes: 4 additions & 2 deletions FallenSub/modules/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion api/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 6d594e9

Please sign in to comment.