| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package telegram
- import (
- "app/commons/core"
- "app/commons/model/entity"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
- "time"
- )
- // SyncGroupInfo 同步群组信息到数据库
- // 当收到群组消息时自动调用
- func SyncGroupInfo(chat *tgbotapi.Chat) {
- if chat == nil {
- return
- }
- // 只处理群组
- if chat.Type != "group" && chat.Type != "supergroup" {
- return
- }
- // 查询数据库中是否已存在该群组
- var existingGroup entity.TgGroup
- db := core.MainDb()
- err := db.Where("chat_id = ?", chat.ID).First(&existingGroup).Error
- now := time.Now().Unix()
- if err != nil {
- // 群组不存在,创建新记录
- newGroup := &entity.TgGroup{
- ChatId: chat.ID,
- ChatType: chat.Type,
- Title: chat.Title,
- Username: chat.UserName,
- Description: chat.Description,
- Status: 1, // 默认启用
- BotJoinedAt: now,
- }
- // 尝试获取成员数量
- if bot != nil {
- memberCount, err := bot.GetChatMembersCount(tgbotapi.ChatMemberCountConfig{
- ChatConfig: tgbotapi.ChatConfig{
- ChatID: chat.ID,
- },
- })
- if err == nil {
- newGroup.MemberCount = memberCount
- }
- }
- if err := db.Create(newGroup).Error; err != nil {
- core.Log.Errorf("创建群组记录失败: %v", err)
- return
- }
- core.Log.Infof("✅ 自动记录新群组: %s (ID: %d)", chat.Title, chat.ID)
- } else {
- // 群组已存在,更新信息
- updates := map[string]interface{}{
- "title": chat.Title,
- "username": chat.UserName,
- "description": chat.Description,
- "updated_at": now,
- }
- // 尝试更新成员数量
- if bot != nil {
- memberCount, err := bot.GetChatMembersCount(tgbotapi.ChatMemberCountConfig{
- ChatConfig: tgbotapi.ChatConfig{
- ChatID: chat.ID,
- },
- })
- if err == nil {
- updates["member_count"] = memberCount
- }
- }
- if err := db.Model(&existingGroup).Updates(updates).Error; err != nil {
- core.Log.Errorf("更新群组记录失败: %v", err)
- return
- }
- core.Log.Debugf("更新群组信息: %s (ID: %d)", chat.Title, chat.ID)
- }
- }
- // GetAllGroupsFromDB 从数据库获取所有群组
- func GetAllGroupsFromDB() ([]entity.TgGroup, error) {
- var groups []entity.TgGroup
- db := core.MainDb()
- err := db.Where("status = 1").Order("created_at DESC").Find(&groups).Error
- if err != nil {
- return nil, err
- }
- return groups, nil
- }
|