group_sync.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package telegram
  2. import (
  3. "app/commons/core"
  4. "app/commons/model/entity"
  5. tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
  6. "time"
  7. )
  8. // SyncGroupInfo 同步群组信息到数据库
  9. // 当收到群组消息时自动调用
  10. func SyncGroupInfo(chat *tgbotapi.Chat) {
  11. if chat == nil {
  12. return
  13. }
  14. // 只处理群组
  15. if chat.Type != "group" && chat.Type != "supergroup" {
  16. return
  17. }
  18. // 查询数据库中是否已存在该群组
  19. var existingGroup entity.TgGroup
  20. db := core.MainDb()
  21. err := db.Where("chat_id = ?", chat.ID).First(&existingGroup).Error
  22. now := time.Now().Unix()
  23. if err != nil {
  24. // 群组不存在,创建新记录
  25. newGroup := &entity.TgGroup{
  26. ChatId: chat.ID,
  27. ChatType: chat.Type,
  28. Title: chat.Title,
  29. Username: chat.UserName,
  30. Description: chat.Description,
  31. Status: 1, // 默认启用
  32. BotJoinedAt: now,
  33. }
  34. // 尝试获取成员数量
  35. if bot != nil {
  36. memberCount, err := bot.GetChatMembersCount(tgbotapi.ChatMemberCountConfig{
  37. ChatConfig: tgbotapi.ChatConfig{
  38. ChatID: chat.ID,
  39. },
  40. })
  41. if err == nil {
  42. newGroup.MemberCount = memberCount
  43. }
  44. }
  45. if err := db.Create(newGroup).Error; err != nil {
  46. core.Log.Errorf("创建群组记录失败: %v", err)
  47. return
  48. }
  49. core.Log.Infof("✅ 自动记录新群组: %s (ID: %d)", chat.Title, chat.ID)
  50. } else {
  51. // 群组已存在,更新信息
  52. updates := map[string]interface{}{
  53. "title": chat.Title,
  54. "username": chat.UserName,
  55. "description": chat.Description,
  56. "updated_at": now,
  57. }
  58. // 尝试更新成员数量
  59. if bot != nil {
  60. memberCount, err := bot.GetChatMembersCount(tgbotapi.ChatMemberCountConfig{
  61. ChatConfig: tgbotapi.ChatConfig{
  62. ChatID: chat.ID,
  63. },
  64. })
  65. if err == nil {
  66. updates["member_count"] = memberCount
  67. }
  68. }
  69. if err := db.Model(&existingGroup).Updates(updates).Error; err != nil {
  70. core.Log.Errorf("更新群组记录失败: %v", err)
  71. return
  72. }
  73. core.Log.Debugf("更新群组信息: %s (ID: %d)", chat.Title, chat.ID)
  74. }
  75. }
  76. // GetAllGroupsFromDB 从数据库获取所有群组
  77. func GetAllGroupsFromDB() ([]entity.TgGroup, error) {
  78. var groups []entity.TgGroup
  79. db := core.MainDb()
  80. err := db.Where("status = 1").Order("created_at DESC").Find(&groups).Error
  81. if err != nil {
  82. return nil, err
  83. }
  84. return groups, nil
  85. }