go-dette/handle-karma.go

162 lines
4.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"bytes"
"errors"
"fmt"
"html/template"
"math/rand"
"time"
"git.nefrace.ru/nefrace/nechotron"
"git.nefrace.ru/nefrace/tongo"
"github.com/NicoNex/echotron/v3"
)
// Returns slices of good and bad triggers
func GetTriggers() map[string]int {
return map[string]int{
"+": 1,
"-": -1,
}
}
type KarmaMessageData struct {
UserTo string
UserFrom string
Change string
KarmaFrom int64
KarmaTo int64
}
func handleKarma(u *nechotron.Update) error {
from, _ := u.Ctx.Value("userfrom").(*User)
to, _ := u.Ctx.Value("userto").(*User)
mentionFrom := nechotron.UserMention(u.Message.From)
mentionTo := nechotron.UserMention(u.Message.ReplyToMessage.From)
if from.ID == to.ID {
res, err := u.AnswerMarkdown(
fmt.Sprintf("Лайкать себя \\- плохая затея, *%s*", mentionFrom))
go func() {
time.Sleep(10 * time.Second)
u.Bot.DeleteMessage(u.ChatID(), res.Result.ID)
}()
return err
}
value := u.Ctx.Value(nechotron.FilteredValue("karmaValue")).(int)
// trigger := u.Ctx.Value(nechotron.FilteredValue("karmaTrigger")).(string)
store := tongo.NewStore[KarmaShot](db)
userStore := tongo.NewStore[User](db)
tmplStore := tongo.NewStore[KarmaMessage](db)
totalFromKarma := from.Karma
if totalFromKarma <= 0 {
res, err := u.AnswerText(
fmt.Sprintf("У тебя слишком маленькая карма *\\(%d\\)*, чтобы менять её другим\\.", totalFromKarma),
&echotron.MessageOptions{ParseMode: echotron.MarkdownV2, ReplyToMessageID: u.MessageID()})
go waitAndDelete(u, u.ChatID(), res.Result.ID)
return err
}
timeThreshold := time.Now().Add(1 * -time.Minute)
recentShots, err := store.Count(
u.Ctx,
tongo.E("from", from.ID),
tongo.E("to", to.ID),
tongo.E("when", tongo.D(tongo.E("$gte", timeThreshold))))
if err != nil {
return err
}
if recentShots > 0 {
// u.DeleteMessage()
res, err := u.AnswerMarkdown(
fmt.Sprintf("*%s*, вы только недавно меняли карму *%s*\\. Подождите минуту\\.", mentionFrom, mentionTo))
go waitAndDelete(u, u.ChatID(), res.Result.ID)
return err
}
if to.ID == u.Bot.Me.ID {
if value > 0 {
u.AnswerMarkdown("*_Ой, это мне?_*")
} else {
res, err := u.AnswerMarkdown("*_Кажется, вы ошиблись адресатом :/_*")
go waitAndDelete(u, u.ChatID(), res.Result.ID)
return err
}
}
newShot := KarmaShot{
Item: tongo.NewID(),
From: from.ID,
To: to.ID,
MessageText: nechotron.GetText(u.Message.ReplyToMessage),
When: time.Now(),
Count: value,
}
store.InsertOne(u.Ctx, &newShot)
to.Karma += int64(value)
userStore.Coll.UpdateByID(
u.Ctx,
to.Id,
tongo.D(
tongo.E(
"$set", tongo.D(
tongo.E("karmaoffset", to.Karma),
),
),
),
)
totalToKarma := to.Karma
textTemplate := "Карма *{{.UserTo}} \\(теперь {{.KarmaTo}}\\)* была {{.Change}} *{{.UserFrom}} \\({{.KarmaFrom}}\\)*"
changeUp := "повышена"
changeDown := "понижена"
tmpls, err := tmplStore.GetMany(u.Ctx)
if err == nil && len(tmpls) > 0 {
tmp := tmpls[rand.Intn(len(tmpls))]
changeUp = tmp.WordPlus
changeDown = tmp.WordMinus
textTemplate = tmp.Template
}
changeText := changeUp
if value < 0 {
changeText = changeDown
}
tmpl, err := template.New("karmatext").Parse(textTemplate)
if err != nil {
return errors.Join(fmt.Errorf("can't parse karma template: %s", textTemplate), err)
}
data := KarmaMessageData{
UserTo: mentionTo,
UserFrom: mentionFrom,
KarmaTo: totalToKarma,
KarmaFrom: totalFromKarma,
Change: changeText,
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
return errors.Join(errors.New("can't execute karma template"), err)
}
_, err = u.AnswerMarkdown(buf.String())
return err
}
var topText = `
*Наш ТОП\-10 пользователей:*
%s
`
func handleTop(u *nechotron.Update, _ string) error {
store := tongo.NewStore[RatedUser](db)
users, err := store.GetMany(u.Ctx)
if err != nil {
return errors.Join(errors.New("can't get top10 users"), err)
}
text := ""
for n, u := range users {
text += fmt.Sprintf("%d \\- %s \\(%d\\)\n", n, nechotron.EscapeMd2(u.Name), u.Karma)
}
text = fmt.Sprintf(topText, text)
u.AnswerMarkdown(text)
return nil
}