API Reference

This sections outlines the shinkei API.

Client

shinkei.connect(url, application_id, client_id, auth=None, *, tags=None, reconnect=True, session=None, loop=None, klass=None, handlers=None, proxy_ip=None, **kwargs)

Connect to singyeong.

Since this returns a context manager mixin of Client, both

async with shinkei.connect(*args, **kwargs):
    # ....

and

client = await shinkei.connect(*args, **kwargs):

try:
    # ...
finally:
    await client.close()

are valid and do the same thing.

Parameters
  • url (str) – The base url for the WebSocket url.

  • application_id (str) – A unique id which should be shared among all related clients.

  • client_id (str) – An id unique across all clients connected to the same application.

  • auth (Optional[str]) – A password used to access the server. If an incorrect password is sent the client will be put in restricted mode. Defaults to None.

  • tags (Optional[list]) – A list of tags to identify the client and to allow the discovery of it’s application id. If the client is restricted the tags will be ignored.

  • reconnect (Optional[bool]) – Whether or not to reconnect when singyeong sends a GOODBYE payload or when the WebSocket disconnects for other reasons. Defaults to True

  • handlers (Optional[List[Handler]]) – The initial handlers to register.

  • session (Optional[aiohttp.ClientSession]) – The session used for HTTP requests. If none is provided, a new one will be created.

  • loop (Optional[asyncio.AbstractEventLoop]) – The loop used to connect to the websocket and make HTTP requests. If non is provided, asyncio.get_event_loop() will be used to get one.

  • klass (Optional[Type[Client]]) – The classed used to instantiate the client. Defaults to Client.

  • proxy_ip (Optional[str]) – The IP that the server will use to proxy HTTP requests.

  • kwargs – All other kwargs will be passed onto the Client class’ _connect method. Useful when passing a custom class.

Returns

The client.

Return type

A context manager mixin of Client

class shinkei.Client

The main client connecting to singyeong.

This is not supposed to be instantiated manually but through connect()

loop

The loop used to connect to the websocket make HTTP requests.

Type

asyncio.AbstractEventLoop

session

The aiohttp session used for HTTP requests.

Type

aiohttp.ClientSession

restricted

Whether or not the client is restricted. A client is restricted usually when it fails to provide the right password.

Type

bool

version

A Version object representing the singyeong and api version.

Type

Version

is_closed

Whether or not the client is closed.

Type

bool

latency

The latency, is seconds, between heartbeats.

Type

float

await send(data, *, target, nonce=None)

Send data to a client which matches the predicates of the target query.

Restricted clients cannot use this method.

Parameters
  • data (Union[str, int, float, list, dict]) – The data to send. Must be JSON serializable.

  • target (QueryBuilder) – The query that is used to match the client.

  • nonce – A value used to identify the data sent.

Raises

ShinkeiWSException – The client is restricted.

await broadcast(data, *, target, nonce=None)

Send data to all clients which matches the predicates of the target query.

Restricted clients cannot use this method.

Parameters
  • data (Union[str, int, float, list, dict]) – The data to send. Must be JSON serializable.

  • target (QueryBuilder) – The query that is used to match the clients.

  • nonce – A value used to identify the data sent.

Raises

ShinkeiWSException – The client is restricted.

await update_metadata(data, *, cache=True)

Update metadata on singyeong.

The data is not consistent between server restarts but if cache is set to True then it will persist between reconnects.

Parameters
  • data (Dict[str, Union[str, int, float, list, VersionMetadata]]) – The metadata to update. Keys cannot be one of ip, restricted, encoding or last_heartbeat_time.

  • cache (Optional[bool]) – Whether or not to cache the metadata and send it back on reconnects. Defaults to True.

Raises

ShinkeiWSException – The metadata structure was invalid or a restricted key was used.

await proxy_request(method, route, *, target, body=None, headers=None)

Make a proxy HTTP request to a client.

Parameters
  • method (str) – The HTTP method to use. Supports only POST, PATCH, PUT, DELETE, MOVE, GET and HEAD.

  • route (str) – The route to make the request to.

  • body (Optional[Union[str, dict, list]]) – The request body, silently ignored in GET and HEAD. If none is provided but the method requires one an empty string will be sent.

  • headers (Optional[Dict[str, str]]) – The request headers.

  • target (QueryBuilder) – The query that is used to match the client.

Returns

The HTTP response.

Return type

Union[str, dict, list]

Raises
await discover(tags)

Discover an application id by it’s clients tags.

Parameters

tags (list) – The list of tags an application client must have to match

Returns

A list of application ids matching.

Return type

list

Raises

TypeError – The tags argument wasn’t a list.

add_handler(handler)

A function used to manually add handler to the client.

Parameters

handler (Handler) – The handler to add.

Returns

The handler added.

Return type

Handler

Raises
  • TypeErrorhandler was not an instance of Handler

  • ValueError – The handler was already registered. This is determined by the name of the handler.

remove_handler(handler_name)

Remove a handler by name.

Parameters

handler_name (str) – The name of the handler.

Returns

The handler, or None if it wasn’t removed.

Return type

Optional[Handler]

await wait_for(event, *, timeout=None, check=None)

Wait for an event.

Parameters
  • event (str) – The name of the event.

  • timeout (Optional[Union[int, float]]) – The amount of time to wait before timing out. By default it never times out.

  • check (Optional[Callable[…, bool]]) – A callable which returns a falsy or truthy value to filter the event to wait for.

Returns

The return value of the event.

Return type

Any

stream(event, *, timeout=None, check=None, limit=None)

Return an async iterator which waits until an event is dispatched before continuing the iterations.

Parameters
Yields

Any – The return value of the event.

await close()

Close the connection to singyeong.

Run this when cleaning up.

Event Reference

All the following events can be catched through event handlers or specific methods like Client.wait_for() or Client.stream().

shinkei.data

This event is fired whenever this client receives data from other clients trough Client.send() and Client.broadcast().

The only argument returned is the data represented as MetadataPayload.

shinkei.ready

This event is fire whenever the WebSocket has connected and successfully identified.

No arguments are returned.

shinkei.error

This event is fired whenever the WebSocket returns an error message.

The only argument returned is the error message as a str.

shinkei.connect

This event is fired whenever the WebSocket has successfully connected.

No arguments are returned.

shinkei.disconnect

This event is fired whenever the WebSocket has disconnected.

No arguments are returned.

Event Handlers

Events described in the event reference are handled through the proper handlers.

Event handlers are classes which subclass Handler and have functions which listen to events decorated with the listens_to().

See the following piece of code for an example:

class CustomHandler(shinkei.Handler, name="custom"):
    @shinkei.listens_to("data")
    async def data_receiver(self, data):
        print("{0.qualified_name} received {1.payload}!".format(self, data))


# somewhere else...

client = await shinkei.connect(..., handlers=[CustomHandler()])

Through this handler, every time the client receives data it will print custom received <data-here>!

class shinkei.HandlerMeta(*args, **kwargs)

A metaclass used to implement the main functionality of the handlers.

Not really to be used directly but rather to implement more complex custom handler classes.

Note

The listed args are meant to be passed in the type constructor as kwargs, like this:

class MyHandler(shinkei.Handler, name="My Handler"):
    pass
Parameters

name (Optional[str]) – The name of the handler, used to determine if it has already been registered or not. Defaults to the class’s name.

class shinkei.Handler

The base class for event handlers.

This class is made only for subclassing.

qualified_name

The name passed in the type constructor or the class’ name if none was provided.

Type

str

@shinkei.listens_to

Decorator to register a method of a Handler as a listener.

The method must be a coroutine.

Parameters

name (str) – The name of the event to listen to.

Raises

TypeError – The name was not a string or the method was not a coroutine.

Query Builder

class shinkei.QueryBuilder(application, key, **kwargs)

A utility to build queries which routes clients based on their metadata.

Used mostly in Client.send() and Client.broadcast().

Example using key-value queries:

# this will target every client part of "my-cool-app" where "special_value" is greater then 5
shinkei.QueryBuilder(application="my-cool-app", key="uniquekey").gt("special_value", 5)

Example using Node based query:

# this will target every client part of "my-cool-app" where "special_value" is greater then 5 or is equal to 10
shinkei.QueryBuilder(application="my-cool-app", key="uniquekey").either(
    "special_value", shinkei.Node().eq(10).gt(5)
)
Parameters
  • application (str) – The id of the target application.

  • key (str) – The key used for consistent-hashing when choosing a client from the output.

  • restricted (Optional[bool]) – Whether or not if restricted clients should be included. Defaults to False.

  • optional (Optional[bool]) – Whether or not to return a result even if the query fails. Defaults to False.

eq(key, value)

Match if the value of key equals to value.

ne(key, value)

Match if the value of key is not equal to value.

gt(key, value)

Match if the value of key is greater then value.

gte(key, value)

Match if the value of key is equal to or greater then value.

lt(key, value)

Match if the value of key is lower then value.

lte(key, value)

Match if the value of key is equal to or lower then value.

inside(key, value)

Match if the value of key is inside value.

value must be a list.

ninside(key, value)

Match if the value of key is not inside value.

value must be a list.

contains(key, value)

Match if value is inside the value of key.

The value of key must be a list.

ncontains(key, value)

Match if value is not inside the value of key.

The value of key must be a list.

also(key, node)

Match if all the predicates in node succeed.

node must be an instance of Node.

either(key, node)

Match if any of the predicates in node succeed.

node must be an instance of Node.

neither(key, node)

Match if no predicates in node succeed.

node must be an instance of Node.

class shinkei.Node

Similar to QueryBuilder.

Used only for predicates inside also(), either() and neither().

eq(value)

Equal to QueryBuilder.eq(), but only takes a value.

ne(value)

Equal to QueryBuilder.ne(), but only takes a value.

gt(value)

Equal to QueryBuilder.gt(), but only takes a value.

gte(value)

Equal to QueryBuilder.gte(), but only takes a value.

lt(value)

Equal to QueryBuilder.lt(), but only takes a value.

lte(value)

Equal to QueryBuilder.lte(), but only takes a value.

inside(value)

Equal to QueryBuilder.inside(), but only takes a value.

ninside(value)

Equal to QueryBuilder.ninside(), but only takes a value.

contains(value)

Equal to QueryBuilder.contains(), but only takes a value.

ncontains(value)

Equal to QueryBuilder.ncontains(), but only takes a value.

Data Classes

class shinkei.Version

An object representing the API and singyeong version.

api

The API version, in vN format.

Type

str

singyeong

The singyeong version, in x.y.z format.

Type

str

class shinkei.MetadataPayload

An object representing a payload of data received from a client.

nonce

A unique nonce used to identify the payload.

payload

The payload.

Type

Union[str, int, float, list, dict]

class shinkei.VersionMetadata(fmt)

An object to represent a version object in Client.update_metadata().

This is NOT the same as Version.

Parameters

fmt (str) – The version string. Must be complient to the elixir specification.

Exceptions

class shinkei.ShinkeiException

Base exception for this library.

All following exceptions inherit from this.

class shinkei.ShinkeiHTTPException

Generic HTTP exception.

request

The failed request.

Type

aiohttp.ClientResponse

code

The request status code.

Type

int

message

A error message.

Type

str

class shinkei.ShinkeiWSException

Generic WebSocket exception.

message

A error message.

Type

str

class shinkei.ShinkeiResumeWS

An internal exception raised when the WebSocket has been disconnected but can resume.

message

A error message.

Type

str

class shinkei.ShinkeiWSClosed

An internal exception raised when the WebSocket has been disconnected and can’t resume.

code

The WebSocket status code.

Type

int

message

A error message.

Type

str