Matrix notifications

This commit is contained in:
Brieuc Dubois 2023-12-12 09:20:22 +01:00
parent fcc4e715ee
commit b44f42547b
1 changed files with 52 additions and 17 deletions

69
main.py
View File

@ -5,18 +5,31 @@ import telegram
import asyncio import asyncio
import time import time
import datetime import datetime
import requests
client = None client = None
bot = None telegram_bot = None
removal_notification = os.environ.get('REMOVAL_NOTIFICATION')
if removal_notification is None:
removal_notification = False
def check_env(): def check_env():
return not (os.environ.get('TGTG_EMAIL') is None or os.environ.get('TELEGRAM_TOKEN') is None or os.environ.get('TELEGRAM_ID') is None) if os.environ.get('TGTG_EMAIL') is None:
return False
if os.environ.get('TELEGRAM') is None and os.environ.get('MATRIX') is None:
return False
if os.environ.get('TELEGRAM') is not None and (os.environ.get('TELEGRAM_TOKEN') is None or os.environ.get('TELEGRAM_ID') is None):
return False
if os.environ.get('MATRIX') is not None and os.environ.get('MATRIX_URL') is None:
return False
return True
def load_creds(): def load_creds():
global client, bot global client, telegram_bot
if not os.path.exists('/data/token'): if not os.path.exists('/data/token'):
client = TgtgClient(email=os.environ.get('TGTG_EMAIL')) client = TgtgClient(email=os.environ.get('TGTG_EMAIL'))
@ -31,23 +44,39 @@ def load_creds():
print('Credentials loaded from file') print('Credentials loaded from file')
client = TgtgClient(**credentials) client = TgtgClient(**credentials)
bot = telegram.Bot(os.environ['TELEGRAM_TOKEN']) if os.environ.get('TELEGRAM') is not None:
telegram_bot = telegram.Bot(os.environ['TELEGRAM_TOKEN'])
async def send_message(text): async def send_message(text):
async with bot: if os.environ.get('TELEGRAM') is not None:
await bot.send_message(chat_id=os.environ.get('TELEGRAM_ID'), text=text) async with telegram_bot:
await telegram_bot.send_message(chat_id=os.environ.get('TELEGRAM_ID'), text='\n'.join(['Too good to Go'] + text))
if os.environ.get('MATRIX') is not None:
dic = {
'title': 'Too Good to Go',
'list': text,
}
response = requests.post(
url=os.environ.get('MATRIX_URL'),
headers={
'Content-Type': 'application/json',
},
auth=(os.environ.get('MATRIX_BASIC_AUTH_USER'), os.environ.get('MATRIX_BASIC_AUTH_PASS')),
json=json.encode(dic)
)
async def main(): async def main():
await send_message('tg² bot is watching!') await send_message('tg² telegram_bot is watching!')
last = [] last = []
while True: while True:
items = client.get_items() items = client.get_items()
texts = ['Too good to go'] texts = []
next = [] next = []
@ -63,24 +92,30 @@ async def main():
name = ', '.join(filter(bool, [item_name, store_name, store_branch])) name = ', '.join(filter(bool, [item_name, store_name, store_branch]))
if not name:
name = "Panier anti-gaspi"
texts.append(f'{amount} x "{name}" ({price:.2f}€)') texts.append(f'{amount} x "{name}" ({price:.2f}€)')
# elif item["item"]["item_id"] in last: elif removal_notification and item["item"]["item_id"] in last:
# amount = item["items_available"] amount = item["items_available"]
# name = item["item"]["name"] name = item["item"]["name"]
# price = item["item"]["price_including_taxes"]["minor_units"]/(10**item["item"]["price_including_taxes"]["decimals"]) price = item["item"]["price_including_taxes"]["minor_units"]/(10**item["item"]["price_including_taxes"]["decimals"])
# store = item["store"]["store_name"] store_name = item["store"]["store_name"]
store_branch = item["store"]["branch"]
# if not name: name = ', '.join(filter(bool, [item_name, store_name, store_branch]))
# name = "Panier anti-gaspi"
# texts.append(f' - No more "{name}" ({price:.2f}€) available at "{store}"') if not name:
name = "Panier anti-gaspi"
texts.append(f'no more "{name}"')
if len(texts) > 1: if len(texts) > 1:
print(f'\n{datetime.datetime.now()}: {len(texts)-1} new items available') print(f'\n{datetime.datetime.now()}: {len(texts)-1} new items available')
await send_message('\n'.join(texts)) await send_message(texts)
else: else:
print('-', end='', flush=True) print('-', end='', flush=True)