python-amazon-echo 0.2.0__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
amazon_echo/__init__.py CHANGED
@@ -30,7 +30,7 @@ from .models import (
30
30
  )
31
31
  from .push import PushClient, PushEvent
32
32
 
33
- __version__ = "0.2.0"
33
+ __version__ = "0.3.1"
34
34
 
35
35
  __all__ = [
36
36
  "Account",
amazon_echo/client.py CHANGED
@@ -67,11 +67,14 @@ from .models import (
67
67
  Routine,
68
68
  VoiceRecord,
69
69
  )
70
+ from .phrases import timer_request
70
71
 
71
72
  _LOGGER = logging.getLogger(__name__)
72
73
 
73
74
  _TIMEOUT = aiohttp.ClientTimeout(total=30)
74
75
  _RETRY_DELAYS = (1.0, 3.0) # back-off before the 2nd and 3rd attempt on 429/503
76
+ _TIMER_POLLS = 8
77
+ _TIMER_POLL_SECONDS = 3.0
75
78
  _REAUTH_COOLDOWN = 60.0 # a 401/403 this soon after a cookie exchange is final
76
79
  _TOKEN_MARGIN = 60.0
77
80
  _HISTORY_CSRF_TTL = 12 * 3600
@@ -1425,16 +1428,32 @@ class AmazonEchoClient:
1425
1428
  )
1426
1429
  )
1427
1430
 
1428
- async def play_music(self, device: Device, provider_id: str, phrase: str) -> None:
1429
- """Play ``phrase`` from a music provider (see :meth:`get_music_providers`)."""
1431
+ async def play_music(
1432
+ self,
1433
+ device: Device,
1434
+ provider_id: str,
1435
+ phrase: str,
1436
+ *,
1437
+ timer: int | None = None,
1438
+ ) -> None:
1439
+ """Play ``phrase`` from a music provider (see :meth:`get_music_providers`).
1440
+
1441
+ Args:
1442
+ device: The device that plays.
1443
+ provider_id: A key of :meth:`get_music_providers`.
1444
+ phrase: What to search for.
1445
+ timer: Stop after this many seconds (a sleep timer).
1446
+
1447
+ """
1448
+ payload: dict[str, Any] = {
1449
+ "searchPhrase": phrase,
1450
+ "sanitizedSearchPhrase": phrase,
1451
+ "musicProviderId": provider_id,
1452
+ }
1453
+ if timer:
1454
+ payload["waitTimeInSeconds"] = timer
1430
1455
  await self._run(
1431
- await self._node(
1432
- device,
1433
- "Alexa.Music.PlaySearchPhrase",
1434
- searchPhrase=phrase,
1435
- sanitizedSearchPhrase=phrase,
1436
- musicProviderId=provider_id,
1437
- )
1456
+ await self._node(device, "Alexa.Music.PlaySearchPhrase", **payload)
1438
1457
  )
1439
1458
 
1440
1459
  async def launch_skill(self, device: Device, skill_id: str) -> None:
@@ -1582,6 +1601,7 @@ class AmazonEchoClient:
1582
1601
  *,
1583
1602
  label: str | None = None,
1584
1603
  recurrence: str | None = None,
1604
+ music: Notification | None = None,
1585
1605
  ) -> Notification:
1586
1606
  """Create an alarm.
1587
1607
 
@@ -1592,6 +1612,14 @@ class AmazonEchoClient:
1592
1612
  label: Not supported by Amazon for alarms; accepted and ignored.
1593
1613
  recurrence: ``DAILY``, ``WEEKDAYS``, ``WEEKENDS``, ``WEEKLY`` or a
1594
1614
  day list such as ``MO,WE,FR``.
1615
+ music: An existing music alarm of the account; the new alarm
1616
+ wakes with the same station. Amazon has no public way to
1617
+ search for a station, so one that was picked in the Alexa app
1618
+ is reused (the ``MUSIC-<id>`` tone :meth:`enable_alarm` sends;
1619
+ this request has not been replayed against Amazon).
1620
+
1621
+ Raises:
1622
+ AmazonEchoNotSupportedError: ``music`` is not a music alarm.
1595
1623
 
1596
1624
  """
1597
1625
  del label
@@ -1599,17 +1627,20 @@ class AmazonEchoClient:
1599
1627
  trigger: dict[str, Any] = {"scheduledTime": local.isoformat(timespec="seconds")}
1600
1628
  if recurrence:
1601
1629
  trigger["recurrence"] = _recurrence_rule(recurrence, local)
1630
+ body: dict[str, Any] = {
1631
+ "trigger": trigger,
1632
+ "extensions": [],
1633
+ "endpointId": f"{device.serial}@{device.device_type}",
1634
+ }
1635
+ if music is not None:
1636
+ if not (music_id := music.raw.get("musicAlarmId")):
1637
+ raise AmazonEchoNotSupportedError("Not a music alarm")
1638
+ body["assets"] = [{"type": "TONE", "assetId": f"MUSIC-{music_id}"}]
1602
1639
  known = {item.id for item in await self.get_notifications()}
1603
- await self._alerts(
1604
- "POST",
1605
- "alarms",
1606
- {
1607
- "trigger": trigger,
1608
- "extensions": [],
1609
- "endpointId": f"{device.serial}@{device.device_type}",
1610
- },
1640
+ await self._alerts("POST", "alarms", body)
1641
+ return await self._find_new(
1642
+ device, "alarm" if music is None else "music_alarm", known
1611
1643
  )
1612
- return await self._find_new(device, "alarm", known)
1613
1644
 
1614
1645
  async def create_reminder(
1615
1646
  self, device: Device, when: datetime, label: str
@@ -1648,30 +1679,45 @@ class AmazonEchoClient:
1648
1679
  raise AmazonEchoResponseError(200, "No reminder in the answer")
1649
1680
 
1650
1681
  async def create_timer(
1651
- self, device: Device, duration: timedelta, *, label: str | None = None
1682
+ self,
1683
+ device: Device,
1684
+ duration: timedelta,
1685
+ *,
1686
+ label: str | None = None,
1687
+ locale: str | None = None,
1652
1688
  ) -> Notification:
1653
- """Start a timer on ``device``.
1689
+ """Start a timer on ``device``; Alexa confirms it out loud.
1690
+
1691
+ Amazon has no API for this: the timers API of the app starts the timer
1692
+ on the app's own registration, not on an Echo. What works is a typed
1693
+ request with the duration in words (see :mod:`amazon_echo.phrases`),
1694
+ available for Portuguese and English.
1695
+
1696
+ Args:
1697
+ device: The Echo that will run the timer.
1698
+ duration: More than zero and less than 24 hours.
1699
+ label: Optional name of the timer.
1700
+ locale: Locale of the device; read from Amazon when omitted.
1701
+
1702
+ Raises:
1703
+ AmazonEchoNotSupportedError: No phrase for the device's language.
1704
+ AmazonEchoResponseError: Alexa did not start the timer.
1705
+ ValueError: The duration is out of range.
1654
1706
 
1655
- The request body follows the field names found in the Alexa app
1656
- (``/v1/alerts/timers``); it has not been replayed against Amazon.
1657
1707
  """
1658
- seconds = int(duration.total_seconds())
1659
- if seconds <= 0:
1660
- raise ValueError("The timer duration must be positive")
1708
+ if locale is None:
1709
+ preferences = await self.get_device_preferences()
1710
+ locale = (preferences.get(device.serial) or {}).get("locale") or "en-US"
1711
+ request = timer_request(duration, locale, label=label)
1661
1712
  known = {item.id for item in await self.get_notifications()}
1662
- body: dict[str, Any] = {
1663
- "duration": f"PT{seconds}S",
1664
- "creationBehavior": {"displayExperience": {"visibility": "VISIBLE"}},
1665
- "triggeringBehavior": {
1666
- "operation": {"type": "NOTIFY_ONLY"},
1667
- "notificationConfig": {"playAudible": True},
1668
- },
1669
- "endpointId": f"{device.serial}@{device.device_type}",
1670
- }
1671
- if label:
1672
- body["timerLabel"] = label
1673
- await self._alerts("POST", "timers", body)
1674
- return await self._find_new(device, "timer", known)
1713
+ await self.text_command(device, request)
1714
+ for _ in range(_TIMER_POLLS):
1715
+ await asyncio.sleep(_TIMER_POLL_SECONDS)
1716
+ try:
1717
+ return await self._find_new(device, "timer", known)
1718
+ except AmazonEchoResponseError:
1719
+ continue
1720
+ raise AmazonEchoResponseError(200, "The new timer did not show up")
1675
1721
 
1676
1722
  @staticmethod
1677
1723
  def _alarm_index(alarm: Notification) -> str:
amazon_echo/const.py CHANGED
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Any, Final
6
6
 
7
- VERSION: Final = "0.2.0"
7
+ VERSION: Final = "0.3.1"
8
8
 
9
9
  # Identity of the Alexa iOS app, which is what a registration impersonates.
10
10
  APP_NAME: Final = "Amazon Echo for Home Assistant"
amazon_echo/phrases.py ADDED
@@ -0,0 +1,128 @@
1
+ """Spoken phrases for the things Alexa only accepts as a voice request.
2
+
3
+ Alexa has no API to start a timer on an Echo: the timers API of the app starts
4
+ it on the app's own registration. A typed request works, but only with the
5
+ numbers spelled out ("timer de dez minutos" starts one, "timer de 10 minutos"
6
+ makes Alexa ask for how long), so the duration is written in words here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import timedelta
12
+
13
+ from .exceptions import AmazonEchoNotSupportedError
14
+
15
+ _PT_UNITS = [
16
+ "zero",
17
+ "um",
18
+ "dois",
19
+ "três",
20
+ "quatro",
21
+ "cinco",
22
+ "seis",
23
+ "sete",
24
+ "oito",
25
+ "nove",
26
+ "dez",
27
+ "onze",
28
+ "doze",
29
+ "treze",
30
+ "quatorze",
31
+ "quinze",
32
+ "dezesseis",
33
+ "dezessete",
34
+ "dezoito",
35
+ "dezenove",
36
+ ]
37
+ _PT_TENS = {20: "vinte", 30: "trinta", 40: "quarenta", 50: "cinquenta"}
38
+ _EN_UNITS = [
39
+ "zero",
40
+ "one",
41
+ "two",
42
+ "three",
43
+ "four",
44
+ "five",
45
+ "six",
46
+ "seven",
47
+ "eight",
48
+ "nine",
49
+ "ten",
50
+ "eleven",
51
+ "twelve",
52
+ "thirteen",
53
+ "fourteen",
54
+ "fifteen",
55
+ "sixteen",
56
+ "seventeen",
57
+ "eighteen",
58
+ "nineteen",
59
+ ]
60
+ _EN_TENS = {20: "twenty", 30: "thirty", 40: "forty", 50: "fifty"}
61
+
62
+
63
+ def _pt(number: int, *, feminine: bool = False) -> str:
64
+ if number < 20:
65
+ word = _PT_UNITS[number]
66
+ return {"um": "uma", "dois": "duas"}.get(word, word) if feminine else word
67
+ tens, rest = number - number % 10, number % 10
68
+ return _PT_TENS[tens] + (f" e {_pt(rest, feminine=feminine)}" if rest else "")
69
+
70
+
71
+ def _en(number: int) -> str:
72
+ if number < 20:
73
+ return _EN_UNITS[number]
74
+ tens, rest = number - number % 10, number % 10
75
+ return _EN_TENS[tens] + (f"-{_EN_UNITS[rest]}" if rest else "")
76
+
77
+
78
+ def _parts(duration: timedelta) -> tuple[int, int, int]:
79
+ seconds = int(duration.total_seconds())
80
+ if not 0 < seconds < 24 * 3600:
81
+ raise ValueError("The timer duration must be between 1 second and 24 hours")
82
+ return seconds // 3600, seconds % 3600 // 60, seconds % 60
83
+
84
+
85
+ def timer_request(
86
+ duration: timedelta, language: str, *, label: str | None = None
87
+ ) -> str:
88
+ """Return the typed request that starts a timer of ``duration``.
89
+
90
+ Args:
91
+ duration: More than zero and less than 24 hours.
92
+ language: Locale of the device, e.g. ``pt-BR`` or ``en-US``.
93
+ label: Optional name of the timer.
94
+
95
+ Raises:
96
+ AmazonEchoNotSupportedError: No phrase for that language.
97
+ ValueError: The duration is out of range.
98
+
99
+ """
100
+ hours, minutes, seconds = _parts(duration)
101
+ code = language[:2].lower()
102
+ if code == "pt":
103
+ spoken = " e ".join(
104
+ f"{_pt(n, feminine=feminine)} {one if n == 1 else many}"
105
+ for n, one, many, feminine in (
106
+ (hours, "hora", "horas", True),
107
+ (minutes, "minuto", "minutos", False),
108
+ (seconds, "segundo", "segundos", False),
109
+ )
110
+ if n
111
+ )
112
+ return f"timer de {spoken}" + (f" chamado {label}" if label else "")
113
+ if code == "en":
114
+ spoken = " and ".join(
115
+ f"{_en(n)} {one if n == 1 else many}"
116
+ for n, one, many in (
117
+ (hours, "hour", "hours"),
118
+ (minutes, "minute", "minutes"),
119
+ (seconds, "second", "seconds"),
120
+ )
121
+ if n
122
+ )
123
+ return (
124
+ (f"set a {label} timer for {spoken}")
125
+ if label
126
+ else f"set a timer for {spoken}"
127
+ )
128
+ raise AmazonEchoNotSupportedError(f"No timer phrase for the language {language!r}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-amazon-echo
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: Async Python client for Amazon Echo / Alexa devices: state, settings, media, notifications, lists, HTTP/2 push and LAN discovery
5
5
  Project-URL: Homepage, https://github.com/hudsonbrendon/python-amazon-echo
6
6
  Project-URL: Repository, https://github.com/hudsonbrendon/python-amazon-echo
@@ -244,7 +244,9 @@ with mocked HTTP.
244
244
  | `set_volume` (sequence pipeline) | no-op write |
245
245
  | `create_reminder`, `delete_notification` | live (a reminder 320 days ahead was created and deleted) |
246
246
  | `create_alarm` | ported |
247
- | `create_timer` | ported — body inferred from field names in the app, never sent |
247
+ | `create_alarm(music=…)` (music alarm that reuses the station of an existing one) | ported from Alexa Media Player's request, never sent |
248
+ | `play_music(timer=…)` (stop after that many seconds) | ported from Alexa Media Player's payload, never sent |
249
+ | `create_timer` | verified live on an Echo Plus (pt-BR): a 12-minute timer, with and without a name, created and deleted. It is a typed request with the duration in words; English phrases are unit-tested only |
248
250
  | `set_wake_word` | ported |
249
251
  | `speak`, `announce`, `text_command`, `play_sound`, `play_music`, `launch_skill`, `run_routine`, `stop` | ported |
250
252
  | `media_command`, `bluetooth_connect`, `bluetooth_disconnect`, `reboot` | ported |
@@ -256,8 +258,8 @@ with mocked HTTP.
256
258
  | `get_smart_home_endpoints` | live read; power, brightness, colour, colour temperature, temperature, battery, contact, motion and lock states and the operation names all parsed |
257
259
  | `parse_endpoint_update` (smart-home push) | ported, not replayed live — no push stream on the test session |
258
260
  | Smart-home operations through `call_feature` (`turnOn`, `turnOff`, `setBrightness`, `setColor`, `setColorTemperature`, `setMode`, `lock`, `unlock`) | ported, not replayed live — they change a device's visible state. The request shapes of `power`, `brightness`, `lock` and `toggle` are the ones in the Alexa app; the payload of `setColorTemperature` is inferred |
259
- | `get_communication_preferences` | ported. Called live on five devices: the service answers HTTP 503 for this account whatever the device, while `/accounts` on the same host answers 200 with the same cookies |
260
- | `set_communications`, `set_announcements`, `set_drop_in` | ported, not replayed live — there was no value to write back (see the line above) |
261
+ | `get_communication_preferences` | verified live once (an Echo Plus answered `announcements: true, communications: true, drop_in: all`); otherwise the service answered HTTP 503 on roughly nine out of ten of some 60 requests on 2026-11-16, on both the `.com` and the marketplace host, with cookies or a bearer token |
262
+ | `set_communications`, `set_announcements`, `set_drop_in` | ported, not replayed live — the no-op write was attempted three times each and the service answered 503 every time |
261
263
  | `get_device_preferences`, `get_kids_mode`, `get_children`, `get_kids_profile` | live read |
262
264
  | `set_kids_mode` | ported, not replayed live — it changes how a device behaves |
263
265
  | `get_guard` | live for an account without Guard (the appliance list is read, no panel is found, None); the state read is ported — the test account has no Guard |
@@ -289,8 +291,14 @@ with mocked HTTP.
289
291
  pass a naive datetime in the Echo's local time if the host lives elsewhere.
290
292
  - **Alarms have no label** in Amazon's API; `create_alarm(label=…)` is accepted
291
293
  and ignored.
292
- - **`create_timer` is unverified** (see the table). Use
293
- `text_command(device, "set a timer for 5 minutes")` if it is rejected.
294
+ - **Music alarms** can only reuse a station: `create_alarm(music=…)` takes a
295
+ music alarm that already exists on the account (create one in the Alexa app
296
+ first) and wakes with the same station. Amazon has no public search for one.
297
+ - **`create_timer`** speaks: Alexa has no API to start a timer on an Echo (the
298
+ app's timers API starts it on the app's own registration, which was observed
299
+ live), so the request is typed with the duration in words and Alexa confirms
300
+ it out loud. Portuguese and English only; other languages raise
301
+ `AmazonEchoNotSupportedError`.
294
302
  - **Voice history** comes 10 records per call; at most 50 are fetched.
295
303
  - **Lists** return the first 100 items.
296
304
  - **`get_notifications`** is a large, rate-limited answer; call it sparingly (push
@@ -1,16 +1,17 @@
1
- amazon_echo/__init__.py,sha256=0oC9ErIQXFVmdUTl7RYXw1hvl6-gTp3yN2s0qY-8NqM,1437
1
+ amazon_echo/__init__.py,sha256=A2TR67ga1Q9cB1wzlf8PWPzoIHxSfiu5F4nsgJ9RAMU,1437
2
2
  amazon_echo/__main__.py,sha256=1Hhd7w2cW5Z9jmwO1OThhcj6gbTLVqAQu5fAMqijJ_0,4325
3
3
  amazon_echo/auth.py,sha256=O5SAtY5Wf76-LtFOkHJvrzlNoZdprgJsx5-3crEPUGQ,14417
4
- amazon_echo/client.py,sha256=k8xzNc6WDSadtZ444HgdCFK71CACFZOYLLN8ODgWvLk,79419
5
- amazon_echo/const.py,sha256=o8qqiY7JCD1BDELpIn-L17FT2THn_ni_5YejGtWZVM4,11880
4
+ amazon_echo/client.py,sha256=CwzLzZn8zNO2pHp7FpYpUCrXw73e37vCcM6Sq9uRBE4,81267
5
+ amazon_echo/const.py,sha256=VdwrTHytFm4Yh-qlcClfTFL-KnnfyClWGA-7W_sU2X4,11880
6
6
  amazon_echo/endpoints.py,sha256=_6vXYWtwGIR_2IjVFJAXWP1vR6jwzIpZ4upkRctwBp8,7925
7
7
  amazon_echo/exceptions.py,sha256=7ETH4C2sKbKEJWnJ30ygAO0a_GiD5PWmDHJCSVTedAU,1120
8
8
  amazon_echo/local.py,sha256=KHwwgC2-MzFZ0wBaxXRuotyr7-zrrenzfM0P3BEMRvE,3080
9
9
  amazon_echo/models.py,sha256=ZKEHuiyG7hqRt5M8nufyf1nyaRZ2-l1WXlOCzG4UH7A,5258
10
+ amazon_echo/phrases.py,sha256=iqhqIK07XRTWmAwJ5jhzGPtqatvUz4nywCvJvCgwTK0,3579
10
11
  amazon_echo/push.py,sha256=KMcHeDLgRxEjCQpTybiJUAUNTFTxlDMpTVPDv0ZYAzE,11206
11
12
  amazon_echo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- python_amazon_echo-0.2.0.dist-info/METADATA,sha256=Jn6gvMcgmFIkkgObcl4-09A9n07PU0NTChVHwJ7_nGY,16967
13
- python_amazon_echo-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
- python_amazon_echo-0.2.0.dist-info/entry_points.txt,sha256=rbZJ8BI8kkiDTV9cKk6acbHuyAm2xNYfpDBXQNw8Yb8,58
15
- python_amazon_echo-0.2.0.dist-info/licenses/LICENSE,sha256=4Zgd3fbLJqWSkwKA-hh1rNN6DC9tNQ3rWLX93fingOw,1071
16
- python_amazon_echo-0.2.0.dist-info/RECORD,,
13
+ python_amazon_echo-0.3.1.dist-info/METADATA,sha256=m2ILh-YpRt36B1OV0Gx-a7RDkzdOtFLBLXbZMXZgheE,17932
14
+ python_amazon_echo-0.3.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ python_amazon_echo-0.3.1.dist-info/entry_points.txt,sha256=rbZJ8BI8kkiDTV9cKk6acbHuyAm2xNYfpDBXQNw8Yb8,58
16
+ python_amazon_echo-0.3.1.dist-info/licenses/LICENSE,sha256=4Zgd3fbLJqWSkwKA-hh1rNN6DC9tNQ3rWLX93fingOw,1071
17
+ python_amazon_echo-0.3.1.dist-info/RECORD,,