import asyncdispatch, telebot, strutils, options, os, json, algorithm, times type User = tuple username: string todayMsgs: int totalMsgs: int proc myCmp(x, y: User): int = if x.todayMsgs < y.todayMsgs: -1 else: 1 proc statsCommand* (bot: Telebot, command: Command): Future[bool] {.async.} = var filePath = getEnv("DATA_PATH") & "/stats/" & $(command.message.chat.id) & ".json" var text = "" if command.params == "nsfw": filePath = getEnv("DATA_PATH") & "/stats/penis/" & $(command.message.chat.id) & ".json" if not fileExists(filePath): text = "No statistics yet." else: var data = parseFile(filePath) var users: seq[User] for key, item in pairs(data["users"]): users.add((item["username"].getStr, item["todayMessagesCount"].getInt, item["totalMessagesCount"].getInt)) users.sort(myCmp, SortOrder.Descending) if command.params != "nsfw": text = "Toplist (today/total):\n" else: text = "Penislist (today/total):\n" text &= "======================\n" var id = 1 for user in users: text &= $(id) & ": " & $(user.username) & " " & $(user.todayMsgs) & "/" & $(user.totalMsgs) & "\n" inc(id) text &= "\n" text &= "today sent: " & $(data["messagesCount"]["today"]) & "\n" text &= "total sent: " & $(data["messagesCount"]["total"]) & "\n" discard await bot.sendMessage(command.message.chat.id, text, replyToMessageId = command.message.messageId) proc statsHandler* (message: Message, penis: bool) {.async.} = let user = message.fromUser.get var filePath = getEnv("DATA_PATH") & "/stats/" & $(message.chat.id) & ".json" if penis: discard existsOrCreateDir(getEnv("DATA_PATH") & "/stats/penis") filePath = getEnv("DATA_PATH") & "/stats/penis/" & $(message.chat.id) & ".json" var data = %* { "lastReset": getDateStr(now()), "messagesCount":{ "today": 0, "total": 0 }, "users": {} } if fileExists(filePath): data = parseFile(filePath) if not data.hasKey("lastReset"): data.add("lastReset", %getDateStr(now())) if not data["users"].hasKey($(user.id)): data["users"].add($(user.id), %* { "username": user.username, "todayMessagesCount": 0, "totalMessagesCount": 0 }) if not user.username.isSome: data["users"][$(user.id)]["username"] = %user.firstName else: data["users"][$(user.id)]["username"] = %user.username var num = 1 if penis: if message.text.isSome: num = message.text.get.normalize.count("penis") data["users"][$(user.id)]["todayMessagesCount"] = newJInt(data["users"][$(user.id)]["todayMessagesCount"].getInt()+num) data["users"][$(user.id)]["totalMessagesCount"] = newJInt(data["users"][$(user.id)]["totalMessagesCount"].getInt()+num) data["messagesCount"]["today"] = newJInt(data["messagesCount"]["today"].getInt()+num) data["messagesCount"]["total"] = newJInt(data["messagesCount"]["total"].getInt()+num) if getDateStr(now()) > data["lastReset"].getStr: data["messagesCount"]["today"] = %0 for id in keys(data["users"]): data["users"][id]["todayMessagesCount"] = %0 data["lastReset"] = %getDateStr(now()) writeFile(filePath, $data)