Skip to content
76 changes: 76 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,78 @@ async def filter(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE) ->
await context.bot.send_message(update.effective_chat.id, message, parse_mode="Markdown")


async def setresponse(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /setresponse command to save user's response template"""
try:
# Get full message text after command, preserving newlines
full_text = update.message.text
command = next(e for e in update.message.entities if e.type == "bot_command")
template_text = full_text[command.offset + command.length :]

MAX_TEMPLATE_LENGTH = 2000
if len(template_text) > MAX_TEMPLATE_LENGTH:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Template too long! Max {MAX_TEMPLATE_LENGTH} characters."
)
return

if not template_text:
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="Please provide a template text! Example:\n/setresponse Hi, I'm interested in [[address]]"
)
return

# Save to database
hestia.query_db(
"UPDATE hestia.subscribers SET response_template = %s WHERE telegram_id = %s",
(template_text, str(update.effective_chat.id))
)

# Show preview with sample address
preview = template_text.replace("[[address]]", "SampleStraat 123")
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Response template saved! Preview:\n\n{preview}"
)

except Exception as e:
logging.error(f"Error in setresponse: {str(e)}")
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="Failed to save template. Please try again later."
)


async def showresponse(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE):
"""Display the user's current response template"""
try:
template = hestia.query_db(
"SELECT response_template FROM hestia.subscribers WHERE telegram_id = %s",
[str(update.effective_chat.id)],
fetchOne=True
)["response_template"]

if template:
message = f"*Your current response template:*\n\n{template}"
else:
message = "You haven't set a response template yet. Use /setresponse to create one."

await context.bot.send_message(
chat_id=update.effective_chat.id,
text=message,
parse_mode="Markdown"
)

except Exception as e:
logging.error(f"Error in showresponse: {str(e)}")
await context.bot.send_message(
chat_id=update.effective_chat.id,
text="Failed to retrieve template. Please try again later."
)


async def donate(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE):
donation_link = hestia.get_donation_link()

Expand Down Expand Up @@ -523,6 +595,8 @@ async def callback_query_handler(update: telegram.Update, _) -> None:
async def help(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE):
message = "*I can do the following for you:*\n"
message += "/help - Show this message\n"
message += "/setresponse - Set auto-response template (use [[address]] placeholder)\n"
message += "/showresponse - View your current response template\n"
message += "/faq - Show the frequently asked questions (and answers!)\n"
message += "/start - Subscribe to updates\n"
message += "/stop - Stop recieving updates\n\n"
Expand Down Expand Up @@ -564,6 +638,8 @@ async def help(update: telegram.Update, context: ContextTypes.DEFAULT_TYPE):
application.add_handler(CommandHandler("dev", enable_dev))
application.add_handler(CommandHandler("nodev", disable_dev))
application.add_handler(CommandHandler("setdonate", set_donation_link))
application.add_handler(CommandHandler("setresponse", setresponse))
application.add_handler(CommandHandler("showresponse", showresponse))
application.add_handler(CommandHandler("help", help))
application.add_handler(CommandHandler("faq", faq))
application.add_handler(CallbackQueryHandler(callback_query_handler))
Expand Down
4 changes: 3 additions & 1 deletion hestia.ddl
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ CREATE TABLE hestia.subscribers (
date_added timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);

ALTER TABLE hestia.subscribers
ADD COLUMN response_template TEXT;

ALTER TABLE hestia.subscribers OWNER TO postgres;

Expand Down Expand Up @@ -164,4 +166,4 @@ GRANT SELECT ON TABLE hestia.targets TO hestia;

--
-- PostgreSQL database dump complete
--
--
19 changes: 18 additions & 1 deletion scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import requests
import secrets
from urllib import parse
from datetime import datetime, timedelta
from asyncio import run
from telegram.error import Forbidden
Expand Down Expand Up @@ -94,7 +95,11 @@ async def broadcast(homes: list[hestia.Home]) -> None:
message += f"{hestia.LINK_EMOJI} [{agencies[home.agency]}]({home.url})"

try:
await hestia.BOT.send_message(text=message, chat_id=sub["telegram_id"], parse_mode="MarkdownV2")
await hestia.BOT.send_message(
text=message,
chat_id=sub["telegram_id"],
parse_mode="MarkdownV2"
)
except Forbidden as e:
# This means the user deleted their account or blocked the bot, so disable them
hestia.query_db("UPDATE hestia.subscribers SET telegram_enabled = false WHERE id = %s", params=[str(sub["id"])])
Expand All @@ -103,6 +108,18 @@ async def broadcast(homes: list[hestia.Home]) -> None:
except Exception as e:
# Log any other exceptions
logging.warning(f"Failed to broadcast to {sub['telegram_id']}: {repr(e)}")

# Send response template as separate message if exists
if sub["response_template"]:
response_text = sub["response_template"].replace("[[address]]", home.address)
try:
await hestia.BOT.send_message(
text=f"Your response:\n```\n{response_text}\n```",
chat_id=sub["telegram_id"],
parse_mode=None
)
except Exception as e:
logging.warning(f"Failed to send response template to {sub['telegram_id']}: {repr(e)}")


async def scrape_site(target: dict) -> None:
Expand Down