AlexaPy

1.29.20 · active · verified Mon Apr 13

AlexaPy is a Python library designed to programmatically control Amazon Echo devices. It acts as an unofficial API, primarily developed for the alexa_media_player custom component for Home Assistant. As of version 1.29.20, it provides functionalities for device interaction, login management, and sending commands to Alexa. Due to its reliance on an unofficial API, the library's functionality may change or cease without warning. The project maintains an active development status, with updates released as needed to adapt to changes in Amazon's unofficial Alexa interface.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to log in to an Alexa account, retrieve a list of associated devices, and send a Text-to-Speech (TTS) command to the first detected device. It uses environment variables for sensitive credentials. Replace 'your_email@example.com' and 'your_password' with actual values or set the `ALEXAPY_EMAIL` and `ALEXAPY_PASSWORD` environment variables.

import asyncio
import os
from alexapy import AlexaLogin, AlexaAPI

async def main():
    email = os.environ.get('ALEXAPY_EMAIL', 'your_email@example.com')
    password = os.environ.get('ALEXAPY_PASSWORD', 'your_password')
    url = 'https://alexa.amazon.com'

    # Initialize AlexaLogin
    login = AlexaLogin(email=email, password=password, url=url)

    # Attempt login
    await login.login()

    if await login.test_connection():
        print(f"Successfully logged in to Alexa account: {email}")

        # Initialize AlexaAPI with the logged-in session
        alexa_api = AlexaAPI(login=login, email=email)
        await alexa_api.get_devices()

        if alexa_api.devices:
            print("Found Alexa devices:")
            for device in alexa_api.devices.values():
                print(f"  - {device['accountName']} (Type: {device['deviceType']})")
            
            # Example: Send a TTS message to the first found device
            first_device_id = list(alexa_api.devices.keys())[0]
            await alexa_api.send_tts(first_device_id, "Hello from AlexaPy!")
            print(f"Sent TTS to {alexa_api.devices[first_device_id]['accountName']}")

        else:
            print("No Alexa devices found.")
    else:
        print("Failed to log in to Alexa. Check credentials or 2FA.")

    # Logout
    await login.logout()
    print("Logged out.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →