Skip to content

Commit

Permalink
Implement the blacklist module
Browse files Browse the repository at this point in the history
Signed-off-by: ATechnoHazard <[email protected]>
  • Loading branch information
ATechnoHazard committed Jun 17, 2019
1 parent 26a9eb4 commit bc77152
Show file tree
Hide file tree
Showing 7 changed files with 237 additions and 11 deletions.
190 changes: 190 additions & 0 deletions go_bot/modules/blacklist/blacklist.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package blacklist

import (
"fmt"
"github.com/ATechnoHazard/ginko/go_bot/modules/sql"
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/chat_status"
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/error_handling"
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/extraction"
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/helpers"
"github.com/PaulSonOfLars/gotgbot"
"github.com/PaulSonOfLars/gotgbot/ext"
"github.com/PaulSonOfLars/gotgbot/handlers"
"github.com/PaulSonOfLars/gotgbot/handlers/Filters"
"html"
"log"
"regexp"
"strconv"
"strings"
)

func blacklist(_ ext.Bot, u *gotgbot.Update, args []string) error {
msg := u.EffectiveMessage
chat := u.EffectiveChat

allBlacklisted := sql.GetChatBlacklist(strconv.Itoa(chat.Id))
filterList := "Current <b>blacklisted</b> words:\n"

if len(args) > 0 && strings.ToLower(args[0]) == "copy" {
filterList = ""
for _, filter := range allBlacklisted {
filterList += fmt.Sprintf("<code>%v</code>\n", html.EscapeString(filter.Trigger))
}
} else {
for _, filter := range allBlacklisted {
filterList += fmt.Sprintf(" - <code>%v</code>\n", html.EscapeString(filter.Trigger))
}
}
splitText := helpers.SplitMessage(filterList)
for _, text := range splitText {
if text == "Current <b>blacklisted</b> words:\n" {
_, err := msg.ReplyText("There are no blacklisted messages here!")
return err
}
_, err := msg.ReplyHTML(text)
error_handling.HandleErr(err)
}
return nil
}

func addBlacklist(_ ext.Bot, u *gotgbot.Update) error {
msg := u.EffectiveMessage
chat := u.EffectiveChat

// Permission checks
if !chat_status.RequireBotAdmin(chat, msg) {
return gotgbot.EndGroups{}
}
if !chat_status.RequireUserAdmin(chat, msg, u.EffectiveUser.Id, nil) {
return gotgbot.EndGroups{}
}

words := strings.SplitN(msg.Text, " ", 2)

if len(words) > 1 {
text := words[1]
var toBlacklist []string
for _, trigger := range strings.Split(text, "\n") {
toBlacklist = append(toBlacklist, strings.TrimSpace(trigger))
}
go func(chatId string, toBlacklist []string) {
for _, trigger := range toBlacklist {
sql.AddToBlacklist(chatId, strings.ToLower(trigger))
}
}(strconv.Itoa(chat.Id), toBlacklist) // Use a goroutine to insert all blacklists in the background

if len(toBlacklist) == 1 {
_, err := msg.ReplyHTMLf("Added <code>%v</code> to the blacklist!", html.EscapeString(toBlacklist[0]))
return err
} else {
_, err := msg.ReplyHTMLf("Added <code>%v</code> triggers to the blacklist!", len(toBlacklist))
return err
}
} else {
_, err := msg.ReplyText("Tell me which words you would like to add to the blacklist.")
return err
}
}

func unblacklist(_ ext.Bot, u *gotgbot.Update) error {
msg := u.EffectiveMessage
chat := u.EffectiveChat

// Permission checks
if !chat_status.RequireBotAdmin(chat, msg) {
return gotgbot.EndGroups{}
}
if !chat_status.RequireUserAdmin(chat, msg, u.EffectiveUser.Id, nil) {
return gotgbot.EndGroups{}
}

words := strings.SplitN(msg.Text, " ", 2)
if len(words) > 1 {
text := words[1]

var toUnBlacklist []string
for _, trigger := range strings.Split(text, "\n") {
toUnBlacklist = append(toUnBlacklist, strings.TrimSpace(trigger))
}

successful := 0
for _, trigger := range toUnBlacklist {
success := sql.RmFromBlacklist(strconv.Itoa(chat.Id), strings.ToLower(trigger))
if success {
successful++
}
}

if len(toUnBlacklist) == 1 {
if successful > 0 {
_, err := msg.ReplyHTMLf("Removed <code>%v</code> from the blacklist!", html.EscapeString(toUnBlacklist[0]))
return err
} else {
_, err := msg.ReplyText("This isn't a blacklisted trigger!")
return err
}
} else if successful == len(toUnBlacklist) {
_, err := msg.ReplyHTMLf("Removed <code>%v</code> triggers from the blacklist!", successful)
return err
} else if successful == 0 {
_, err := msg.ReplyText("None of these triggers exist, so they weren't removed.")
return err
} else {
_, err := msg.ReplyHTMLf("Removed <code>%v</code> triggers from the blacklist."+
" %v did not exist, so were not removed", successful, len(toUnBlacklist)-successful)
return err
}
} else {
_, err := msg.ReplyText("Tell me which words you would like to remove from the blacklist.")
return err
}
}

func delBlacklist(_ ext.Bot, u *gotgbot.Update) error {
chat := u.EffectiveChat
msg := u.EffectiveMessage

if chat_status.IsUserAdmin(chat, u.EffectiveUser.Id, nil) {
return gotgbot.EndGroups{}
}

toMatch := extraction.ExtractText(msg)
if toMatch == "" {
return gotgbot.EndGroups{}
}
chatFilters := sql.GetChatBlacklist(strconv.Itoa(chat.Id))

for _, trigger := range chatFilters {
pattern := `( |^|[^\w])` + regexp.QuoteMeta(trigger.Trigger) + `( |$|[^\w])`
re, err := regexp.Compile("(?i)" + pattern)
error_handling.HandleErr(err)

if re.MatchString(toMatch) {
_, err := msg.Delete()
if err != nil {
if err.Error() != "Bad Request: message to delete not found" {
error_handling.HandleErr(err)
} else {
log.Println("Error while deleting blacklist message")
}
}
break
}
}
return nil
}

var customFilter handlers.FilterFunc = func(message *ext.Message) bool {
return (Filters.Text(message) || Filters.Command(message) || Filters.Sticker(message) || Filters.Photo(message)) && (Filters.Group(message))
}
var blacklistMessage = handlers.NewMessage(customFilter, delBlacklist)

func LoadBlacklist(u *gotgbot.Updater) {
defer log.Println("Loading module blacklist")
u.Dispatcher.AddHandler(handlers.NewArgsCommand("blacklist", blacklist))
u.Dispatcher.AddHandler(handlers.NewCommand("addblacklist", addBlacklist))
u.Dispatcher.AddHandler(handlers.NewCommand("rmblacklist", unblacklist))
u.Dispatcher.AddHandler(handlers.NewCommand("unblacklist", unblacklist))
blacklistMessage.AllowEdited = true
u.Dispatcher.AddHandler(blacklistMessage)
}
41 changes: 41 additions & 0 deletions go_bot/modules/sql/blacklist_sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package sql

import (
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/error_handling"
)

type BlackListFilters struct {
ChatId string `sql:",pk"`
Trigger string `sql:",pk"`
}


func AddToBlacklist(chatId string, trigger string) {
filter := &BlackListFilters{ChatId: chatId, Trigger: trigger}
_ = SESSION.Insert(filter)
}

func RmFromBlacklist(chatId string, trigger string) bool {
filter := &BlackListFilters{ChatId: chatId, Trigger: trigger}
err := SESSION.Select(filter)
if err != nil {
return false
} else {
err := SESSION.Delete(filter)
error_handling.HandleErr(err)
return true
}
}

func GetChatBlacklist(chatId string) []BlackListFilters {
var filters []BlackListFilters
err := SESSION.Model(&filters).Where("chat_id = ?", chatId).Select()
error_handling.HandleErr(err)
return filters
}

func NumBlacklistFilters(chatId string) int {
count, err := SESSION.Model((*BlackListFilters)(nil)).Where("chat_id = ?", chatId).Count()
error_handling.HandleErr(err)
return count
}
2 changes: 1 addition & 1 deletion go_bot/modules/sql/users_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type ChatMembers struct {
}

func EnsureBotInDb(u *gotgbot.Updater) {
models := []interface{}{&Users{}, &Chats{}, &ChatMembers{}}
models := []interface{}{&Users{}, &Chats{}, &ChatMembers{}, &Warns{}, &WarnFilters{}, &WarnSettings{}, &BlackListFilters{}}
for _, model := range models {
_ = SESSION.CreateTable(model, &orm.CreateTableOptions{FKConstraints: true})
}
Expand Down
8 changes: 0 additions & 8 deletions go_bot/modules/sql/warns_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package sql
import (
"fmt"
"github.com/ATechnoHazard/ginko/go_bot/modules/utils/error_handling"
"github.com/go-pg/pg/orm"
)

type Warns struct {
Expand Down Expand Up @@ -33,13 +32,6 @@ type WarnSettings struct {
SoftWarn bool `sql:",default:false"`
}

func init() {
models := []interface{}{&Warns{}, &WarnFilters{}, &WarnSettings{}}
for _, model := range models {
_ = SESSION.CreateTable(model, &orm.CreateTableOptions{FKConstraints: true})
}
}

func WarnUser(userId string, chatId string, reason string) (int, []string) {
warnedUser := &Warns{UserId: userId, ChatId: chatId}
_ = SESSION.Select(warnedUser)
Expand Down
4 changes: 2 additions & 2 deletions go_bot/modules/utils/helpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ func SplitMessage(msg string) []string {
result := make([]string, 0)
for _, line := range lines {
if len(smallMsg) + len(line) < MAX_MESSAGE_LENGTH {
smallMsg += line
smallMsg += line + "\n"
} else {
result = append(result, smallMsg)
smallMsg = line
smallMsg = line + "\n"
}
}
result = append(result, smallMsg)
Expand Down
1 change: 1 addition & 0 deletions go_bot/modules/warns/warns.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ func LoadWarns(u *gotgbot.Updater) {
u.Dispatcher.AddHandler(handlers.NewArgsCommand("warns", warns))
u.Dispatcher.AddHandler(handlers.NewCommand("addwarn", addWarnFilter))
u.Dispatcher.AddHandler(handlers.NewCommand("nowarn", removeWarnFilter))
u.Dispatcher.AddHandler(handlers.NewCommand("rmwarn", removeWarnFilter)) // Just an alias for nowarn
u.Dispatcher.AddHandler(handlers.NewCommand("warnlist", listWarnFilters))
u.Dispatcher.AddHandler(handlers.NewArgsCommand("warnlimit", setWarnLimit))
u.Dispatcher.AddHandler(handlers.NewArgsCommand("strongwarn", setWarnStrength))
Expand Down
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/ATechnoHazard/ginko/go_bot"
"github.com/ATechnoHazard/ginko/go_bot/modules/admin"
"github.com/ATechnoHazard/ginko/go_bot/modules/bans"
"github.com/ATechnoHazard/ginko/go_bot/modules/blacklist"
"github.com/ATechnoHazard/ginko/go_bot/modules/deleting"
"github.com/ATechnoHazard/ginko/go_bot/modules/misc"
"github.com/ATechnoHazard/ginko/go_bot/modules/muting"
Expand All @@ -30,6 +31,7 @@ func main() {
misc.LoadMisc(u)
muting.LoadMuting(u)
deleting.LoadDelete(u)
blacklist.LoadBlacklist(u)

sql.EnsureBotInDb(u)

Expand Down

0 comments on commit bc77152

Please sign in to comment.