Pincer Module¶
Clients¶
Client¶
- asynccreate_guild_from_template
- @event
- asyncevent_handler
- asyncexecute_error
- defexecute_event
- asyncget_channel
- defget_cogs
- defget_event_coro
- asyncget_guild
- asyncget_guild_template
- asyncget_role
- asyncget_user
- asynchandle_middleware
- defload_cog
- defloop_for
- asyncpayload_event_handler
- asyncprocess_event
- defrun
- asyncunload_cog
- asyncwait_for
- 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.
- 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:None
intents (Optional[
Intents
]) – The discord intents to useDefault:None
throttler (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 create_guild_from_template(template, name, icon=None)¶
This function is a coroutine. Creates a guild from a template.
- Parameters
template (
GuildTemplate
) – The guild templatename (
str
) – Name of the guild (2-100 characters)icon (Optional[
str
]) – base64 128x128 image for the guild iconDefault:None
- Returns
The created guild
- Return type
- 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)¶
This function is a coroutine. Fetch a Channel from its identifier. The
get_dm_channel
method fromUser
should be used if you need to create a dm_channel; using thesend()
method fromUser
is preferred.
- 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.
- await get_guild_template(code)¶
This function is a coroutine. Retrieves a guild template by its code.
- Parameters
code (
str
) – The code of the guild template- Returns
The guild template
- Return type
- 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
*args
and**kwargs
for 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
- 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
- Returns
What the Discord API returns for this event.
- Return type
Any
Exceptions¶
- exception InvalidPayload¶
Bases:
pincer.exceptions.PincerError
Exception which gets thrown if an invalid payload has been received. This means that the data of the payload did not match the expected format and/or didn’t contain the the expected values.
- 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
- 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.
- 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.
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.