Pincer Module¶
Clients¶
Client¶
- @event
- asyncevent_handler
- asyncexecute_error
- defexecute_event
- asyncget_channel
- defget_cogs
- defget_event_coro
- asyncget_guild
- asyncget_role
- asyncget_user
- asynchandle_middleware
- defload_cog
- asyncpayload_event_handler
- asyncprocess_event
- defrun
- asyncunload_cog
- class Client(token, *, received=None, intents=None, throttler=<class 'pincer.objects.app.throttling.DefaultThrottleHandler'>, reconnect=True)¶
Bases:
pincer.core.gateway.DispatcherThe client is the main instance which is between the programmer and the discord API.
This client represents your bot.
- http¶
The http client used to communicate with the discord API
- Type
- Parameters
token (
str) – The token to login with your bot from the developer portalreceived (Optional[
str]) – The default message which will be sent when no response is given.Default:Noneintents (Optional[
Intents]) – The discord intents to useDefault:Nonethrottler (Optional[
ThrottleInterface]) – The cooldown handler for your client, defaults toDefaultThrottleHandler(which uses the WindowSliding technique). Custom throttlers must derive fromThrottleInterface.Default:DefaultThrottleHandler
- 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
TypeError – If the function is not a coro
InvalidEventName – If the function name is not a valid event (on_x)
- 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.
- 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)¶
Fetch a Channel from its identifier.
- _id:
int The id of the user which should be fetched from the Discord gateway.
- Returns
A Channel object.
- Return type
- _id:
- 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.
- 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
- guild_id:
- 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
*argsand**kwargsfor the event.- Parameters
payload (
GatewayDispatch) – The original payload for the eventkey (
str) – The index of the middleware in_events
- Raises
RuntimeError – The return type must be a tuple
RuntimeError – Middleware has not been registered
- 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
- 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
Commands¶
command¶
- @command(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 )
- Parameters
name (Optional[
str]) – The name of the commandDefault:Nonedescription (Optional[
str]) – The description of the commandDefault:Description not setenable_default (Optional[
bool]) – Whether the command is enabled by defaultDefault:Trueguild (Optional[Union[
Snowflake,int,str]]) – What guild to add it to (don’t specify for global)Default:Nonecooldown (Optional[
int]) – The amount of times in the cooldown_scale the command can be invokedDefault:0cooldown_scale (Optional[
float]) – The ‘checking time’ of the cooldownDefault:60cooldown_scope (
ThrottleScope) – What type of cooldown strategy to useDefault:ThrottleScope.USER
- Raises
CommandIsNotCoroutine – If the command function is not a coro
InvalidCommandName – If the command name does not follow the regex
^[\w-]{1,32}$InvalidCommandGuild – If the guild id is invalid
CommandDescriptionTooLong – Descriptions max 100 characters If the annotation on an argument is too long (also max 100)
CommandAlreadyRegistered – If the command already exists
TooManyArguments – Max 25 arguments to pass for commands
InvalidArgumentAnnotation – Annotation amount is max 25, Not a valid argument type, Annotations must consist of name and value
ChatCommandHandler¶
- asyncadd_command
- asyncadd_commands
- asyncget_commands
- asyncinitialize
- asyncremove_command
- asyncremove_commands
- asyncupdate_command
- asyncupdate_commands
- class ChatCommandHandler¶
Bases:
objectMetaclass containing methods used to handle various commands
- 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 deletekeep (bool) – Whether the command should be removed from the ChatCommandHandler. Set to
Trueto 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 deletekeep (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 updatechanges (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 UnhandledException¶
Bases:
pincer.exceptions.PincerErrorException 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.PincerErrorException which gets raised when an export method is expected but not found in a module.
- exception CogError¶
Bases:
pincer.exceptions.PincerErrorException base class for errors related to Cogs.
- exception CogNotFound¶
Bases:
pincer.exceptions.CogErrorException which gets raised when a cog is trying to be loaded/unloaded but is nonexistent.
- exception CogAlreadyExists¶
Bases:
pincer.exceptions.CogErrorException which gets raised when a cog is already loaded, but is trying to be reloaded!
- exception NoValidSetupMethod¶
Bases:
pincer.exceptions.CogErrorException which gets raised when an setup function is expected but none was found!
- exception TooManySetupArguments¶
Bases:
pincer.exceptions.CogErrorException which gets raised when too many arguments were requested in a cog its setup function.
- exception NoCogManagerReturnFound¶
Bases:
pincer.exceptions.CogErrorException which gets raised when no cog return was found from the setup function. (are you missing a return statement?)
- exception CommandError¶
Bases:
pincer.exceptions.PincerErrorBase class for exceptions which are related to commands.
- exception CommandCooldownError¶
Bases:
pincer.exceptions.CommandErrorException which gets raised when a command cooldown has not been breached.
- ctx¶
The context of the error
- Type
- exception CommandIsNotCoroutine¶
Bases:
pincer.exceptions.CommandErrorException raised when the provided command call is not a coroutine.
- exception CommandAlreadyRegistered¶
Bases:
pincer.exceptions.CommandErrorThe command which you are trying to register is already registered.
- exception CommandDescriptionTooLong¶
Bases:
pincer.exceptions.CommandErrorThe provided command description is too long, as it exceeds 100 characters.
- exception TooManyArguments¶
Bases:
pincer.exceptions.CommandErrorA 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.CommandErrorThe provided argument annotation is not known, so it cannot be used.
- exception CommandReturnIsEmpty¶
Bases:
pincer.exceptions.CommandErrorCannot return an empty string to an interaction.
- exception InvalidCommandGuild¶
Bases:
pincer.exceptions.CommandErrorThe provided guild id not not valid.
- exception InvalidCommandName¶
Bases:
pincer.exceptions.CommandErrorException 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.PincerErrorException 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,ValueErrorException raised when an invalid url has been provided.
- exception EmbedFieldError¶
Bases:
pincer.exceptions.PincerError,ValueErrorException that is raised when an embed field is too large.
- exception TaskError¶
Bases:
pincer.exceptions.PincerErrorBase class for exceptions that are related to tasks.
- exception TaskAlreadyRunning¶
Bases:
pincer.exceptions.TaskErrorException that is raised when the user tries to start a running task.
- exception TaskCancelError¶
Bases:
pincer.exceptions.TaskErrorException that is raised when a task cannot be cancelled.
- exception TaskIsNotCoroutine¶
Bases:
pincer.exceptions.TaskErrorException that is raised when the provided function for a task is not a coroutine.
- exception TaskInvalidDelay¶
Bases:
pincer.exceptions.TaskErrorException that is raised when the provided delay is invalid.
- exception DispatchError¶
Bases:
pincer.exceptions.PincerErrorBase exception class for all errors which are specifically related to the dispatcher.
- exception DisallowedIntentsError¶
Bases:
pincer.exceptions.DispatchErrorInvalid gateway intent got provided. Make sure your client has the enabled intent.
- exception InvalidTokenError¶
Bases:
pincer.exceptions.DispatchError,ValueErrorException raised when the authorization token is invalid.
- exception HeartbeatError¶
Bases:
pincer.exceptions.DispatchErrorException raised due to a problem with websocket heartbeat.
Bases:
pincer.exceptions.PincerErrorException raised due to a guild being unavailable. This is caused by a discord outage.
- exception HTTPError¶
Bases:
pincer.exceptions.PincerErrorHTTP Exception base class.
- exception NotModifiedError¶
Bases:
pincer.exceptions.HTTPErrorError code 304.
- exception BadRequestError¶
Bases:
pincer.exceptions.HTTPErrorError code 400.
- exception UnauthorizedError¶
Bases:
pincer.exceptions.HTTPErrorError code 401.
- exception ForbiddenError¶
Bases:
pincer.exceptions.HTTPErrorError code 403.
- exception NotFoundError¶
Bases:
pincer.exceptions.HTTPErrorError code 404.
- exception MethodNotAllowedError¶
Bases:
pincer.exceptions.HTTPErrorError code 405.
- exception RateLimitError¶
Bases:
pincer.exceptions.HTTPErrorError code 429.
- exception GatewayError¶
Bases:
pincer.exceptions.HTTPErrorError code 502.
- exception ServerError¶
Bases:
pincer.exceptions.HTTPErrorError code 5xx.
Exception Hierarchy¶
ExceptionPincerError- exc
InvalidPayload