API Reference

Clients

Client

class Client(token, *, received=None, intents=None, throttler=<class 'pincer.objects.app.throttling.DefaultThrottleHandler'>, reconnect=True)

Bases: pincer.core.gateway.Dispatcher

The client is the main instance which is between the programmer and the discord API.

This client represents your bot.

bot

The user object of the client

Type

User

received_message

The default message which will be sent when no response is given.

Type

str

http

The http client used to communicate with the discord API

Type

HTTPClient

Parameters
  • token (str) – The token to login with your bot from the developer portal

  • received (Optional[str]) – The default message which will be sent when no response is given.

    Default: None

  • intents (Optional[Intents]) – The discord intents to use

    Default: None

  • throttler (Optional[ThrottleInterface]) – The cooldown handler for your client, defaults to DefaultThrottleHandler (which uses the WindowSliding technique). Custom throttlers must derive from ThrottleInterface.

staticmethod @event

A decorator to register a Discord gateway event listener. This event will get called when the client receives a new event update from Discord which matches the event name.

The event name gets pulled from your method name, and this must start with on_. This forces you to write clean and consistent code.

This decorator can be used in and out of a class, and all event methods must be coroutines. (async)

Example usage

>>> # Function based
>>> from pincer import Client
>>>
>>> client = Client("token")
>>>
>>> @client.event
>>> async def on_ready():
...     print(f"Signed in as {client.bot}")
>>>
>>> if __name__ == "__main__":
...     client.run()
>>> # Class based
>>> from pincer import Client
>>>
>>> class MyClient(Client):
...     @Client.event
...     async def on_ready(self):
...         print(f"Signed in as {self.bot}")
>>>
>>> if __name__ == "__main__":
...     MyClient("token").run()
Raises
property chat_commands

List of chat commands

Get a list of chat command calls which have been registered in the ChatCommandHandler.

Type

List[str]

await event_handler(_, payload)

This function is a coroutine.

Handles all payload events with opcode 0.

Parameters
  • _ – Socket param, but this isn’t required for this handler. So its just a filler parameter, doesn’t matter what is passed.

  • payload (GatewayDispatch) – The payload sent from the Discord gateway, this contains the required data for the client to know what event it is and what specifically happened.

await execute_error(error, name='on_error', *args, **kwargs)

This function is a coroutine.

Raises an error if no appropriate error event has been found.

Parameters
  • error (Exception) – The error that should be passed to the event

  • name (str) – the name of the event

    Default: on_error

Raises

error – if call := self.get_event_coro(name) is False

staticmethod execute_event(calls, *args, **kwargs)

Invokes an event.

Parameters
  • calls (Coro) – The call (method) to which the event is registered.

  • *args – The arguments for the event.

  • **kwargs – The named arguments for the event.

await get_channel(_id)

This function is a coroutine. Fetch a Channel from its identifier. The get_dm_channel method from User should be used if you need to create a dm_channel; using the send() method from User is preferred.

Parameters

_id (int) – The id of the user which should be fetched from the Discord gateway.

Returns

A Channel object.

Return type

Channel

staticmethod get_cogs()

Get a dictionary of all loaded cogs.

The key/value pair is import path/cog class.

Returns

The dictionary of cogs

Return type

Dict[str, Any]

staticmethod get_event_coro(name)

get the coroutine for an event

Parameters

name (str) – name of the event

await get_guild(guild_id)

This function is a coroutine.

Fetch a guild object by the guild identifier.

Parameters

guild_id (int) – The id of the guild which should be fetched from the Discord gateway.

Returns

The guild object.

Return type

Guild

await get_role(guild_id, role_id)

This function is a coroutine.

Fetch a role object by the role identifier.

guild_id: int

The guild in which the role resides.

role_id: int

The id of the guild which should be fetched from the Discord gateway.

Returns

A Role object.

Return type

Role

await get_user(_id)

This function is a coroutine.

Fetch a User from its identifier

Parameters

_id (int) – The id of the user which should be fetched from the Discord gateway.

Returns

The user object.

Return type

User

await handle_middleware(payload, key, *args, **kwargs)

This function is a coroutine.

Handles all middleware recursively. Stops when it has found an event name which starts with on_.

Returns a tuple where the first element is the final executor (so the event) its index in _events.

The second and third element are the *args and **kwargs for the event.

Parameters
  • payload (GatewayDispatch) – The original payload for the event

  • key (str) – The index of the middleware in _events

Raises
load_cog(path, package=None)

Load a cog from a string path, setup method in COG may optionally have a first argument which will contain the client!

Example usage

run.py

>>> from pincer import Client
>>>
>>> class MyClient(Client):
...     def __init__(self, *args, **kwargs):
...         self.load_cog("cogs.say")
...         super().__init__(*args, **kwargs)

cogs/say.py

>>> from pincer import command
>>>
>>> class SayCommand:
...     @command()
...     async def say(self, message: str) -> str:
...         return message
>>>
>>> setup = SayCommand
Parameters
  • path (str) – The import path for the cog.

  • package (str) – The package name for relative based imports.

    Default: None

loop_for(event_name, check=None, iteration_timeout=None, loop_timeout=None)
Parameters
  • event_name (str) – The type of event. It should start with on_. This is the same name that is used for @Client.event.

  • check (Callable[[Any], bool], default=None) – This function only returns a value if this return true.

  • iteration_timeout (Union[float, None]) – Amount of seconds before timeout. Timeouts are for each loop.

  • loop_timeout (Union[float, None]) – Amount of seconds before the entire loop times out. The generator will only raise a timeout error while it is waiting for an event.

Yields

Any – What the Discord API returns for this event.

await payload_event_handler(_, payload)

This function is a coroutine.

Special event which activates on_payload event!

Parameters
  • _ – Socket param, but this isn’t required for this handler. So its just a filler parameter, doesn’t matter what is passed.

  • payload (GatewayDispatch) – The payload sent from the Discord gateway, this contains the required data for the client to know what event it is and what specifically happened.

await process_event(name, payload)

This function is a coroutine.

Processes and invokes an event and its middleware

Parameters
  • name (str) – The name of the event, this is also the filename in the middleware directory.

  • payload (GatewayDispatch) – The payload sent from the Discord gateway, this contains the required data for the client to know what event it is and what specifically happened.

run()

Start the event listener.

await unload_cog(path)

This function is a coroutine.

Unload an already loaded cog! This removes all of its commands!

Parameters

path (str) – The path to the cog

Raises

CogNotFound – When the cog is not in that path

await wait_for(event_name, check=None, timeout=None)
Parameters
  • event_name (str) – The type of event. It should start with on_. This is the same name that is used for @Client.event.

  • check (CheckFunction) – This function only returns a value if this return true.

  • timeout (Optional[float]) – Amount of seconds before timeout.

Returns

What the Discord API returns for this event.

Return type

Any

Commands

command

@command(func=None, *, name=None, description='Description not set', enable_default=True, guild=None, cooldown=0, cooldown_scale=60, cooldown_scope=ThrottleScope.USER)

A decorator to create a command to register and respond to with the discord API from a function.

str - String int - Integer bool - Boolean float - Number pincer.objects.User - User pincer.objects.Channel - Channel pincer.objects.Role - Role Mentionable is not implemented

class Bot(Client):
    @command(
        name="test",
        description="placeholder"
    )
    async def test_command(
        self,
        ctx,
        amount: int,
        name: Descripted[str, "ah yes"],
        letter: Choices["a", "b", "c"]
    ):
        return Message(
            f"You chose {amount}, {name}, {letter}",
            flags=InteractionFlags.EPHEMERAL
        )
References from above:

Client, Message, Choices, Descripted, InteractionFlags

Parameters
  • name (Optional[str]) – The name of the command

    Default: None

  • description (Optional[str]) – The description of the command

    Default: Description not set

  • enable_default (Optional[bool]) – Whether the command is enabled by default

    Default: True

  • guild (Optional[Union[Snowflake, int, str]]) – What guild to add it to (don’t specify for global)

    Default: None

  • cooldown (Optional[int]) – The amount of times in the cooldown_scale the command can be invoked

    Default: 0

  • cooldown_scale (Optional[float]) – The ‘checking time’ of the cooldown

    Default: 60

  • cooldown_scope (ThrottleScope) – What type of cooldown strategy to use

    Default: ThrottleScope.USER

Raises

ChatCommandHandler

class ChatCommandHandler

Bases: object

Metaclass containing methods used to handle various commands

client

The client object

Type

Client

managers

Dictionary of managers

Type

Dict

register

Dictionary of ClientCommandStructure

Type

Dict

await add_command(cmd)

This function is a coroutine.

Add an app command

Parameters

cmd (AppCommand) – Command to add

await add_commands(commands)

This function is a coroutine.

Add a list of app commands

Parameters

commands (List[AppCommand]) – List of command objects to add

await get_commands()

This function is a coroutine.

Get a list of app commands

Returns

List of commands.

Return type

List[AppCommand]

await initialize()

This function is a coroutine.

Call methods of this class to refresh all app commands

await remove_command(cmd, keep=False)

This function is a coroutine.

Remove a specific command

Parameters
  • cmd (AppCommand) – What command to delete

  • keep (bool) – Whether the command should be removed from the ChatCommandHandler. Set to True to keep the command.

    Default: False

await remove_commands(commands, /, keep=None)

This function is a coroutine.

Remove a list of commands

Parameters
  • commands (List[AppCommand]) – List of commands to delete

  • keep (List[AppCommand]) – List of commands that should not be removed from the ChatCommandHandler.

    Default: None

await update_command(cmd, changes)

This function is a coroutine.

Update a command with changes

Parameters
  • cmd (AppCommand) – What command to update

  • changes (Dict[str, Any]) – Dictionary of changes

await update_commands(to_update)

This function is a coroutine.

Update a list of app commands with changes

Parameters

to_update (Dict[AppCommand, Dict[str, Any]]) – Dictionary of commands to changes where changes is a dictionary too

Exceptions

exception PincerError

Bases: Exception

Base exception class for all Pincer errors

exception UnhandledException

Bases: pincer.exceptions.PincerError

Exception which gets thrown if an exception wasn’t handled.

Please create an issue on our github if this exception gets thrown.

exception NoExportMethod

Bases: pincer.exceptions.PincerError

Exception which gets raised when an export method is expected but not found in a module.

exception CogError

Bases: pincer.exceptions.PincerError

Exception base class for errors related to Cogs.

exception CogNotFound

Bases: pincer.exceptions.CogError

Exception which gets raised when a cog is trying to be loaded/unloaded but is nonexistent.

exception CogAlreadyExists

Bases: pincer.exceptions.CogError

Exception which gets raised when a cog is already loaded, but is trying to be reloaded!

exception NoValidSetupMethod

Bases: pincer.exceptions.CogError

Exception which gets raised when an setup function is expected but none was found!

exception TooManySetupArguments

Bases: pincer.exceptions.CogError

Exception which gets raised when too many arguments were requested in a cog its setup function.

exception NoCogManagerReturnFound

Bases: pincer.exceptions.CogError

Exception which gets raised when no cog return was found from the setup function. (are you missing a return statement?)

exception CommandError

Bases: pincer.exceptions.PincerError

Base class for exceptions which are related to commands.

exception CommandCooldownError

Bases: pincer.exceptions.CommandError

Exception which gets raised when a command cooldown has not been breached.

ctx

The context of the error

Type

MessageContext

exception CommandIsNotCoroutine

Bases: pincer.exceptions.CommandError

Exception raised when the provided command call is not a coroutine.

exception CommandAlreadyRegistered

Bases: pincer.exceptions.CommandError

The command which you are trying to register is already registered.

exception CommandDescriptionTooLong

Bases: pincer.exceptions.CommandError

The provided command description is too long, as it exceeds 100 characters.

exception TooManyArguments

Bases: pincer.exceptions.CommandError

A command can have a maximum of 25 arguments. If this number of arguments gets exceeded, this exception will be raised.

exception InvalidArgumentAnnotation

Bases: pincer.exceptions.CommandError

The provided argument annotation is not known, so it cannot be used.

exception CommandReturnIsEmpty

Bases: pincer.exceptions.CommandError

Cannot return an empty string to an interaction.

exception InvalidCommandGuild

Bases: pincer.exceptions.CommandError

The provided guild id not not valid.

exception InvalidCommandName

Bases: pincer.exceptions.CommandError

Exception raised when the command is considered invalid. This is caused by a name that doesn’t match the command name regex.

exception InvalidEventName

Bases: pincer.exceptions.PincerError

Exception raised when the event name is not a valid event. This can be because the event name did not begin with an on_ or because its not a valid event in the library.

exception InvalidUrlError

Bases: pincer.exceptions.PincerError, ValueError

Exception raised when an invalid url has been provided.

exception EmbedFieldError

Bases: pincer.exceptions.PincerError, ValueError

Exception that is raised when an embed field is too large.

exception TaskError

Bases: pincer.exceptions.PincerError

Base class for exceptions that are related to tasks.

task

The task that raised the exception.

Type

Task

exception TaskAlreadyRunning

Bases: pincer.exceptions.TaskError

Exception that is raised when the user tries to start a running task.

exception TaskCancelError

Bases: pincer.exceptions.TaskError

Exception that is raised when a task cannot be cancelled.

exception TaskIsNotCoroutine

Bases: pincer.exceptions.TaskError

Exception that is raised when the provided function for a task is not a coroutine.

exception TaskInvalidDelay

Bases: pincer.exceptions.TaskError

Exception that is raised when the provided delay is invalid.

exception DispatchError

Bases: pincer.exceptions.PincerError

Base exception class for all errors which are specifically related to the dispatcher.

exception DisallowedIntentsError

Bases: pincer.exceptions.DispatchError

Invalid gateway intent got provided. Make sure your client has the enabled intent.

exception InvalidTokenError

Bases: pincer.exceptions.DispatchError, ValueError

Exception raised when the authorization token is invalid.

exception HeartbeatError

Bases: pincer.exceptions.DispatchError

Exception raised due to a problem with websocket heartbeat.

exception UnavailableGuildError

Bases: pincer.exceptions.PincerError

Exception raised due to a guild being unavailable. This is caused by a discord outage.

exception HTTPError

Bases: pincer.exceptions.PincerError

HTTP Exception base class.

exception NotModifiedError

Bases: pincer.exceptions.HTTPError

Error code 304.

exception BadRequestError

Bases: pincer.exceptions.HTTPError

Error code 400.

exception UnauthorizedError

Bases: pincer.exceptions.HTTPError

Error code 401.

exception ForbiddenError

Bases: pincer.exceptions.HTTPError

Error code 403.

exception NotFoundError

Bases: pincer.exceptions.HTTPError

Error code 404.

exception MethodNotAllowedError

Bases: pincer.exceptions.HTTPError

Error code 405.

exception RateLimitError

Bases: pincer.exceptions.HTTPError

Error code 429.

exception GatewayError

Bases: pincer.exceptions.HTTPError

Error code 502.

exception ServerError

Bases: pincer.exceptions.HTTPError

Error code 5xx.

Exception Hierarchy

pincer.core

Dispatching

GatewayDispatch

class GatewayDispatch

Bases: object

Represents a websocket message.

op

The discord opcode which represents what the message means.

Type

int

data

The event data that has been sent/received.

Type

Optional[Union[int, Dict[str, Any]]]

seq

The sequence number of a message, which can be used for resuming sessions and heartbeats.

Type

Optional[int]

event_name

The event name for the payload.

Type

Optional[str]

classmethod from_string(payload)

Parses a given payload from a string format and returns a GatewayDispatch.

Parameters

payload (str) – The payload to parse.

Returns

The new class.

Return type

GatewayDispatch

Gateway

Dispatcher

Attributes
Methods
class Dispatcher

Bases: object

The Dispatcher handles all interactions with discord websocket API. This also contains the main event loop, and handles the heartbeat.

Running the dispatcher will create a connection with the Discord WebSocket API on behalf of the provided token.

This token must be a bot token. (Which can be found on https://discord.com/developers/applications/)

await close()

This function is a coroutine.

Stop the dispatcher from listening and responding to gateway events. This should let the client close on itself.

property intents

app.Intents

await restart(seq=None)

Restart the dispatcher.

:param seq Optional[int]: The sequence number of the last dispatched event.

If not provided, the dispatcher will restart with no base sequence.

start_loop(*, loop=None)

Instantiate the dispatcher, this will create a connection to the Discord websocket API on behalf of the client who’s token has been passed.

Parameters

loop (AbstractEventLoop) – The loop in which the Dispatcher will run. If no loop is provided it will get a new one.

Default: None

Heartbeat

Heartbeat

class Heartbeat

Bases: object

The heartbeat of the websocket connection.

This is what lets the server and client know that they are still both online and properly connected.

classmethod get()

Get the current heartbeat.

Returns

The current heartbeat of the client.

Default: 0 (client has not initialized the heartbeat yet.)

Return type

float

classmethod await handle_heartbeat(socket, _)

This function is a coroutine.

Handles a heartbeat, which means that it rests and then sends a new heartbeat.

Parameters
  • socket (WebSocketClientProtocol) – The socket to send the heartbeat to.

  • _ – Filling param for auto event handling.

classmethod await handle_hello(socket, payload)

This function is a coroutine.

Handshake between the discord API and the client. Retrieve the heartbeat for maintaining a connection.

Parameters
Raises

HeartbeatError – No heartbeat_interval is present.

classmethod update_sequence(seq)

Update the heartbeat sequence.

Parameters

seq (int) – The new heartbeat sequence to be updated with.

Http

HTTPClient

Attributes
Methods
class HTTPClient

Bases: object

Interacts with Discord API through HTTP protocol

url

f"https://discord.com/api/v{version}" “Base url for all HTTP requests”

Type

str

max_tts

Max amount of attempts after error code 5xx

Type

int

await close()

This function is a coroutine.

Closes the aiohttp session

await delete(route, headers=None)

This function is a coroutine.

Sends a delete request to a Discord REST endpoint.

Parameters
  • route (str) – The Discord REST endpoint to send a delete request to.

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

    Default: None

Returns

The response from discord.

Return type

Optional[Dict]

await get(route)

This function is a coroutine.

Sends a get request to a Discord REST endpoint.

Parameters

route (str) – The Discord REST endpoint to send a get request to.

Returns

The response from discord.

Return type

Optional[Dict]

await head(route)

This function is a coroutine.

Sends a head request to a Discord REST endpoint.

Parameters

route (str) – The Discord REST endpoint to send a head request to.

Returns

The response from discord.

Return type

Optional[Dict]

await options(route)

This function is a coroutine.

Sends a options request to a Discord REST endpoint.

Parameters

route (str) – The Discord REST endpoint to send a options request to.

Returns

The response from discord.

Return type

Optional[Dict]

await patch(route, data=None, content_type='application/json', headers=None)

This function is a coroutine.

Sends a patch request to a Discord REST endpoint.

Parameters
  • route (str`) – The Discord REST endpoint to send a patch request to.

  • data (Dict) – The update data for the patch request.

  • content_type (str) – Body content type.

    Default: application/json

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

Returns

JSON response from the discord API.

Return type

Optional[Dict]

await post(route, data=None, content_type='application/json', headers=None)

This function is a coroutine.

Sends a post request to a Discord REST endpoint

Parameters
  • route (str) – The Discord REST endpoint to send a patch request to.

  • data (Dict) – The update data for the patch request.

  • content_type (str) – Body content type.

    Default: application/json

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

Returns

JSON response from the discord API.

Return type

Optional[Dict]

await put(route, data=None, content_type='application/json', headers=None)

This function is a coroutine.

Sends a put request to a Discord REST endpoint

Parameters
  • route (str) – The Discord REST endpoint to send a patch request to.

  • data (Dict) – The update data for the patch request.

  • content_type (str) – Body content type.

    Default: application/json

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

Returns

JSON response from the discord API.

Return type

Optional[Dict]

pincer.middleware

Activity Join Request

Note

Not implemented yet.

Activity Join

Note

Not implemented yet.

Activity Spectate

Note

Not implemented yet.

Channel Create

channel_create_middleware

channel_create_middleware(self, payload)

This function is a coroutine.

Middleware for on_channel_creation event.

Parameters

payload (GatewayDispatch) – The data received from the ready event.

Returns

"on_channel_creation" and a channel.

Return type

Tuple[str, List[Channel]]

Error

error_middleware

error_middleware(self, payload)

This function is a coroutine.

Middleware for on_error event.

Parameters

payload (GatewayDispatch) – The data received from the ready event.

Returns

"on_error" and a DiscordError

Return type

Tuple[str, List[DiscordError]]

Guild Create

guild_create_middleware

await guild_create_middleware(self, payload)

This function is a coroutine.

Middleware for on_guild_create,

generate the guild class that was created

Parameters

payload (GatewayDispatch) – The data received from the guild create event

Returns

on_guild_create and a Guild

Return type

Tuple[str, List[Guild]]

Guild Status

Note

Not implemented yet.

Interaction Create

convert_message

interaction_response_handler

await interaction_response_handler(self, command, context, interaction, kwargs)

This function is a coroutine.

Handle any coroutine as a command.

Parameters
  • command (Coro) – The coroutine which will be seen as a command.

  • context (MessageContext) – The context of the command.

  • interaction (Interaction) – The interaction which is linked to the command.

  • **kwargs – The arguments to be passed to the command.

interaction_handler

await interaction_handler(self, interaction, context, command)

This function is a coroutine.

Processes an interaction.

Parameters
  • interaction (Interaction) – The interaction which is linked to the command.

  • context (MessageContext) – The context of the command.

  • command (Coro) – The coroutine which will be seen as a command.

interaction_create_middleware

await interaction_create_middleware(self, payload)

Middleware for on_interaction, which handles command execution.

Parameters

payload (GatewayDispatch) – The data received from the interaction event.

Raises

e – Generic try except on await interaction_handler and if 0 < len(params) < 3

Returns

on_interaction_create and an Interaction

Return type

Tuple[str, List[Interaction]]

Message Create

message_create_middleware

await message_create_middleware(self, payload)

This function is a coroutine.

Middleware for on_message event.

Parameters

payload (pincer.core.dispatch.GatewayDispatch) – The data received from the message creation event.

Returns

on_message and a UserMessage

Return type

Tuple[str, List[UserMessage]]

Message Delete

on_message_delete_middleware

await on_message_delete_middleware(self, payload)

This function is a coroutine. Middleware for on_message_delete event.

Parameters

payload (GatewayDispatch) – The data received from the message delete event

Returns

on_message_delete and a MessageDeleteEvent

Return type

Tuple[str, MessageDeleteEvent]

Message Update

message_update_middleware

await message_update_middleware(self, payload)

This function is a coroutine.

Middleware for on_message_update event,

generate a class for the message that has been updated.

Parameters

payload (GatewayDispatch) – The data received from the message update event event

Returns

on_message_update and a UserMessage

Return type

Tuple[str, List[UserMessage]]

Notification Create

Note

Not implemented yet.

Payload

payload_middleware

await payload_middleware(payload)

Invoked when basically anything is received from gateway.

Parameters

payload (pincer.core.dispatch.GatewayDispatch) – The data received from the ready event.

Returns

on_payload and a payload

Return type

Tuple[str, List[GatewayDispatch]]

Ready

on_ready_middleware

await on_ready_middleware(self, payload)

This function is a coroutine.

Middleware for on_ready event.

Parameters

payload (GatewayDispatch) – The data received from the stage instance create event

Returns

on_ready

Return type

Tuple[str]

Speaking Start

Note

Not implemented yet.

Speaking Stop

Note

Not implemented yet.

Voice Channel Select

Note

Not implemented yet.

Voice Connection Status

Note

Not implemented yet.

Voice Settings Update

Note

Not implemented yet.

Voice State Create

Note

Not implemented yet.

Voice State Delete

Note

Not implemented yet.

Voice State Update

voice_state_update_middleware

await voice_state_update_middleware(self, payload)

This function is a coroutine. Middleware for on_voice_state_update event.

Parameters

payload (GatewayDispatch) – The data received from the voice state update event.

Returns

on_voice_state_update and a VoiceState

Return type

Tuple[str, List[VoiceState]]

pincer.utils

Api Object

APIObject

class APIObject

Bases: object

Represents an object which has been fetched from the Discord API.

classmethod from_dict(data)

Parse an API object from a dictionary.

to_dict()

Transform the current object to a dictionary representation.

Directory

chdir

Signature

get_signature_and_params

get_signature_and_params(func)

Get the parameters and signature from a coroutine.

func: Callable

The coroutine from whom the information should be extracted.

Returns

Signature and ist of parameters of the coroutine.

Return type

Tuple[List[Union[str, inspect.Parameter]]]

get_params

get_params(func)

Get the parameters from a coroutine.

func: Callable

The coroutine from whom the information should be extracted.

Returns

List of parameters of the coroutine.

Return type

List[Union[str, inspect.Parameter]]

Snowflake

Snowflake

class Snowflake

Bases: int

Discord utilizes Twitter’s snowflake format for uniquely identifiable descriptors (IDs).

These IDs are guaranteed to be unique across all of Discord, except in some unique scenarios in which child objects share their parent’s ID.

Because Snowflake IDs are up to 64 bits in size (e.g. a uint64), they are always returned as strings in the HTTP API to prevent integer overflows in some languages.

classmethod from_string(string)

Initialize a new Snowflake from a string.

Parameters

string (str) – The snowflake as a string.

property increment

For every ID that is generated on that process, this number is incremented.

Type

int

property process_id

Internal process ID

Type

int

property timestamp

Milliseconds since Discord Epoch, the first second of 2015 or 14200704000000

Type

int

property worker_id

Internal worker ID

Type

int

Tasks

Task

Methods
class Task

Bases: object

A Task is a coroutine that is scheduled to repeat every x seconds. Use a TaskScheduler in order to create a task. :param scheduler: The scheduler to use. :type scheduler: TaskScheduler :param coro: The coroutine to register as a task. :type coro: Coro :param delay: Delay between each iteration of the task. :type delay: float

cancel()

Cancel the task.

property cancelled

Check if the task has been cancelled or not.

Type

bool

property client_required
property running

Check if the task is running.

Type

bool

start()

Register the task in the TaskScheduler and start the execution of the task.

TaskScheduler

Methods
class TaskScheduler

Bases: object

@loop(days=0, weeks=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0)

A decorator to create a task that repeat the given amount of t :Example usage:

Parameters
  • days (int) – Days to wait between iterations.

    Default: 0

  • weeks (int) – Days to wait between iterations.

    Default: 0

  • hours (int) – Days to wait between iterations.

    Default: 0

  • minutes (int) – Days to wait between iterations.

    Default: 0

  • seconds (int) – Days to wait between iterations.

    Default: 0

  • milliseconds (int) – Days to wait between iterations.

    Default: 0

  • microseconds (int) – Days to wait between iterations.

    Default: 0

Raises
  • TaskIsNotCoroutine: – The task is not a coroutine.

  • TaskInvalidDelay: – The delay is 0 or negative.

close()

Gracefully stops any running task.

register(task)

Register a task. :param task: The task to register. :type task: Task

Timestamp

Timestamp

Attributes
class Timestamp

Bases: object

Contains a lot of useful methods for working with timestamps.

date

The time of the timestamp.

Type

str

time

Alias for date.

Type

str

Parameters

time (Union[str, int, float, datetime.datetime]) –

staticmethod epoch_to_datetime(epoch)

Convert an epoch to a datetime object.

epoch: Union[int, float]

The epoch to convert to a datetime object.

Returns

The converted datetime object.

Return type

datetime.datetime

staticmethod parse(time=None)

Convert a time to datetime object.

time: Optional[Union[str, int, float, datetime.datetime]]

The time to be converted to a datetime object. This can be one of these types: datetime, float, int, str

If no parameter is passed it will return the current datetime.

Returns

The converted datetime object.

Return type

datetime.datetime

staticmethod string_to_datetime(string)

Convert a string to a datetime object.

string: str

The string to convert.

Returns

The converted datetime object.

Return type

datetime.datetime

staticmethod to_epoch(time)

Convert a datetime to an epoch.

time: datetime.datetime

The datetime to convert.

Returns

The epoch time integer.

Return type

int

Types

MissingType

class MissingType

Bases: object

Type class for missing attributes and parameters.

MISSING

pincer.utils.MISSING: MissingType

APINullable

APINullable: Union[T, MissingType]

Represents a value which is optionally returned from the API

Coro

Coro: TypeVar("Coro", bound=Callable[..., Coroutine[Any, Any, Any]])

Represents a coroutine.

choice_value_types

choice_value_types: Tuple[str, int, float]