summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--bot.py63
-rw-r--r--main.py41
-rw-r--r--util.py17
3 files changed, 105 insertions, 16 deletions
diff --git a/bot.py b/bot.py
index 4da8baf..8428df4 100644
--- a/bot.py
+++ b/bot.py
@@ -3,7 +3,7 @@ from urllib import parse
import requests
from dotenv import load_dotenv
-from util import setupLogger
+from util import setupLogger, getDbConn
load_dotenv()
@@ -14,17 +14,72 @@ class Bot:
def __init__(self):
self.token = os.getenv('BOT_TOKEN')
self.chatId = os.getenv('BOT_CHAT_ID')
+ self.isProcessingPolling = False
+ self.hasNewMessages = False
+ self.messages = list()
- def send_message(self, message):
+ def sendMessage(self, message):
message = parse.quote_plus(message)
- url = f'https://api.telegram.org/bot{self.token}/sendMessage?chat_id={self.chatId}&parse_mode=MarkdownV2&text={message}'
+ url = f'https://api.telegram.org/bot{self.token}/sendMessage?chat_id={self.chatId}&parse_mode=html&text={message}'
response = requests.get(url)
if response.status_code == 200:
logger.info(f'Message sent: {response.text}')
else:
logger.error(f'Error sending message: {response.text}')
+ def _dbUpdate(self, data):
+ conn = getDbConn()
+ cur = conn.cursor()
+ for data in data['result']:
+ msg = data['message']
+ msgId = msg['message_id']
+ msgDate = msg['date']
+ msgFrom = msg['from']['username']
+ text = msg['text']
+ res = cur.execute(f"SELECT id, is_read FROM incoming WHERE id = {msgId}")
+ if not res.fetchall():
+ cur.execute(f"INSERT INTO incoming VALUES ({msgId}, {msgDate}, '{msgFrom}', '{text}', False)")
+ self.hasNewMessages = True
+ conn.commit()
+ conn.close()
+
+ def _checkUnreadDb(self):
+ if not self.hasNewMessages:
+ conn = getDbConn()
+ cur = conn.cursor()
+ res = cur.execute(f"SELECT id, is_read FROM incoming WHERE is_read = 0")
+ if len(res.fetchall()) > 0:
+ self.hasNewMessages = True
+ conn.close()
+
+ def pollUpdate(self):
+ self.isProcessingPolling = True
+
+ url = f'https://api.telegram.org/bot{self.token}/getUpdates'
+ response = requests.get(url)
+ if response.status_code == 200:
+ self._dbUpdate(response.json())
+ self._checkUnreadDb()
+
+ self.isProcessingPolling = False
+
+ def getNewMessages(self):
+ result = list()
+ if not self.hasNewMessages:
+ return result
+ conn = getDbConn()
+ cur = conn.cursor()
+ resCheck = cur.execute(f"SELECT text FROM incoming WHERE is_read = False")
+ for row in resCheck.fetchall():
+ result.append(row[0])
+ cur.execute(f"UPDATE incoming SET is_read = True WHERE is_read = False")
+ conn.commit()
+ conn.close()
+ self.hasNewMessages = False
+ return result
+
if __name__ == '__main__':
bot = Bot()
- bot.send_message('*harusnya ini bold* dan ini ngga')
+ # bot.sendMessage('*harusnya ini bold* dan ini ngga')
+ bot.getNewMessages()
diff --git a/main.py b/main.py
index 4fdb82b..771059f 100644
--- a/main.py
+++ b/main.py
@@ -1,13 +1,32 @@
+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():
+ downloadCsv()
+ myScore = readCSV()
+ try:
+ myScore = 100 * float(myScore)
+ except ValueError:
+ myScore = 0
+ return myScore
+
+
+def processMessages(messages):
+ if 'update' in messages:
+ score = getScore()
+ bot.sendMessage(f"Score leantime bulan ini = {score}%")
@repeat(every().day.at("09:00"))
@@ -16,24 +35,24 @@ def main():
today = datetime.today()
weekday = today.weekday()
if weekday not in [5, 6]: # jangan ganggu aku di akhir pekan
- downloadCsv()
- myScore = readCSV()
- try:
- myScore = 100 * float(myScore)
- except ValueError:
- myScore = 0
- bot = Bot()
- msg = f'Isi leantime... score ente bulan ini {myScore}%'
+ myScore = getScore()
+ msg = f"Leantime score = {myScore}%. <i>Jangan lupa isi leantime</i>"
if (17 <= today.day <= 24) and myScore < 70: # seminggu sebelumnya udah ngingetin
- msg = f'*WARNING!* SEKARANG UDAH TANGGAL {today.day}, SCORE LEANTIME MASIH {myScore}%'
+ msg = f'<b>WARNING!</b> SEKARANG UDAH TANGGAL {today.day}, SCORE LEANTIME MASIH {myScore}%'
- bot.send_message(msg)
+ bot.sendMessage(msg)
if __name__ == '__main__':
try:
+ if not os.path.isfile(dbFile):
+ initDb()
while True:
+ if not bot.isProcessingPolling and bot.hasNewMessages:
+ processMessages(bot.getNewMessages())
+ else:
+ bot.pollUpdate()
run_pending()
- time.sleep(3600)
+ time.sleep(1)
except BaseException as e:
logger.error(repr(e))
diff --git a/util.py b/util.py
index 88bff8e..0590c49 100644
--- a/util.py
+++ b/util.py
@@ -1,13 +1,15 @@
import logging
import os
+import sqlite3
from dotenv import load_dotenv
load_dotenv()
+dbFile = 'db.sqlite3'
+
def setupLogger():
- # kayanya python logger itu singleton, bisa dipanggil berkali2
logger = logging.getLogger(__name__)
logging.basicConfig(
filename=os.getenv('LOGFILE'),
@@ -16,3 +18,16 @@ def setupLogger():
format='%(asctime)s - %(levelname)s - %(message)s'
)
return logger
+
+
+def initDb():
+ conn = sqlite3.connect(dbFile)
+ cur = conn.cursor()
+ cur.execute("CREATE TABLE incoming (id, msg_date, msg_from, text, is_read)")
+ conn.commit()
+ conn.close()
+
+
+def getDbConn():
+ conn = sqlite3.connect(dbFile)
+ return conn