hass_play_music.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from plugins_func.register import register_function, ToolType, ActionResponse, Action
  2. from plugins_func.functions.hass_init import initialize_hass_handler
  3. from config.logger import setup_logging
  4. import asyncio
  5. import requests
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from core.connection import ConnectionHandler
  9. TAG = __name__
  10. logger = setup_logging()
  11. hass_play_music_function_desc = {
  12. "type": "function",
  13. "function": {
  14. "name": "hass_play_music",
  15. "description": "用户想听音乐、有声书的时候使用,在房间的媒体播放器(media_player)里播放对应音频",
  16. "parameters": {
  17. "type": "object",
  18. "properties": {
  19. "media_content_id": {
  20. "type": "string",
  21. "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random",
  22. },
  23. "entity_id": {
  24. "type": "string",
  25. "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头",
  26. },
  27. },
  28. "required": ["media_content_id", "entity_id"],
  29. },
  30. },
  31. }
  32. @register_function(
  33. "hass_play_music", hass_play_music_function_desc, ToolType.SYSTEM_CTL
  34. )
  35. def hass_play_music(conn: "ConnectionHandler", entity_id="", media_content_id="random"):
  36. try:
  37. # 执行音乐播放命令
  38. future = asyncio.run_coroutine_threadsafe(
  39. handle_hass_play_music(conn, entity_id, media_content_id), conn.loop
  40. )
  41. ha_response = future.result()
  42. return ActionResponse(
  43. action=Action.RESPONSE, result="退出意图已处理", response=ha_response
  44. )
  45. except Exception as e:
  46. logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
  47. async def handle_hass_play_music(
  48. conn: "ConnectionHandler", entity_id, media_content_id
  49. ):
  50. ha_config = initialize_hass_handler(conn)
  51. api_key = ha_config.get("api_key")
  52. base_url = ha_config.get("base_url")
  53. url = f"{base_url}/api/services/music_assistant/play_media"
  54. headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
  55. data = {"entity_id": entity_id, "media_id": media_content_id}
  56. response = requests.post(url, headers=headers, json=data)
  57. if response.status_code == 200:
  58. return f"正在播放{media_content_id}的音乐"
  59. else:
  60. return f"音乐播放失败,错误码: {response.status_code}"