group_helper/channels/leaveduserchecker.go

102 lines
2.4 KiB
Go
Raw Normal View History

package channels
import (
"git.dragon-labs.de/alphyron/group_helper/logic"
"git.dragon-labs.de/alphyron/group_helper/message"
"git.dragon-labs.de/alphyron/group_helper/models"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"log"
"time"
)
func CheckForLeavingUser(ticker *time.Ticker, quitChannel <-chan struct{}, groupHelperService logic.GroupHelperService, bot *tgbotapi.BotAPI) {
for {
select {
case <-ticker.C:
groups, err := groupHelperService.ListGroups()
if err != nil {
log.Println("Error while getting all groups in the LeavingChecking routine")
log.Println(err)
continue
}
for _, group := range groups {
time.Sleep(100 * time.Millisecond)
2021-04-01 20:14:25 +00:00
config := tgbotapi.ChatConfig{
ChatID: group.GroupID,
}
teleSize, _ := bot.GetChatMembersCount(config)
2021-04-01 20:14:25 +00:00
if teleSize == group.Size {
continue
}
2021-04-01 20:14:25 +00:00
if group.Size < teleSize {
group.Size = teleSize
2021-04-01 20:14:25 +00:00
_, err = groupHelperService.UpdateGroup(group)
continue
}
2021-04-01 20:14:25 +00:00
if teleSize < group.Size {
checkGroupUser(group, groupHelperService, bot)
groupHelperService.UpdateGroup(group)
}
}
case <-quitChannel:
ticker.Stop()
return
}
}
}
func checkGroupUser(group *models.Group, groupHelperService logic.GroupHelperService, bot *tgbotapi.BotAPI) {
rate := time.Second / 25
throttle := time.Tick(rate)
users, err := groupHelperService.ListGroupUsers(group)
if err != nil {
log.Println("Error while getting the users for group while checking for leaved user")
log.Println(err)
return
}
for _, user := range users {
<-throttle // rate limit our Service.Method RPCs
userConfig := tgbotapi.ChatConfigWithUser{
ChatID: group.GroupID,
UserID: int(user.UserID),
}
member, _ := bot.GetChatMember(userConfig)
if !member.HasLeft() {
continue
}
if !(member.User == nil || member.User.FirstName == "" || member.User.IsBot || member.User.FirstName == "Telegram") {
leaveMessage := group.UserLeaveMessage
leaveMessage = message.ReplaceMessage(leaveMessage, member.User, group)
msg := tgbotapi.NewMessage(group.GroupID, leaveMessage)
msg.ParseMode = "Markdown"
bot.Send(msg)
}
2021-04-01 20:14:25 +00:00
_, err = groupHelperService.UserLeaveGroup(user, group)
if err != nil {
log.Println(err)
}
group.Size = group.Size - 1
groupHelperService.UpdateGroup(group)
if err != nil {
log.Println(err)
}
}
}