ctucx.git: ctucxbot

[nimlang] A telegram bot

commit 1e4788c6448067fff68526c91a07bb1776e01082
parent 285c0c98719d6d9a005ba4ef711df1908e577289
Author: ctucx <c@ctu.cx>
Date: Mon, 20 Jan 2020 11:16:52 +0100

stats now sorted
1 file changed, 21 insertions(+), 4 deletions(-)
M
src/cmd/stats.nim
|
25
+++++++++++++++++++++----
diff --git a/src/cmd/stats.nim b/src/cmd/stats.nim
@@ -1,4 +1,12 @@
-import asyncdispatch, telebot, strutils, options, os, json
+import asyncdispatch, telebot, strutils, options, os, json, algorithm
+
+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) {.async.} =
   let filePath = getCurrentDir() & "/data/stats/" & $(command.message.chat.id) & ".json"

@@ -8,13 +16,19 @@ proc statsCommand(bot: Telebot, command: Command) {.async.} =
     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)
+
     text  = "Toplist (today/total):\n"
     text &= "======================\n"
      
     var id = 1
-    var users = data["users"]
-    for key, value in mpairs(users):
-      text &= $(id) & ": " & $(value["username"].getStr()) & " " & $(value["todayMessagesCount"]) & "/" & $(value["totalMessagesCount"]) & "\n"
+    for user in users:
+      text &= $(id) & ": " & $(user.username) & " " & $(user.todayMsgs) & "/" & $(user.totalMsgs) & "\n"
       inc(id)
 
     text &= "\n"

@@ -49,6 +63,9 @@ proc statsHandler(message: Message) {.async.} =
       "totalMessagesCount": 0
     })
 
+  if not user.username.isSome:
+    data["users"][$(user.id)]["username"] = newJString(user.firstName)
+
   data["users"][$(user.id)]["todayMessagesCount"] = newJInt(data["users"][$(user.id)]["todayMessagesCount"].getInt()+1)
   data["users"][$(user.id)]["totalMessagesCount"] = newJInt(data["users"][$(user.id)]["totalMessagesCount"].getInt()+1)
   data["messagesCount"]["today"] = newJInt(data["messagesCount"]["today"].getInt()+1)