ctucx.git: ctucxbot

[nimlang] A telegram bot

commit 62dd43257aea19dd45559855e49c13244e8a436e
parent 1e4788c6448067fff68526c91a07bb1776e01082
Author: ctucx <c@ctu.cx>
Date: Wed, 22 Jan 2020 17:17:14 +0100

reset daily stats on daychange
1 file changed, 16 insertions(+), 2 deletions(-)
M
src/cmd/stats.nim
|
18
++++++++++++++++--
diff --git a/src/cmd/stats.nim b/src/cmd/stats.nim
@@ -1,4 +1,4 @@
-import asyncdispatch, telebot, strutils, options, os, json, algorithm
+import asyncdispatch, telebot, strutils, options, os, json, algorithm, times
 
 type User = tuple
   username: string

@@ -46,6 +46,7 @@ proc statsHandler(message: Message) {.async.} =
   let filePath = getCurrentDir() & "/data/stats/" & $(message.chat.id) & ".json"
 
   var data = %* {
+    "lastReset": getDateStr(now()),
     "messagesCount":{
       "today": 0,
       "total": 0

@@ -56,6 +57,11 @@ proc statsHandler(message: Message) {.async.} =
   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,

@@ -64,11 +70,19 @@ proc statsHandler(message: Message) {.async.} =
     })
 
   if not user.username.isSome:
-    data["users"][$(user.id)]["username"] = newJString(user.firstName)
+    data["users"][$(user.id)]["username"] = %user.firstName
+  else:
+    data["users"][$(user.id)]["username"] = %user.username
 
   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)
   data["messagesCount"]["total"] = newJInt(data["messagesCount"]["total"].getInt()+1)
 
+  if getDateStr(now()) > data["lastReset"].getStr:
+    data["messagesCount"]["today"] = %0
+    
+    for id in keys(data["users"]):
+      data["users"][id]["todayMessagesCount"] = %0
+
   writeFile(filePath, $data)