group_helper/telegram/routines/database.go

103 lines
2.3 KiB
Go
Raw Normal View History

package routines
import (
"git.dragon-labs.de/alphyron/group_helper/logic"
"git.dragon-labs.de/alphyron/group_helper/models"
"git.dragon-labs.de/alphyron/group_helper/telegram"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"log"
)
type databaseRoutine struct {
groupHelperService logic.GroupHelperService
}
func NewDatabaseRoutine(groupHelperService logic.GroupHelperService) telegram.Routine {
return &databaseRoutine{groupHelperService: groupHelperService}
}
func (d databaseRoutine) Update(botAPI *tgbotapi.BotAPI, update *tgbotapi.Update, group *models.Group) error {
if update.Message == nil { // ignore any non-Message Updates
return nil
}
if update.Message.Chat.IsPrivate() || update.Message.Chat.IsChannel() {
return nil
}
if update.Message.NewChatMembers != nil {
for _, newUser := range *update.Message.NewChatMembers {
user, err := d.groupHelperService.GetUserByID(int64(newUser.ID))
if err != nil {
return err
}
go d.groupHelperService.UserJoinGroup(user, group)
}
config := tgbotapi.ChatConfig{
ChatID: update.Message.Chat.ID,
}
size, _ := botAPI.GetChatMembersCount(config)
group.Size = size - 1
_, err := d.groupHelperService.UpdateGroup(group)
return err
}
if update.Message.LeftChatMember != nil {
user, err := d.groupHelperService.GetUserByID(int64(update.Message.LeftChatMember.ID))
if err != nil {
2021-04-01 20:14:25 +00:00
return err
}
go func() {
success, err := d.groupHelperService.UserLeaveGroup(user, group)
log.Println(success)
log.Println(err)
}()
config := tgbotapi.ChatConfig{
ChatID: update.Message.Chat.ID,
}
size, _ := botAPI.GetChatMembersCount(config)
group.Size = size - 1
_, err = d.groupHelperService.UpdateGroup(group)
return err
}
user, err := d.groupHelperService.GetUserByID(int64(update.Message.From.ID))
if err != nil {
return err
}
isInGroup, err := d.groupHelperService.IsUserInGroup(user, group)
if err != nil {
return err
}
if !isInGroup {
chatMember, err := botAPI.GetChatMember(tgbotapi.ChatConfigWithUser{
ChatID: group.GroupID,
UserID: update.Message.From.ID,
})
if err != nil {
return err
}
if chatMember.IsMember() || chatMember.IsCreator() || chatMember.IsAdministrator() {
_, err = d.groupHelperService.UserJoinGroup(user, group)
if err != nil {
return err
}
}
}
return nil
}