Pincer Module#
Clients#
Client#
- defclose
- asynccreate_group_dm
- asynccreate_guild_from_template
- asynccreate_stage
- asynccrosspost_message
- asyncdelete_stage
- @event
- asyncevent_handler
- asyncexecute_error
- defexecute_event
- asyncget_channel
- asyncget_connections
- asyncget_current_user
- asyncget_current_user_guilds
- defget_event_coro
- asyncget_guild
- asyncget_guild_template
- asyncget_message
- asyncget_role
- defget_shard
- asyncget_stage
- asyncget_user
- asyncget_webhook
- asynchandle_middleware
- asyncleave_guild
- defload_cog
- defload_cogs
- defload_module
- defloop_for
- asyncmodify_current_user
- asyncmodify_stage
- asyncpayload_event_handler
- asyncprocess_event
- defreload_cogs
- defrun
- defrun_autosharded
- defrun_shards
- asyncstart_shard
- asyncsticker_packs
- defunassign
- asyncwait_for
- class Client(token, *, received=None, intents=None, throttler=<class 'pincer.objects.app.throttling.DefaultThrottleHandler'>, reconnect=True)#
Bases:
Interactable
,CogManager
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[Union[Iterable[
Intents
],Intents
]]) – The discord intents to useDefault:Intents.all()
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
]
- close()#
Ensure close of the http client. Allow for script execution to continue.
- property cogs#
Get a dictionary of all loaded cogs.
The key/value pair is import path/cog class.
- Returns
The list of cogs
- Return type
List[
Cog
]
- await create_group_dm(access_tokens, nicks)#
This function is a coroutine. Create a new group DM channel with multiple users. DMs created with this endpoint will not be shown in the Discord client
- 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 create_stage(channel_id, topic, privacy_level=None, reason=None)#
This function is a coroutine.
- Parameters
channel_id (
int
) – The id of the Stage channeltopic (
str
) – The topic of the Stage instance (1-120 characters)privacy_level (Optional[
PrivacyLevel
]) – The privacy level of the Stage instance (defaultGUILD_ONLY
)reason (Optional[
str
]) – The reason for creating the Stage instance
- Returns
The Stage instance created
- Return type
- await crosspost_message(channel_id, message_id)#
This function is a coroutine. Crosspost a message in a News Channel to following channels.
This endpoint requires the
SEND_MESSAGES
permission, if the current user sent the message, or additionally theMANAGE_MESSAGES
permission, for all other messages, to be present for the current user.
- await delete_stage(_id, reason=None)#
This function is a coroutine. Deletes the Stage instance. Requires the user to be a moderator of the Stage channel.
- await event_handler(gateway, payload)#
This function is a coroutine.
Handles all payload events with opcode 0.
- Parameters
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, gateway, 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 eventname (
str
) – the name of the eventDefault:on_error
- Raises
error – if
call := self.get_event_coro(name)
isFalse
- staticmethod execute_event(events, gateway, *args, **kwargs)#
Invokes an event.
- Parameters
calls (List[
InteractableStructure
]) – 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.
- async for ... in get_connections()#
This function is a coroutine. Returns a list of connection objects. Requires the
connections
OAuth2 scope.- Yields
Connections
– the connection objects
- await get_current_user()#
This function is a coroutine. The user object of the requester’s account.
For OAuth2, this requires the
identify
scope, which will return the object without an email, and optionally theemail
scope, which returns the object with an email.- Return type
- async for ... in get_current_user_guilds(before=None, after=None, limit=None)#
This function is a coroutine. Returns a list of partial guild objects the current user is a member of. Requires the
guilds
OAuth2 scope.- Parameters
before (Optional[
Snowflake
]) – get guilds before this guild IDafter (Optional[
Snowflake
]) – get guilds after this guild IDlimit (Optional[
int
]) – max number of guilds to return (1-200)Default:200
- Yields
Guild
– A Partial Guild that the user is in- staticmethod get_event_coro(name)#
get the coroutine for an event
- await get_guild(guild_id, with_count=False)#
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_message(_id, channel_id)#
This function is a coroutine. Creates a UserMessage object
- Parameters
- Returns
The message object.
- 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:
- get_shard(guild_id=None, num_shards=None)#
Returns the shard receiving events for a specified guild_id.
num_shards
is inferred from the num_shards value for the first started shard. If your shards do not all have the samenum_shard
value, you must specify value to get the expected result.- Parameters
guild_id (Optional[
Snowflake
]) – The guild_id of the shard to look for. If no guild id is provided, the shard that receives dms will be returned.Default:None
num_shards (Optional[
int
]) – The number of shards. If no number is provided, the value will default to the num_shards for the first started shard.Default:None
- await get_stage(_id)#
This function is a coroutine. Gets the stage instance associated with the Stage channel, if it exists
- Parameters
_id (int) – The ID of the stage to get
- Returns
The stage instance
- Return type
- await get_webhook(id, token=None)#
This function is a coroutine. Fetch a Webhook from its identifier.
- property guild_ids#
Returns a list of Guilds that the client is a part of
- Return type
- await handle_middleware(payload, key, gateway, *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
- property is_closed#
returns: Whether the bot is closed. :rtype: bool
- await leave_guild(_id)#
This function is a coroutine. Leave a guild.
- Parameters
_id (
Snowflake
) – the id of the guild that the bot will leave
- load_cog(cog)#
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 from cogs.say import SayCommand class MyClient(Client): def __init__(self, *args, **kwargs): self.load_cog(SayCommand) super().__init__(*args, **kwargs)
cogs/say.py
from pincer import command class SayCommand(Cog): @command() async def say(self, message: str) -> str: return message
- Parameters
cog (Type[
Cog
]) – The cog to load.
- load_module(module)#
Loads the cogs from a module recursively.
- Parameters
module (
ModuleType
) – The module to load.
- 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 modify_current_user(username=None, avatar=None)#
This function is a coroutine. Modify the requester’s user account settings
- Parameters
username (Optional[
str
]) – user’s username, if changed may cause the user’s discriminator to be randomized.Default:None
avatar (Optional[
File
]) – if passed, modifies the user’s avatar a data URI scheme of JPG, GIF or PNGDefault:None
- Returns
Current modified user
- Return type
- await modify_stage(_id, topic=None, privacy_level=None, reason=None)#
This function is a coroutine. Updates fields of an existing Stage instance. Requires the user to be a moderator of the Stage channel.
- Parameters
_id (int) – The ID of the stage to modify
topic (Optional[
str
]) – The topic of the Stage instance (1-120 characters)privacy_level (Optional[
PrivacyLevel
]) – The privacy level of the Stage instancereason (Optional[
str
]) – The reason for the modification
- await payload_event_handler(gateway, payload)#
This function is a coroutine.
Special event which activates the on_payload event.
- Parameters
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, gateway)#
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.
- reload_cogs()#
Reloads all of the loaded cogs
- run()#
Start the bot.
- run_autosharded()#
Runs the bot with the amount of shards specified by the Discord gateway.
- run_shards(shards, num_shards)#
Runs shards that you specify.
- shards: Iterable
The shards to run.
- num_shards: int
The total amount of shards.
- await start_shard(shard, num_shards)#
This function is a coroutine. Starts a shard This should not be run most of the time.
run_shards
andrun_autosharded
will likely do what you want.- shardint
The number of the shard to start.
- num_shardsint
The total number of shards.
- async for ... in sticker_packs()#
This function is a coroutine. Yields sticker packs available to Nitro subscribers.
- Yields
StickerPack
– a sticker pack
- unassign()#
Removes this objects loaded commands from ChatCommandHandler and ComponentHandler and removes loaded events from the client.
- 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:
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 expected values.
- exception UnhandledException#
Bases:
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:
PincerError
Exception which gets raised when an export method is expected but not found in a module.
- exception CogError#
Bases:
PincerError
Exception base class for errors related to Cogs.
- exception CogNotFound#
Bases:
CogError
Exception which gets raised when a cog is trying to be loaded/unloaded but is nonexistent.
- exception CogAlreadyExists#
Bases:
CogError
Exception which gets raised when a cog is already loaded, but is trying to be reloaded!
- exception NoValidSetupMethod#
Bases:
CogError
Exception which gets raised when an setup function is expected but none was found!
- exception TooManySetupArguments#
Bases:
CogError
Exception which gets raised when too many arguments were requested in a cog its setup function.
- exception NoCogManagerReturnFound#
Bases:
CogError
Exception which gets raised when no cog return was found from the setup function. (are you missing a return statement?)
- exception CommandError#
Bases:
PincerError
Base class for exceptions which are related to command.
- exception CommandCooldownError#
Bases:
CommandError
Exception which gets raised when a command cooldown has not been breached.
- ctx#
The context of the error
- Type
MessageContext
- exception CommandIsNotCoroutine#
Bases:
CommandError
Exception raised when the provided command call is not a coroutine.
- exception CommandAlreadyRegistered#
Bases:
CommandError
The command which you are trying to register is already registered.
- exception CommandDescriptionTooLong#
Bases:
CommandError
The provided command description is too long, as it exceeds 100 characters.
- exception TooManyArguments#
Bases:
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:
CommandError
The provided argument annotation is not known, so it cannot be used.
- exception CommandReturnIsEmpty#
Bases:
CommandError
Cannot return an empty string to an interaction.
- exception ImageEncodingError#
Bases:
PincerError
Exception raised when an image cannot be encoded for Discord
- exception InvalidCommandGuild#
Bases:
CommandError
The provided guild id not not valid.
- exception InvalidCommandName#
Bases:
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:
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 it’s not a valid event in the library.
- exception InvalidUrlError#
Bases:
PincerError
,ValueError
Exception raised when an invalid url has been provided.
- exception EmbedFieldError#
Bases:
PincerError
,ValueError
Exception that is raised when an embed field is too large.
- exception TaskError#
Bases:
PincerError
Base class for exceptions that are related to task.
- task#
The task that raised the exception.
- Type
Task
- exception TaskAlreadyRunning#
Bases:
TaskError
Exception that is raised when the user tries to start a running task.
- exception TaskCancelError#
Bases:
TaskError
Exception that is raised when a task cannot be cancelled.
- exception TaskIsNotCoroutine#
Bases:
TaskError
Exception that is raised when the provided function for a task is not a coroutine.
- exception TaskInvalidDelay#
Bases:
TaskError
Exception that is raised when the provided delay is invalid.
- exception DispatchError#
Bases:
PincerError
Base exception class for all errors which are specifically related to the dispatcher.
- exception DisallowedIntentsError#
Bases:
DispatchError
Invalid gateway intent got provided. Make sure your client has the enabled intent.
- exception InvalidTokenError#
Bases:
DispatchError
,ValueError
Exception raised when the authorization token is invalid.
- exception HeartbeatError#
Bases:
DispatchError
Exception raised due to a problem with websocket heartbeat.
Bases:
PincerError
Exception raised due to a guild being unavailable. This is caused by a discord outage.
- exception TimeoutError#
Bases:
PincerError
Exception raised when
EventMgr
wait_for and loop_for methods time out
- exception GatewayConnectionError#
Bases:
PincerError
Could not connect to Discord gateway
- exception HTTPError#
Bases:
PincerError
HTTP Exception base class.
Exception Hierarchy#