64 lines
1.4 KiB
Go
64 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"math"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
var db *sql.DB
|
|
var lastMessage = make(map[string]time.Time)
|
|
var incrementMutex = sync.Mutex{}
|
|
|
|
func init() {
|
|
var err error
|
|
db, err = sql.Open("sqlite3", "./bot.db")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
db.SetMaxOpenConns(1)
|
|
db.Exec("CREATE TABLE xp(id STRING NOT NULL UNIQUE, xp INTEGER NOT NULL)")
|
|
}
|
|
|
|
func incrementXP(dg *discordgo.Session, discordID string) {
|
|
amountToIncrement := calculateIncrement(discordID)
|
|
|
|
tx, err := db.Begin()
|
|
if err != nil {
|
|
logError(dg, "incrementXP", "begin", discordID, err)
|
|
return
|
|
}
|
|
_, err = tx.Exec("INSERT INTO xp(id, xp) VALUES(?, ?) ON CONFLICT(id) DO UPDATE SET xp = xp+?;", discordID, amountToIncrement, amountToIncrement)
|
|
if err != nil {
|
|
logError(dg, "incrementXP", "insert", discordID, err)
|
|
tx.Rollback()
|
|
return
|
|
}
|
|
err = tx.Commit()
|
|
if err != nil {
|
|
logError(dg, "incrementXP", "commit", discordID, err)
|
|
return
|
|
}
|
|
}
|
|
|
|
func calculateIncrement(discordID string) int {
|
|
incrementMutex.Lock()
|
|
defer incrementMutex.Unlock()
|
|
|
|
now := time.Now()
|
|
delta := now.Sub(lastMessage[discordID])
|
|
lastMessage[discordID] = now
|
|
|
|
if delta.Seconds() < 0 {
|
|
return 0
|
|
}
|
|
|
|
//Constructed on Desmos:
|
|
//y=\frac{100}{\left(1+e^{-\left(\frac{x-15}{3}\right)}\right)}
|
|
return int(100 / (1 + math.Pow(math.E, -((delta.Seconds()-15)/3))))
|
|
}
|