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): bot.isBusy = True 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() bot.isBusy = False @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}%. Jangan lupa isi leantime" if myScore >= 0 else "Koneksi ke dashboard bermasalah" if (17 <= today.day <= 24) and (0 <= myScore < 70): # seminggu sebelumnya udah ngingetin msg = f'WARNING! 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.isBusy and bot.hasNewMessages: handleCommand(bot.getNewMessages()) else: bot.pollUpdate() run_pending() time.sleep(1) except BaseException as e: logger.error(repr(e))