Skip to content

Commit

Permalink
fix: db session in commands
Browse files Browse the repository at this point in the history
  • Loading branch information
jackstar12 committed Jan 16, 2025
1 parent e1a5707 commit d2f4b67
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,35 @@
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")


def db_session(context: ContextTypes.DEFAULT_TYPE) -> AsyncSession:
return context.bot_data["session_maker"]()


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Welcome to the boltz pro fee alert bot! Use /subscribe to receive fee updates."
)


async def subscribe(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat_id
session: AsyncSession = context.bot_data["session"]

if await add_subscriber(session, chat_id):
await update.message.reply_text("You have subscribed to fee alerts!")
logging.info(f"New subscriber added: {chat_id}")
else:
await update.message.reply_text("You are already subscribed!")
async with db_session(context) as session:
chat_id = update.message.chat_id
if await add_subscriber(session, chat_id):
await update.message.reply_text("You have subscribed to fee alerts!")
logging.info(f"New subscriber added: {chat_id}")
else:
await update.message.reply_text("You are already subscribed!")


async def unsubscribe(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat_id
session: AsyncSession = context.bot_data["session"]
async with db_session(context) as session:
chat_id = update.message.chat_id

if await remove_subscriber(session, chat_id):
await update.message.reply_text("You have unsubscribed from fee alerts.")
logging.info(f"Subscriber removed: {chat_id}")
else:
await update.message.reply_text("You are not subscribed.")
if await remove_subscriber(session, chat_id):
await update.message.reply_text("You have unsubscribed from fee alerts.")
logging.info(f"Subscriber removed: {chat_id}")
else:
await update.message.reply_text("You are not subscribed.")


async def notify_subscribers(bot: Bot, session: AsyncSession, fees: float):
Expand Down Expand Up @@ -73,6 +76,7 @@ def main():

application = Application.builder().token(settings.telegram_bot_token).build()
application.bot_data["settings"] = settings
application.bot_data["session_maker"] = async_session

application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("subscribe", subscribe))
Expand Down

0 comments on commit d2f4b67

Please sign in to comment.