Pincer Module

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