summaryrefslogtreecommitdiff
path: root/main.py
blob: 20fbfd8eb21ba1b086a7fef373dc8325c8939ea8 (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
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
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")
        startLine = max(len(lines) - numLines, 0)
        lines = lines[startLine:]
        bot.sendMessage(f"Menampilkan log. Mulai dari line: {startLine}")
        for line in lines:
            bot.sendMessage(line)
        bot.sendMessage(f"Selesai menampilkan log. Line terakhir: {maxLines}")


def processMessages(messages):
    for msg in messages:
        msg = msg.lower()
        if msg == 'update':
            logger.info("EXPLICIT SCORE UPDATE REQUESTED")
            score = getScore()
            msg = f"Score leantime bulan ini = {score}%" if score >= 0 else "Koneksi ke dashboard bermasalah"
            bot.sendMessage(msg)
        elif 'log' in msg:
            sendLog(msg)


@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:
                processMessages(bot.getNewMessages())
            else:
                bot.pollUpdate()
            run_pending()
            time.sleep(1)
    except BaseException as e:
        logger.error(repr(e))