Skip to main content

A basic wrapper for the Discord Linked Roles OAuth2 API.

Project description

Discord Linked Roles OAuth2

A basic wrapper for the Discord Linked Roles OAuth2 API.

Releases

Installation:

pip install linked-roles

FastAPI Examples:

import logging

from fastapi import FastAPI, status
from fastapi.responses import RedirectResponse

import config
from linked_roles import LinkedRolesOAuth2, OAuth2Scopes, RolePlatform, Unauthorized, NotFound

_log = logging.getLogger(__name__)

app = FastAPI(title='Linked Roles OAuth2')

client = LinkedRolesOAuth2(
    client_id=config.DISCORD_CLIENT_ID,
    client_secret=config.DISCORD_CLIENT_SECRET,
    redirect_uri=config.DISCORD_REDIRECT_URI,
    # token=config.DISCORD_TOKEN, # Optinal for Resgister
    scopes=(OAuth2Scopes.role_connection_write, OAuth2Scopes.identify),
    state=config.COOKIE_SECRET,
)


@app.on_event('startup')
async def startup():
    await client.start()
    _log.info('Startup complete')


@app.on_event('shutdown')
async def shutdown():
    await client.close()
    _log.info('Shutdown complete')


@app.get('/linked-role', status_code=status.HTTP_302_FOUND)
async def linked_roles():
    url = client.get_oauth_url()
    return RedirectResponse(url=url)


@app.get('/verified-role')
async def verified_role(code: str):

    tokens = await client.get_oauth2_tokens(code)
    user = await client.fetch_user(tokens=tokens)

    platform = RolePlatform(name='VALORANT', username='STACIA#1234')
    platform.set_metadata(key='matches', value=100)
    platform.set_metadata(key='winrate', value=50)
    platform.set_metadata(key='combat_score', value=10)
    platform.set_metadata(key='last_update', value=datetime.datetime.now())
    platform.set_metadata(key='verified', value=True)

    await user.edit_role_metadata(platform=platform)

    return 'Verified role successfully'


@app.post('/update-role-metadata')
async def update_role_metadata(user_id: str):
    
    user = client.get_user(id=user_id)

    if user is None:
        raise UserNotFound(f'User with ID {user_id} not found')

    tokens = user.get_tokens()
    if tokens is None:
        raise OAuth2Unauthorized('User is not connected to Linked Roles')

    if tokens.is_expired():
        await tokens.refresh()

    platform = user.get_role_platform()
    platform.username = 'STACIA#4321'
    platform.edit_metadata(key='matches', value=5000)
    platform.edit_metadata(key='winrate', value=5000)
    platform.edit_metadata(key='combat_score', value=100000)
    platform.edit_metadata(key='last_update', value=datetime.datetime.now())
    platform.edit_metadata(key='verified', value=True)

    await user.edit_role_metadata(platform=platform)

Register Examples:

import asyncio

import config
from linked_roles import AppRoleConnectionMetadataRecordType as RoleMetadataType, LinkedRolesOAuth2, RoleMetadataRecord


async def main():

    client = LinkedRolesOAuth2(client_id=config.DISCORD_CLIENT_ID, token=config.DISCORD_TOKEN)

    async with client:

        records = (
            RoleMetadataRecord(
                key='matches',
                name='Matches',
                description='Number of matches this season',
                type=2,
            ),
            RoleMetadataRecord(
                key='winrate',
                name='Win Rate',
                description='Win rate this season',
                type=RoleMetadataType.interger_greater_than_or_equal,
            ),
            RoleMetadataRecord(
                key='combat_score',
                name='Combat Score',
                description='Combat score this season',
                type=RoleMetadataType.interger_greater_than_or_equal,
            ),
            RoleMetadataRecord(
                key='last_update',
                name='Last Update',
                description='Last time this data was updated',
                type=RoleMetadataType.datetime_less_than_or_equal,
            ),
            RoleMetadataRecord(
                key='verified',
                name='Verified',
                description='Verified role',
                type=RoleMetadataType.boolean_equal,
            )
        )

        records = await client.register_role_metadata(records=records)
        print(records)


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

TODO:

  • Add more examples
  • Add documentation
  • Add database support (postgresql, sqlite, etc.) ?

Code Style Inspiration

License

licensed under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

linked-roles-1.0.0.tar.gz (13.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

linked_roles-1.0.0-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

Details for the file linked-roles-1.0.0.tar.gz.

File metadata

  • Download URL: linked-roles-1.0.0.tar.gz
  • Upload date:
  • Size: 13.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.1

File hashes

Hashes for linked-roles-1.0.0.tar.gz
Algorithm Hash digest
SHA256 24669d0f525fe416efad0901df5b1fa02911f7697c9dfb20e20d8485c17018ee
MD5 5872a058eab416bbcd4fd11d77c6fd32
BLAKE2b-256 129f8f5d12c09c7f35afa79aa762056b44de882d2f0d2dad91a83b86acd85a85

See more details on using hashes here.

File details

Details for the file linked_roles-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: linked_roles-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 14.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.1

File hashes

Hashes for linked_roles-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 827dc1b04055fb25ad41a057eed3bc303ba2856741b1761324a481a77c77a2b7
MD5 91779b549ec0d0ea3db704990de575cb
BLAKE2b-256 5e76104cb148a4b4bb407ad908eb27cc413fdb90753f6818010d795014b521f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page