import requests


def access_token(
    homeserver: str, user: str, password: str, deviceid: str, devicename: str
) -> str:
    """Retrieve a bearer token from a Matrix homeserver"""
    data = {
        "identifier": {
            "type": "m.id.user",
            "user": user,
        },
        "password": password,
        "type": "m.login.password",
        "device_id": deviceid,
        "initial_device_display_name": devicename,
    }
    uri = f"{homeserver}/_matrix/client/r0/login"

    result = requests.post(uri, json=data)
    # A successful request will return something like this:
    # '{"user_id":"@me:micahrl.com","access_token":"...ELIDED...","home_server":"micahrl.com","device_id":"ifrit_get_mx_users","well_known":{"m.homeserver":{"base_url":"https://matrix.micahrl.com/"}}}'
    # In case the request was not successful, raise an error
    result.raise_for_status()
    jresult = result.json()
    return jresult["access_token"]