I want to share how to playsound from telegram messenger

hi!

  1. create folder voice inside apps
  2. create new application telegram_bot.py
class TelegramChatBot(hass.Hass):
    """AppDaemon TelegramChatBot"""

    async def initialize(self):
        """Initialize modlue"""

        # Create the Updater and pass it your bot's token.
        token = self.args.get("token")
        self.bot = Bot(token=token)
        self.allowed_chat_ids = self.args.get("allowed_chat_ids", [])

        self.application = ApplicationBuilder().bot(self.bot).build()

        await self.application.initialize()
        await self.application.updater.start_polling()
        await self.application.start()

        self.application.add_handler(
            MessageHandler(filters.COMMAND, self.command_handler))

        self.application.add_handler(
            CallbackQueryHandler(self.callback_query_handler))

        self.application.add_handler(
            MessageHandler(filters.VOICE, self.voice_message))

    async def terminate(self):
        """Terminate application"""
        await self.application.updater.stop()
        await self.application.stop()
        await self.application.shutdown()

    async def voice_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        """Voice handling"""
        if not self.allow_access(update):
            return

        # Downloading Voice
        newfile = await context.bot.get_file(update.message.voice.file_id)

        user_id = update.effective_user.id if update.effective_user else None
        str_filename = time.strftime("%Y-%m-%d_%H-%M") + '_' + str(user_id)

        dir_path = os.path.dirname(os.path.realpath(__file__))
        input_file = os.path.join(dir_path, 'voice', str_filename + '.ogg')
        await newfile.download_to_drive(input_file)

        sound = AudioSegment.from_ogg(input_file)
        input_file_mp3 = os.path.join(dir_path, 'voice', str_filename + '.mp3')
        sound.export(input_file_mp3, format="mp3")
        time.sleep(1)

        appdaemon=self.args['appdaemon']
        url = f"{appdaemon}/app/serve_audio?file={str_filename}.mp3"
        self.log(f"URL voice message {url}")

        self.log(f"Playing hall...")
        self.call_service("media_player/volume_set",entity_id="media_player.living_room",volume_level="0.5",)
        self.call_service("media_player/play_media",entity_id="media_player.living_room",media_content_id=url,media_content_type="music",announce="true",)

        self.log(f"Playing bedroom...")
        self.call_service("media_player/volume_set",entity_id="media_player.sonos_roam_sl",volume_level="0.5",)

sample init:

Telegram ChatBot:
  class: TelegramChatBot
  module: telegram_bot
  token: 000000000:HDSSLJFSFijjsdsdjasodjojdsaojdas
  allowed_chat_ids:
      - 123456399 
  appdaemon: "http://homeassistant.local:5050" 

create second app serve_audio.py

"""Serve telegram bot voice"""

import os
from pathlib import Path

import appdaemon.plugins.hass.hassapi as hass
from aiohttp import web
import urllib.parse


class ServeAudio(hass.Hass):
    """AppDaemon ServeAudio class"""

    def initialize(self):
        """Initialize modlue"""
        self.register_route(self.serve_audio, "serve_audio")

    async def serve_audio(self, request, kwargs):
        """Process web request"""
        qs = dict(urllib.parse.parse_qsl(request.query_string))
        input_file = Path(qs.get("file")).name
        dir_path = os.path.dirname(os.path.realpath(__file__))
        input_file = os.path.join(dir_path, 'voice', input_file)
        response = web.FileResponse(input_file)
        response.headers['Content-Type'] = 'audio/mpeg'
        return response
ServeAudio:
  module: serve_audio
  class: ServeAudio

just record voice message for bot and after you can hear it in your media device.