Skip to content

Commit

Permalink
fix +1 issue with first message check
Browse files Browse the repository at this point in the history
the issue leads to checking 2 first messages even if first-only set.
  • Loading branch information
umputun committed Nov 15, 2024
1 parent fd75fc7 commit 7663640
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
6 changes: 3 additions & 3 deletions app/events/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ func (a *admin) ReportBan(banUserStr string, msg *bot.Message) {
// to be detected by the bot. we need to update spam filter with this message and ban the user.
// the user will be baned even in training mode, but not in the dry mode.
func (a *admin) MsgHandler(update tbapi.Update) error {
shrink := func(inp string, max int) string {
if utf8.RuneCountInString(inp) <= max {
shrink := func(inp string, maxLen int) string {
if utf8.RuneCountInString(inp) <= maxLen {
return inp
}
return string([]rune(inp)[:max]) + "..."
return string([]rune(inp)[:maxLen]) + "..."
}

// try to get the forwarded user ID, this is just for logging
Expand Down
5 changes: 4 additions & 1 deletion lib/tgspam/detector.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ func NewDetector(p Config) *Detector {
if p.FirstMessagesCount > 0 {
res.FirstMessageOnly = true
}
if p.FirstMessageOnly && p.FirstMessagesCount == 0 {
res.FirstMessagesCount = 1 // default value for FirstMessagesCount if FirstMessageOnly is set
}
return res
}

Expand All @@ -117,7 +120,7 @@ func (d *Detector) Check(req spamcheck.Request) (spam bool, cr []spamcheck.Respo
defer d.lock.RUnlock()

// approved user don't need to be checked
if d.FirstMessageOnly && d.approvedUsers[req.UserID].Count > d.FirstMessagesCount {
if d.FirstMessageOnly && d.approvedUsers[req.UserID].Count >= d.FirstMessagesCount {
return false, []spamcheck.Response{{Name: "pre-approved", Spam: false, Details: "user already approved"}}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/tgspam/detector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,7 @@ func TestDetector_FirstMessagesCount(t *testing.T) {
assert.Equal(t, true, spam)
})
t.Run("first messages are ham, third is spam", func(t *testing.T) {
d := NewDetector(Config{MaxAllowedEmoji: 1, MinMsgLen: 5, FirstMessagesCount: 2, FirstMessageOnly: true})
d := NewDetector(Config{MaxAllowedEmoji: 1, MinMsgLen: 5, FirstMessagesCount: 3, FirstMessageOnly: true})

// first ham
spam, _ := d.Check(spamcheck.Request{Msg: "ham, no emojis", UserID: "123"})
Expand Down

0 comments on commit 7663640

Please sign in to comment.