TelegramAktienBot/telegram_bot/bot_updates.py
2022-04-19 08:30:25 +02:00

168 lines
5.1 KiB
Python

"""
script for regularly sending updates on shares and news based on user interval
"""
__author__ = "Florian Kellermann, Linus Eickhoff"
__date__ = "05.04.2022"
__version__ = "0.0.1"
__license__ = "None"
from calendar import month
from symtable import Symbol
from shares.share_fetcher import get_share_price
import time
import datetime
from bot import bot
import sys
from multiprocessing import Process
from apscheduler.schedulers.blocking import BlockingScheduler
from api_handling.api_handler import API_Handler
'''
* * * * * code
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └──── weekday (0->Monday, 7->Sunday)
│ │ │ └────── Month (1-12)
│ │ └──────── Day (1-31)
│ └────────── Hour (0-23)
└──────────── Minute (0-59)
example 0 8 * * * -> daily update at 8am
'''
user_ids = []
user_crontab = []
def main_loop():
""" main loop for regularly sending updates
:raises: none
:rtype: none
"""
current_time_datetime = datetime.datetime.now()
my_handler = API_Handler("https://gruppe1.testsites.info/api", "bot@example.com", "bot")
# update_for_user(5270256395, my_handler) # Debug (running test update for kevins shares)
update_crontab(current_time_datetime, my_handler)
def update_crontab(pCurrent_Time, p_my_handler):
""" Updating crontab lists every hour
:type pCurrent_Time: time when starting crontab update
:param pCurrent_Time: datetime
:raises: none
:rtype: none
"""
global user_crontab
global user_ids
p_my_handler.set_cron_interval(user_id = 1770205310, cron_interval = "8 17 * * *")
all_users = p_my_handler.get_all_users()
user_ids = []
user_crontab = []
for element in all_users:
if element["cron"] != '' and element["telegram_user_id"] != '':
user_ids.append(int(element["telegram_user_id"]))
user_crontab.append(str(element["cron"]))
print(user_ids)
update_based_on_crontab(user_ids, user_crontab)
p1 = Process(target= sleeping_time, args=(pCurrent_Time, ))
p1.start()
p3 = Process(target= update_based_on_crontab, args=(user_ids, user_crontab ) )
p3.daemon = True
p3.start()
p1.join()
p3.terminate()
p1.terminate()
update_crontab(datetime.datetime.now(), p_my_handler)
def sleeping_time(pCurrent_Time):
while True:
time_difference = datetime.datetime.now() - pCurrent_Time
print(time_difference)
if float(str(time_difference).split(':')[1]) >=1: # every minute (0:00:03.646070) -> example time code
update_crontab(datetime.datetime.now())
break
def update_based_on_crontab(p_user_ids, p_user_crontab):
my_scheduler = BlockingScheduler()
print("update based on cron")
print(len(user_ids)) #Debug
for i in range(len(p_user_ids)):
print("in loop")
cron_split = p_user_crontab[i].split(" ")
print(cron_split[4], cron_split[1], cron_split[0], cron_split[3], cron_split[2])
my_scheduler.add_job(update_for_user, 'cron', day_of_week = cron_split[4] , hour= cron_split[1] , minute = cron_split[0], month= cron_split[3] , day=cron_split[2], args=(p_user_ids[i], ))
my_scheduler.start()
def update_for_user(p_user_id, p_my_handler):
share_symbols = []
share_amounts = []
share_courses = []
my_portfolio = p_my_handler.get_user_portfolio(p_user_id)
for element in my_portfolio:
if element["count"] != '' and element["symbol"]!= '':
print(element["count"], element["symbol"])
share_symbols.append(element["symbol"])
share_amounts.append(element["count"])
share_courses.append(element["current_price"])
my_user = p_my_handler.get_user(p_user_id)
send_to_user("Hello %s this is your share update:"%str(my_user["username"]), pUser_id=p_user_id)
if len(share_symbols) != 0:
for i in range(len(share_symbols)):
my_update_message = f'Symbol: {share_symbols[i]}\nCurrent Price per Share: {share_courses[i]}\nAmount owned: {share_amounts[i]}\nTotal Investment: {float(share_courses[i]) * float(share_amounts[i])}'
send_to_user(my_update_message, pUser_id=p_user_id)
else:
send_to_user("No shares found for your account. Check https://gruppe1.testsites.info/api to change your settings and add shares.", pUser_id=p_user_id)
def send_to_user(pText, pUser_id = 1770205310):
""" Send message to user
:type pText: string
:param pText: Text to send to user
:type pUser_id: int
:param pUser_id: user to send to. per default me (Florian Kellermann)
:raises: none
:rtype: none
"""
bot.send_message(chat_id=pUser_id, text=pText)
if __name__ == "__main__":
print('This script shall not be run directly. Starting main_loop for debugging purposes.')
try:
main_loop()
sys.exit(-1)
except KeyboardInterrupt:
print("Ending")
sys.exit(-1)