summaryrefslogtreecommitdiff
path: root/main.py
blob: 6753a424476db53e390c138473dd1551a0533b7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
from datetime import datetime
from downloader import downloadCsv
from csvReader import readCSV
from bot import Bot
from schedule import every, repeat, run_pending
from util import dbFile, initDb, getDbConn
import time

from util import setupLogger

logger = setupLogger()
bot = Bot()


def getScore():
    isSuccess = downloadCsv()
    if not isSuccess:
        return -1
    myScore = readCSV()
    try:
        myScore = 100 * float(myScore)
    except (TypeError, ValueError):
        myScore = 0
    return myScore


def sendLog(msg):
    numLines = msg.split(' ')[1] if len(msg.split(' ')) > 1 else 5
    try:
        numLines = int(numLines)
    except ValueError:
        numLines = 5
    with open(os.getenv('LOGFILE'), 'r') as f:
        lines = f.readlines()
        maxLines = len(lines) - 1
        if maxLines < 0:
            bot.sendMessage("Log kosong", log=False)
            return
        startLine = max(len(lines) - numLines, 0)
        lines = lines[startLine:]
        bot.sendMessage(f"Menampilkan log. Mulai dari line: {startLine}", log=False)
        for line in lines:
            bot.sendMessage(line, log=False)
        bot.sendMessage(f"Selesai menampilkan log. Line terakhir: {maxLines}", log=False)


def handleCommand(messages):
    for msg in messages:
        msg = msg.lower()
        if msg == 'update':
            logger.info("EXPLICIT SCORE UPDATE REQUESTED")
            score = getScore()
            msgSend = f"Score leantime bulan ini = {score}%" if score >= 0 else "Koneksi ke dashboard bermasalah"
            bot.sendMessage(msgSend)
        elif 'getlog' in msg:
            sendLog(msg)
        elif msg == 'cleanlog':
            open(os.getenv('LOGFILE'), 'w').close()
            bot.sendMessage("Log dihapus", log=False)
        elif msg == 'cleandb':
            connn = getDbConn()
            cur = connn.cursor()
            cur.execute("DELETE FROM incoming")
            """
            getUpdate di server telegram harus dibersihin juga, kalo ngga bakal ngeloop terus2an
            db bersih -> ngirim konfirmasi ke gw -> polling dapet data baru -> ditandai belum dibaca 
            -> ngeliat ada command cleandb di antrian -> cleandb -> ngirim konfirmasi -> polling dst
            """
            bot.cleanTelegramApiQueue()
            connn.commit()
            connn.close()
            bot.sendMessage("DB dihapus")
            logger.info("DB Cleaned")
        elif msg == 'status':
            fileStat = os.stat(os.getenv('LOGFILE'))
            msgSend = f'Log file = {fileStat.st_size / 1024}kB'
            connn = getDbConn()
            cur = connn.cursor()
            cur.execute("SELECT COUNT(*) FROM incoming")
            res = cur.fetchone()
            msgSend += f'\nDB = {res[0]} rows'
            bot.sendMessage(msgSend)
            connn.close()


@repeat(every().day.at("09:00"))
def main():
    logger.info("SCHEDULER RUN")
    today = datetime.today()
    weekday = today.weekday()
    if weekday not in [5, 6]:  # jangan ganggu aku di akhir pekan
        myScore = getScore()
        msg = f"Leantime score = {myScore}%. <i>Jangan lupa isi leantime</i>" if myScore >= 0 else "Koneksi ke dashboard bermasalah"
        if (17 <= today.day <= 24) and (0 <= myScore < 70):  # seminggu sebelumnya udah ngingetin
            msg = f'<b>WARNING!</b> SEKARANG UDAH TANGGAL {today.day}, SCORE LEANTIME MASIH {myScore}%'

        bot.sendMessage(msg)


if __name__ == '__main__':
    try:
        if not os.path.isfile(dbFile):
            logger.info("DB FILE NOT FOUND. CREATING...")
            initDb()
        while True:
            if not bot.isProcessingPolling and bot.hasNewMessages:
                handleCommand(bot.getNewMessages())
            else:
                bot.pollUpdate()
            run_pending()
            time.sleep(1)
    except BaseException as e:
        logger.error(repr(e))