summaryrefslogtreecommitdiff
path: root/bot.py
diff options
context:
space:
mode:
Diffstat (limited to 'bot.py')
-rw-r--r--bot.py63
1 files changed, 59 insertions, 4 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()