from modules.database import DatabaseManager from botbuilder.core import TurnContext, CardFactory, MessageFactory from botbuilder.schema import Attachment, Activity, ActivityTypes from aiohttp.web import Response, json_response import json from typing import cast, Any class WebhookManager: def __init__(self, database: DatabaseManager): self.database = database def __load_template(self, template_name: str) -> dict: with open(f"templates/{template_name}.json", "r", encoding="utf-8") as f: return json.loads(f.read()) def _replace_placeholders(self, obj, data: dict): """Recursively replace placeholders in dict/list/string values.""" if isinstance(obj, dict): return {k: self._replace_placeholders(v, data) for k, v in obj.items()} elif isinstance(obj, list): return [self._replace_placeholders(item, data) for item in obj] elif isinstance(obj, str): return obj.format(**data) else: return obj def _create_webhooks_card(self, template: dict, data: dict) -> Attachment: # Replace placeholders in dict structure filled_template = self._replace_placeholders(template, data) print(f"Filled template: {filled_template}") # Type cast: filled_template is guaranteed to be a dict since template is a dict return CardFactory.adaptive_card( cast(dict[str, Any], filled_template) ) async def handle_list_webhooks(self, turn_context: TurnContext) -> None: try: activity = turn_context.activity channel_id = activity.channel_id # Check if the channel is a Microsoft Teams channel (msteams) or emulator (for testing) if channel_id not in ["msteams", "emulator"]: await turn_context.send_activity(f"Dieser Befehl ist nur in Microsoft Teams verfügbar.") return webhooks = self.database.get_webhooks() # Load template and prepare data template = self.__load_template("webhook-overview-card" if webhooks else "webhook-overview-no-webhooks-card") data = {"webhook_count": len(webhooks)} # Create and send the Adaptive Card card_attachment = self._create_webhooks_card(template, data) # Send the attachment directly - send_activity will create the Activity with proper fields result = await turn_context.send_activity(MessageFactory.attachment(card_attachment)) print(f"Activity sent successfully, result: {result}") except Exception as e: print(f"Error in handle_list_webhooks: {e}") import traceback traceback.print_exc() raise