• Stars
    star
    176
  • Rank 215,994 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created over 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A python library to authenticate with Xbox Live via your Microsoft Account and provides Xbox related Web-API.

Xbox-WebAPI

PyPi - latest Documentation status Build status Discord chat channel

Xbox-WebAPI is a python library to authenticate with Xbox Live via your Microsoft Account and provides Xbox related Web-API.

Authentication is supported via OAuth2.

  • Register a new application in Azure AD
    • Name your app
    • Select "Personal Microsoft accounts only" under supported account types
    • Add http://localhost/auth/callback as a Redirect URI of type "Web"
  • Copy your Application (client) ID for later use
  • On the App Page, navigate to "Certificates & secrets"
    • Generate a new client secret and save for later use

Dependencies

  • Python >= 3.7

How to use

Install

pip install xbox-webapi

Authentication

Note: You must use non child account (> 18 years old)

Token save location: If tokenfile is not provided via cmdline, fallback of <appdirs.user_data_dir>/tokens.json is used as save-location

Specifically:

Windows: C:\\Users\\<username>\\AppData\\Local\\OpenXbox\\xbox

Mac OSX: /Users/<username>/Library/Application Support/xbox/tokens.json

Linux: /home/<username>/.local/share/xbox

For more information, see: https://pypi.org/project/appdirs and module: xbox.webapi.scripts.constants

xbox-authenticate --client-id <client-id> --client-secret <client-secret>

Example: Search Xbox Live via cmdline tool

  # Search Xbox One Catalog
  xbox-searchlive "Some game title"

API usage

import asyncio
import sys

from httpx import HTTPStatusError

from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.authentication.manager import AuthenticationManager
from xbox.webapi.authentication.models import OAuth2TokenResponse
from xbox.webapi.common.signed_session import SignedSession
from xbox.webapi.scripts import CLIENT_ID, CLIENT_SECRET, TOKENS_FILE

"""
This uses the global default client identification by OpenXbox
You can supply your own parameters here if you are permitted to create
new Microsoft OAuth Apps and know what you are doing
"""
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
tokens_file = TOKENS_FILE

"""
For doing authentication, see xbox/webapi/scripts/authenticate.py
"""


async def async_main():
    # Create a HTTP client session
    async with SignedSession() as session:
        """
        Initialize with global OAUTH parameters from above
        """
        auth_mgr = AuthenticationManager(session, client_id, client_secret, "")

        """
        Read in tokens that you received from the `xbox-authenticate`-script previously
        See `xbox/webapi/scripts/authenticate.py`
        """
        try:
            with open(tokens_file) as f:
                tokens = f.read()
            # Assign gathered tokens
            auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        except FileNotFoundError as e:
            print(
                f"File {tokens_file} isn`t found or it doesn`t contain tokens! err={e}"
            )
            sys.exit(-1)

        """
        Refresh tokens, just in case
        You could also manually check the token lifetimes and just refresh them
        if they are close to expiry
        """
        try:
            await auth_mgr.refresh_tokens()
        except HTTPStatusError as e:
            print(
                f"""
                Could not refresh tokens from {tokens_file}, err={e}\n
                You might have to delete the tokens file and re-authenticate 
                if refresh token is expired
            """
            )
            sys.exit(-1)

        # Save the refreshed/updated tokens
        with open(tokens_file, mode="w") as f:
            f.write(auth_mgr.oauth.json())
        print(f"Refreshed tokens in {tokens_file}!")

        """
        Construct the Xbox API client from AuthenticationManager instance
        """
        xbl_client = XboxLiveClient(auth_mgr)

        """
        Some example API calls
        """
        # Get friendslist
        friendslist = await xbl_client.people.get_friends_own()
        print(f"Your friends: {friendslist}\n")

        # Get presence status (by list of XUID)
        presence = await xbl_client.presence.get_presence_batch(
            ["2533274794093122", "2533274807551369"]
        )
        print(f"Statuses of some random players by XUID: {presence}\n")

        # Get messages
        messages = await xbl_client.message.get_inbox()
        print(f"Your messages: {messages}\n")

        # Get profile by GT
        profile = await xbl_client.profile.get_profile_by_gamertag("SomeGamertag")
        print(f"Profile under SomeGamertag gamer tag: {profile}\n")


asyncio.run(async_main())

Contribute

  • Report bugs/suggest features
  • Add/update docs
  • Add additional xbox live endpoints

Credits

This package uses parts of Cookiecutter and the audreyr/cookiecutter-pypackage project template. The authentication code is based on joealcorn/xbox

Informations on endpoints gathered from:

Disclaimer

Xbox, Xbox One, Smartglass and Xbox Live are trademarks of Microsoft Corporation. Team OpenXbox is in no way endorsed by or affiliated with Microsoft Corporation, or any associated subsidiaries, logos or trademarks.

More Repositories

1

xbox-smartglass-nano-python

The gamestreaming part of the smartglass library
Python
104
star
2

xbox-smartglass-core-python

SmartGlass Core protocol python library
Python
72
star
3

xbox-smartglass-csharp

๐ŸŽฎ.NET Standard client library for the Xbox One SmartGlass protocol
C#
64
star
4

xbox-webapi-csharp

C# Xbox WebAPI, includes support for authentication with Windows Live / Xbox Live
C#
55
star
5

xbox-client-xamarin

Xbox one gamestreaming app for Android & iOS
C#
36
star
6

xbox-smartglass-rest-python

[DEPRECATED] Xbox One SmartGlass RESTful server
36
star
7

xbox-smartglass-core-node

NodeJS port of xbox-smartglass-core-python
JavaScript
35
star
8

smartglass-documentation

Documentation of the Xbox One SmartGlass protocol
Makefile
34
star
9

xcloud-python

Python
21
star
10

xcloud-rs

XCloud experiments in RUST
Rust
19
star
11

xbox-client-ffmpeg

Multi-platform Gamestreaming app
C#
19
star
12

xbox-client-android

Android Gamestreaming App
C#
14
star
13

openxbox.github.io

Team OpenXbox
13
star
14

xal-rs

Xbox Authentication library
Rust
10
star
15

xbox-client-gtk

A GTK+3 multi-platform Xbox application
C#
10
star
16

smartglass-tools

Misc SmartGlass helper tools
Lua
9
star
17

xbox-client-macios

MacOS / iOS Gamestreaming app
9
star
18

ms_cv

A correlation vector implementation in python, based on Microsoft's implementation
Python
5
star
19

xcloud-tools

JavaScript
5
star
20

xbox-smartglass-auxiliary-python

[DEPRECATED] This library provides the title channel / auxiliary stream extension of the SmartGlass protocol.
4
star
21

xbox-smartglass-stump-python

[DEPRECATED] Library to handle SmartGlass Stump (TV Streaming / IR control) messages.
3
star
22

filetime_type-rs

Platform agnostic FILETIME conversion
Rust
2
star
23

xbox-smartglass-core-rust

Rust
1
star
24

xbox-client-vala

Xbox GUI Client, written in Vala
Vala
1
star