stateful notifications
This commit is contained in:
parent
e7a4e90988
commit
7a8d2fe793
5 changed files with 52 additions and 15 deletions
|
@ -0,0 +1,27 @@
|
|||
"""add games_won column
|
||||
|
||||
Revision ID: ff0a728ba3da
|
||||
Revises: 15c028536ef5
|
||||
Create Date: 2022-05-24 08:31:25.684099
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ff0a728ba3da'
|
||||
down_revision = '15c028536ef5'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('notification', sa.Column('games_won', sa.Integer(), nullable=True))
|
||||
# set a default for previous won notifications
|
||||
with op.get_context().autocommit_block():
|
||||
op.execute("UPDATE notification SET games_won=1 WHERE type='won';")
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('notification', 'games_won')
|
|
@ -51,9 +51,10 @@ class NotificationHelper:
|
|||
return session.query(TableNotification).order_by(TableNotification.created_at.desc()).all()
|
||||
|
||||
@classmethod
|
||||
def insert(cls, type_of_error, message, medium, success):
|
||||
def insert(cls, type_of_error, message, medium, success, number_won):
|
||||
with Session(engine) as session:
|
||||
n = TableNotification(type=type_of_error, message=message, medium=medium, success=success)
|
||||
n = TableNotification(type=type_of_error, message=message, medium=medium, success=success,
|
||||
games_won=number_won)
|
||||
session.add(n)
|
||||
session.commit()
|
||||
|
||||
|
@ -65,7 +66,7 @@ class NotificationHelper:
|
|||
within_3_days = session.query(TableNotification) \
|
||||
.filter(func.DATE(TableNotification.created_at) >= (datetime.utcnow().date() - timedelta(days=1))) \
|
||||
.filter(func.DATE(TableNotification.created_at) <= (datetime.utcnow().date() + timedelta(days=1))) \
|
||||
.filter_by(type='won').all()
|
||||
.filter_by(type='won').order_by(TableNotification.created_at.asc()).all()
|
||||
actual = []
|
||||
for r in within_3_days:
|
||||
if r.created_at.replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal()).date() == datetime.now(
|
||||
|
|
|
@ -89,14 +89,22 @@ class EnterGiveaways:
|
|||
|
||||
won = soup.select("a[title='Giveaways Won'] div")
|
||||
if won:
|
||||
number_won = soup.select_one("a[title='Giveaways Won'] div").text
|
||||
number_won = int(soup.select_one("a[title='Giveaways Won'] div").text)
|
||||
won_notifications = NotificationHelper.get_won_notifications_today()
|
||||
if won_notifications and len(won_notifications) >= 1:
|
||||
if number_won == won_notifications[-1].games_won:
|
||||
logger.info("🆒️ Win(s) detected, but we have already notified that there are won games waiting "
|
||||
"to be received. Doing nothing.")
|
||||
elif number_won > won_notifications[-1].games_won:
|
||||
logger.info("🔥🔥 MORE win(s) detected. Notifying again.")
|
||||
self.notification.send_won(f"You won ANOTHER game. You now have {number_won} game(s) "
|
||||
f"waiting to be claimed.", number_won)
|
||||
else: # we have less games waiting to be claimed than notified, meaning some have been claimed
|
||||
logger.info("🆒️ Win(s) detected, but we have already notified that there are won games waiting "
|
||||
"to be received. Some have been claimed. Doing nothing.")
|
||||
else:
|
||||
logger.info(f"💰💰 WINNER! You have {number_won} game(s) waiting to be claimed. 💰💰")
|
||||
self.notification.send_won(f"WINNER! You have {number_won} game(s) waiting to be claimed.")
|
||||
self.notification.send_won(f"WINNER! You have {number_won} game(s) waiting to be claimed.", number_won)
|
||||
else:
|
||||
logger.debug('No wins detected. Doing nothing.')
|
||||
|
||||
|
|
|
@ -13,6 +13,7 @@ class TableNotification(Base):
|
|||
message = Column(String(300), nullable=False)
|
||||
medium = Column(String(50), nullable=False)
|
||||
success = Column(Boolean, nullable=False)
|
||||
games_won = Column(Integer, nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
|
|
|
@ -15,11 +15,11 @@ class Notification:
|
|||
self.pushover_user_key = None
|
||||
self.message_prefix = f"{message_prefix}: "
|
||||
|
||||
def send_won(self, message):
|
||||
self.__send('won', message)
|
||||
def send_won(self, message, number_won):
|
||||
self.__send('won', message, number_won)
|
||||
|
||||
def send_error(self, message):
|
||||
self.__send('error', message)
|
||||
self.__send('error', message, number_won=None)
|
||||
|
||||
def enable_pushover(self, token, user_key):
|
||||
logger.debug("Enabling pushover notifications.")
|
||||
|
@ -27,13 +27,13 @@ class Notification:
|
|||
self.pushover_token = token
|
||||
self.pushover_user_key = user_key
|
||||
|
||||
def __send(self, type_of_error, message):
|
||||
logger.debug(f"Attempting to notify: {message}")
|
||||
def __send(self, type_of_error, message, number_won=None):
|
||||
logger.debug(f"Attempting to notify: '{message}'. Won: {number_won}")
|
||||
if self.pushover:
|
||||
logger.debug("Pushover enabled. Sending message.")
|
||||
self.__pushover(type_of_error, message)
|
||||
self.__pushover(type_of_error, message, number_won)
|
||||
|
||||
def __pushover(self, type_of_error, message):
|
||||
def __pushover(self, type_of_error, message, number_won=None):
|
||||
conn = http.client.HTTPSConnection("api.pushover.net:443")
|
||||
conn.request("POST", "/1/messages.json",
|
||||
urllib.parse.urlencode({
|
||||
|
@ -48,4 +48,4 @@ class Notification:
|
|||
else:
|
||||
logger.error(f"Pushover notification failed. Code {response.getcode()}: {response.read().decode()}")
|
||||
success = False
|
||||
NotificationHelper.insert(type_of_error, f"{message}", 'pushover', success)
|
||||
NotificationHelper.insert(type_of_error, f"{message}", 'pushover', success, number_won)
|
||||
|
|
Loading…
Reference in a new issue