-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstat_handler.go
More file actions
224 lines (188 loc) · 5.93 KB
/
stat_handler.go
File metadata and controls
224 lines (188 loc) · 5.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
"fmt"
"log"
"sort"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
// handleStatCommand processes the /stat command
func handleStatCommand(bot *tgbotapi.BotAPI, messg *tgbotapi.Message) {
// Only work in groups
if !messg.Chat.IsGroup() && !messg.Chat.IsSuperGroup() {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command only works in groups.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
// Check if user is admin or owner
isAuthorized, err := isUserAuthorizedForStats(bot, messg)
if err != nil {
log.Printf("[ERROR] Failed to check authorization: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Failed to verify permissions.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
if !isAuthorized {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command is only available to group admins and bot owner.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
// Check rate limit
allowed, err := checkStatRateLimit(messg.Chat.ID)
if err != nil {
msg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("⏱️ Rate limit: %v", err))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
if !allowed {
msg := tgbotapi.NewMessage(messg.Chat.ID, "⏱️ Please wait before running /stat again.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
// Get activity stats for last 7 days
stats, err := getGroupActivityStats(messg.Chat.ID, 7)
if err != nil {
log.Printf("[ERROR] Failed to get activity stats: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Failed to retrieve statistics.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
if len(stats.UserStats) == 0 {
msg := tgbotapi.NewMessage(messg.Chat.ID, "No activity data available for the last 7 days.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
// Generate chart
chartBuffer, err := generateActivityChart(stats)
if err != nil {
log.Printf("[ERROR] Failed to generate chart: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Failed to generate chart.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
return
}
// Send chart as photo
photoMsg := tgbotapi.NewPhoto(messg.Chat.ID, tgbotapi.FileBytes{
Name: "activity_chart.png",
Bytes: chartBuffer.Bytes(),
})
photoMsg.ReplyToMessageID = messg.MessageID
photoMsg.Caption = "📊 Group Activity Statistics (Last 7 Days)"
_, err = bot.Send(photoMsg)
if err != nil {
log.Printf("[ERROR] Failed to send chart: %v", err)
return
}
// Update rate limit
err = updateStatRateLimit(messg.Chat.ID)
if err != nil {
log.Printf("[ERROR] Failed to update rate limit: %v", err)
}
// Generate GPT analysis in background
go generateStatAnalysis(bot, messg, stats)
}
// isUserAuthorizedForStats checks if user is group admin or bot owner
func isUserAuthorizedForStats(bot *tgbotapi.BotAPI, messg *tgbotapi.Message) (bool, error) {
// Check if user is bot owner
ownerID, err := getOwnerID()
if err == nil && messg.From.ID == ownerID {
return true, nil
}
// Check if user is group admin
chatConfig := tgbotapi.GetChatMemberConfig{
ChatConfigWithUser: tgbotapi.ChatConfigWithUser{
ChatID: messg.Chat.ID,
UserID: messg.From.ID,
},
}
member, err := bot.GetChatMember(chatConfig)
if err != nil {
return false, err
}
// Check if user is admin or creator
if member.IsAdministrator() || member.IsCreator() {
return true, nil
}
return false, nil
}
// generateStatAnalysis uses GPT to analyze activity patterns
func generateStatAnalysis(bot *tgbotapi.BotAPI, messg *tgbotapi.Message, stats *ActivityStats) {
if client == nil {
return
}
// Prepare data summary for GPT
summary := buildActivitySummary(stats)
prompt := fmt.Sprintf(`Analyze this Telegram group activity data:
%s
Provide a SHORT analysis with:
1. Mention top 4 contributors with their message counts in a single sentence
2. ONE interesting fun fact about the activity patterns
Keep it super brief (max 100 words total). Be casual and friendly.`, summary)
analysis, err := getGPTAnswerWithSystem(prompt, "You are a friendly data analyst who provides brief, fun insights about group chat activity.")
if err != nil {
log.Printf("[ERROR] GPT analysis failed: %v", err)
return
}
msg := tgbotapi.NewMessage(messg.Chat.ID, "🔍 *Activity Analysis*\n\n"+analysis)
msg.ParseMode = "Markdown"
msg.ReplyToMessageID = messg.MessageID
_, err = bot.Send(msg)
if err != nil {
log.Printf("[ERROR] Failed to send analysis: %v", err)
}
}
// buildActivitySummary creates a text summary of activity stats for GPT
func buildActivitySummary(stats *ActivityStats) string {
// Sort users by total messages
sort.Slice(stats.UserStats, func(i, j int) bool {
return stats.UserStats[i].TotalMessages > stats.UserStats[j].TotalMessages
})
summary := fmt.Sprintf("Group Activity Summary (Last 7 Days)\n")
summary += fmt.Sprintf("Period: %s to %s\n\n",
stats.StartTime.Format("Jan 2"),
stats.EndTime.Format("Jan 2"))
// Top contributors
summary += "Top Contributors:\n"
for i, user := range stats.UserStats {
if i >= 10 {
break
}
summary += fmt.Sprintf("%d. @%s - %d messages\n", i+1, user.UserName, user.TotalMessages)
}
// Calculate peak hours for each user
summary += "\nActivity Patterns:\n"
for i, user := range stats.UserStats {
if i >= 5 {
break
}
peakHour, peakCount := findPeakHour(user)
if peakCount > 0 {
summary += fmt.Sprintf("@%s most active at %02d:00 (%d msgs)\n",
user.UserName, peakHour, peakCount)
}
}
return summary
}
// findPeakHour finds the hour with most activity for a user
func findPeakHour(user UserActivitySummary) (int, int) {
hourCounts := make(map[int]int)
for hourBucket, count := range user.HourlyData {
hour := hourBucket.Hour()
hourCounts[hour] += count
}
maxHour := 0
maxCount := 0
for hour, count := range hourCounts {
if count > maxCount {
maxCount = count
maxHour = hour
}
}
return maxHour, maxCount
}