Skip to content

Commit

Permalink
Restore telegram chats after a restart. #882
Browse files Browse the repository at this point in the history
  • Loading branch information
theyosh committed Jan 20, 2024
1 parent 642ff78 commit cd03aa1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions migrations/0003_add_notification_states.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE "NotificationService" ADD COLUMN "state" JSON NULL;
24 changes: 22 additions & 2 deletions terrariumNotification.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,10 @@ def load_services(self):
service = service.to_dict()
if service["id"] not in self.services:
setup = copy.deepcopy(service["setup"])

# Notification states from previous run
setup['state'] = copy.deepcopy(service["state"])

if self.engine:
setup["engine"] = self.engine
setup["terrariumpi_name"] = self.engine.settings["title"]
Expand Down Expand Up @@ -2405,9 +2409,18 @@ async def start(self, update, context):
if await self._authenticate(update.message):
if update.message.chat_id not in self.setup["chat_ids"]:
self.setup["chat_ids"].append(update.message.chat_id)

# Store chat id in database for reconnecting after a restart
with orm.db_session():
service = NotificationService[self.id]
if not service.state:
service.state = {}

service.state['chat_ids'] = self.setup["chat_ids"]

await update.message.reply_text("start command received, you are now getting updates...")
else:
await update.message.reply_text("runing...")
await update.message.reply_text("running...")

async def webcamSelect(self, update, context):
if await self._authenticate(update.message):
Expand Down Expand Up @@ -2681,10 +2694,14 @@ def _run():
except Exception as ex:
logger.exception(f"Error in telegram service: {ex}")

old_chat_ids = []
if setup_data['state'] and setup_data['state']['chat_ids']:
old_chat_ids = setup_data['state']['chat_ids']

self.setup = {
"token": setup_data.get("token"),
"allowed_users": setup_data.get("allowed_users").split(","),
"chat_ids": [],
"chat_ids": old_chat_ids,
}

super().load_setup(setup_data)
Expand Down Expand Up @@ -2731,6 +2748,9 @@ def _run():
except Exception as ex:
logger.exception(f"Error in Telegram run: {ex}")

if len(old_chat_ids) > 0:
self.send_message(None, 'Reconnected', 'TerrariumPI just restarted...')

def stop(self):
async def _stop():
if self.telegram_bot is not None:
Expand Down

0 comments on commit cd03aa1

Please sign in to comment.