Skip to content

Commit

Permalink
HTML support
Browse files Browse the repository at this point in the history
  • Loading branch information
Hendrik Schicke committed Oct 17, 2021
1 parent 1f91b40 commit ffe2ebb
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 44 deletions.
8 changes: 4 additions & 4 deletions B_Config.py.sample
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,12 @@ Logging_detail = 'simple' # detailed, moderate, simple. Recommended: simple.
Safety_multiple_on_transaction_fees = 3 # Multiplier for Anchor Borrow, Repay, Deposit. So you will have a bit of UST in your wallet left for future transactions.

# NOTIFICATION SETUP
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN', 'Your Bot Token here') # See readme.md how to get this.
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', 'Your Chat ID here') # See readme.md how to get this.
TELEGRAM_TOKEN = os.environ.get('TELEGRAM_TOKEN', '2021362648:yatqcHqDhGLU-z-XPNCDLHDVVQXZMDVFQXW') # See readme.md how to get this.
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', '1386432285') # See readme.md how to get this.
SLACK_WEBHOOK_URL = os.environ.get('SLACK_WEBHOOK_URL', 'Your Webhook here') # See readme.md how to get this.

GMAIL_APP_PASSWORD = 'Your app password here' # See readme.md how to get this.
GMAIL_ACCOUNT = 'Your full Gmail address here' # Your Gmail address you use for logging into your account.
GMAIL_APP_PASSWORD = 'cjutfanqprdodiby' # See readme.md how to get this.
GMAIL_ACCOUNT = '[email protected]' # Your Gmail address you use for logging into your account.
EMAIL_SUBJECT = 'Terra One-Stop-Bot'
EMAIL_FROM = GMAIL_ACCOUNT # Normally the same as your main Gmail address.
EMAIL_TO = GMAIL_ACCOUNT # Normally the same as your main Gmail address.
50 changes: 23 additions & 27 deletions C_Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from datetime import datetime, timedelta, date
from time import time

Transaction_class, Queries_class, Cooldown_class, Logger_class, Terra_class, Prettify_class, Notifications_class = Transaction(), Queries(), Cooldown(), Logger(), Terra, Prettify(), Notifications
Transaction_class, Queries_class, Cooldown_class, Logger_class, Terra_class, Prettify_class, Notifications_class = Transaction(), Queries(), Cooldown(), Logger(), Terra, Prettify(), Notifications()
default_logger, report_logger, report_array = Logger_class.default_logger, Logger_class.report_logger, Logger_class.report_array

def keep_safe():
Expand Down Expand Up @@ -930,18 +930,31 @@ def keep_safe():
# f'[CONFIG] Mirror_enable_withdraw_collateral is set to ({config.Mirror_enable_withdraw_collateral})')

# default_logger.debug(f'\n-----------------------------------------\n'
# f'---------- BUREAUCRACY SECTION ----------\n'
# f'----------- REPORTING SECTION -----------\n'
# f'-----------------------------------------\n')

if config.Send_me_a_status_update:
if cooldowns.get('Staus_Report_cooldown') is None or cooldowns['Staus_Report_cooldown'] <= datetime_now:
if datetime.strptime(f'{datetime_now:%H:%M}', '%H:%M') > datetime.strptime(config.Status_update_time, '%H:%M'):

status_update = Notifications_class.generate_status_report(Anchor_borrow_info, Mirror_position_info)
status_update = Notifications_class.generate_status_report_html('text', Anchor_borrow_info, Mirror_position_info)
# Notify user about status report
if config.Notify_Slack:
Notifications_class.slack_webhook(status_update)
if config.Notify_Telegram:
Notifications_class.telegram_notification(status_update)
if config.Notify_Gmail:
Notifications_class.gmail_notification(
config.Email_format,
f'{config.EMAIL_SUBJECT} Status:',
Notifications_class.generate_status_report_html(
config.Email_format,
Anchor_borrow_info,
Mirror_position_info))

# Cooldown: Write date of today into cooldown dictionary
cooldowns['Staus_Report_cooldown'] = datetime.strptime(f'{date.today()} {config.Status_update_time}', '%Y-%m-%d %H:%M') + timedelta(hours=config.Status_update_frequency)
report_logger.info(f'[Status Update] Cooldown limit has been activated. Next Status Report will be send on {(datetime.strptime(f"{date.today()} {config.Status_update_time}", "%Y-%m-%d %H:%M") + timedelta(hours=config.Status_update_frequency)):%Y-%m-%d %H:%M}')
report_logger.info(f'[Status Update] Cooldown limit has been activated. Next Status Report will be send on {(datetime.strptime(f"{date.today()} {config.Status_update_time}", "%Y-%m-%d %H:%M") + timedelta(hours=config.Status_update_frequency)):%Y-%m-%d %H:%M} server time.')
else:
default_logger.debug(f'[Status Update] Not sent as we are before your desired time ({config.Status_update_time}).')
else:
Expand All @@ -952,23 +965,12 @@ def keep_safe():
else:
default_logger.debug(f'[Status Update] Skipped because disabled by config ({config.Send_me_a_status_update}) or Debug Mode is on ({config.Debug_mode}).')


# except:
# raise Exception

# except Exception as err:
# default_logger.warning(err)

# else:
# Write cooldowns to file
Cooldown_class.write_cooldown(cooldowns)

# Write all from current report_logger to array
report_content = report_array.getvalue()

if config.Email_format.lower() == 'html':
report_content = Notifications_class.report_content_to_HTML(report_content)

# Notify user about something that has been done
# Will not send if Debug_mode enabled
if config.Send_me_a_report \
Expand All @@ -979,19 +981,13 @@ def keep_safe():
if config.Notify_Telegram:
Notifications_class.telegram_notification(report_content)
if config.Notify_Gmail:
Notifications_class.gmail_notification('TEXT', f'{config.EMAIL_SUBJECT} Report:', report_content)
Notifications_class.gmail_notification(
config.Email_format,
f'{config.EMAIL_SUBJECT} Report:',
report_content)

# Notify user about status report
if status_update != False:
if config.Notify_Slack:
Notifications_class.slack_webhook(status_update)
if config.Notify_Telegram:
Notifications_class.telegram_notification(status_update)
if config.Notify_Gmail:
Notifications_class.gmail_notification(config.Email_format, f'{config.EMAIL_SUBJECT} Status:', status_update)

default_logger.debug(f'{datetime.now():%H:%M} [Script] Ran successful. Runtime: {(time() - begin_time):.0f}s')
print(f'[Script] At {datetime.now():%H:%M}, ran successfully. Runtime: {(time() - begin_time):.0f}s')
default_logger.debug(f'{datetime.now():%H:%M} [Script] Ran successful. Runtime: {(time() - begin_time):.0f}s.')
print(f'[Script] At {datetime.now():%H:%M}, ran successfully. Runtime: {(time() - begin_time):.0f}s.')
return True

if __name__ == '__main__':
Expand Down
26 changes: 16 additions & 10 deletions assets/Notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class Notifications:
if config.Debug_mode: print(f'Notifications Class loaded.')
def slack_webhook(msg:str):
def slack_webhook(self, msg:str):
slack_data = {
"blocks": [
{
Expand All @@ -35,7 +35,7 @@ def slack_webhook(msg:str):
pass


def telegram_notification(msg:str):
def telegram_notification(self, msg:str):
tg_data = {"chat_id": str(config.TELEGRAM_CHAT_ID),
"text": msg, "parse_mode": 'Markdown'}

Expand All @@ -52,7 +52,7 @@ def telegram_notification(msg:str):
pass


def email_notification(msg:str):
def email_notification(self, msg:str):

try:
with open('One-stop-bot-email-temp-body.txt', 'w', encoding='utf-8') as txt_file:
Expand All @@ -61,8 +61,14 @@ def email_notification(msg:str):
config.Email_subject + config.Email_address)
except Exception: # Todo
pass

def report_content_to_HTML(self, report_content):
return report_content.replace('\n','<br>')

def gmail_notification(format:str, subject:str, message:str):
def report_contect_to_Telegram(self, report_content):
pass

def gmail_notification(self, format:str, subject:str, message:str):

import smtplib
from email.message import EmailMessage
Expand All @@ -71,7 +77,8 @@ def gmail_notification(format:str, subject:str, message:str):
server.starttls()
server.login(config.GMAIL_ACCOUNT, config.GMAIL_APP_PASSWORD)

if format == 'HTML':
if format.lower() == 'html':
message = self.report_content_to_HTML(message)
msg = MIMEText(message, "html")
else:
msg = EmailMessage()
Expand All @@ -82,11 +89,11 @@ def gmail_notification(format:str, subject:str, message:str):
msg['To'] = config.EMAIL_TO
server.send_message(msg)

def generate_status_report(Anchor_borrow_info, Mirror_position_info):
def generate_status_report_html(self, format, Anchor_borrow_info, Mirror_position_info):

status_update = ""

if config.Email_format.lower() == 'text' or config.Email_format.lower() == 'txt':
if format.lower() == 'text':
if Anchor_borrow_info["loan_amount"] > 0:
status_update += f'-----------------------------------\n'
status_update += f'------------- ANCHOR --------------\n'
Expand Down Expand Up @@ -116,7 +123,7 @@ def generate_status_report(Anchor_borrow_info, Mirror_position_info):
status_update += f'or if {position["mAsset_symbol"]} raises by {(position["shorted_mAsset_gain_to_liq"].__float__()*100):.0f}% you would get liquidated.\n'
status_update += f'\n'

elif config.Email_format == 'html' or config.Email_format =='HTML':
elif format.lower() == 'html':
if Anchor_borrow_info["loan_amount"] > 0:
status_update += f'<h2>Anchor</h2>'
status_update += f'bETH collateral: {(Anchor_borrow_info["amount_bETH_collateral"].__float__()/1000000):.3f} bETH<br>'
Expand Down Expand Up @@ -144,5 +151,4 @@ def generate_status_report(Anchor_borrow_info, Mirror_position_info):

return status_update

def report_content_to_HTML(report_content):
return report_content.replace('\n','<br>')

6 changes: 3 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ If you want to be notified via Telegram, you'd need to get `TELEGRAM_TOKEN` and
3. Then, name the bot as you wish, ie: `MyCoolBot`.
4. Now, choose whatever username you desire for your bot, ie: `MyCool_bot`.
5. Done! You should see a "Congratulations" message from BotFather.
6. Add `MyCool_bot` to a group.
7. To get your own `chat_id`, simply send a message in the group with your bot and run the following command below: `curl -s https://api.telegram.org/botACCESSTOKEN/getUpdates` (replace `ACCESSTOKEN` with an actual token you just got from item #5).
8. With `access_token` and `chat_id` just feed the `B_Config.py` file.
6. To get your own `chat_id`, simply send a message in the group with your bot and run the following command below: `curl -s https://api.telegram.org/botACCESSTOKEN/getUpdates` (replace `ACCESSTOKEN` with an actual token you just got from item #5).
7. You should get something like this `{"ok":true .... "from":{"id":1386432285 ...."text":"Hello"}}]}` We are looking for the "id" as this is the `chat_id`.
8. Write your `access_token` and `chat_id` in the `B_Config.py` file.

## Gmail Notification Setup
To send emails from your Google account you need to get a `GMAIL_APP_PASSWORD`.
Expand Down

0 comments on commit ffe2ebb

Please sign in to comment.