API Reference¶
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
- 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.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)¶
This function is a coroutine. Fetch a Channel from its identifier. The
get_dm_channelmethod fromUsershould be used if you need to create a dm_channel; using thesend()method fromUseris 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_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
- 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
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 )
- 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
pincer.core¶
Dispatching¶
GatewayDispatch¶
- class GatewayDispatch¶
Bases:
objectRepresents a websocket message.
- seq¶
The sequence number of a message, which can be used for resuming sessions and heartbeats.
- Type
Optional[
int]
Gateway¶
Dispatcher¶
- asyncclose
- asyncrestart
- defstart_loop
- class Dispatcher¶
Bases:
objectThe 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.
- :param seq Optional[
- 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:
objectThe 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
- 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
socket (
WebSocketClientProtocol) – The socket to send the heartbeat to.payload (
GatewayDispatch) – The received hello message from the Discord gateway.
- Raises
HeartbeatError – No
heartbeat_intervalis present.
Http¶
HTTPClient¶
- class HTTPClient¶
Bases:
objectInteracts with Discord API through HTTP protocol
- await delete(route, headers=None)¶
This function is a coroutine.
Sends a delete request to a Discord REST endpoint.
- 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
- 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
- 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_creationevent.- Parameters
payload (
GatewayDispatch) – The data received from the ready event.- Returns
"on_channel_creation"and a channel.- Return type
Error¶
error_middleware¶
- error_middleware(self, payload)¶
This function is a coroutine.
Middleware for
on_errorevent.- Parameters
payload (
GatewayDispatch) – The data received from the ready event.- Returns
"on_error"and aDiscordError- 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_createand aGuild- Return type
Tuple[
str, List[Guild]]
- Middleware for
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_handlerandif 0 < len(params) < 3- Returns
on_interaction_createand anInteraction- 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_messageevent.- Parameters
payload (
pincer.core.dispatch.GatewayDispatch) – The data received from the message creation event.- Returns
on_messageand aUserMessage- 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_deleteevent.- Parameters
payload (
GatewayDispatch) – The data received from the message delete event- Returns
on_message_deleteand aMessageDeleteEvent- 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_updateevent, 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_updateand aUserMessage- Return type
Tuple[
str, List[UserMessage]]
- Middleware for
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_payloadand apayload- Return type
Tuple[
str, List[GatewayDispatch]]
Ready¶
on_ready_middleware¶
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_updateevent.- Parameters
payload (
GatewayDispatch) – The data received from the voice state update event.- Returns
on_voice_state_updateand aVoiceState- Return type
Tuple[
str, List[VoiceState]]
pincer.utils¶
Api Object¶
APIObject¶
- clsAPIObject.from_dict
- defto_dict
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:
intDiscord 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
- property timestamp¶
Milliseconds since Discord Epoch, the first second of 2015 or 14200704000000
- Type
Tasks¶
Task¶
- class Task¶
Bases:
objectA 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 client_required¶
- start()¶
Register the task in the TaskScheduler and start the execution of the task.
TaskScheduler¶
- 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:0weeks (
int) – Days to wait between iterations.Default:0hours (
int) – Days to wait between iterations.Default:0minutes (
int) – Days to wait between iterations.Default:0seconds (
int) – Days to wait between iterations.Default:0milliseconds (
int) – Days to wait between iterations.Default:0microseconds (
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.
Timestamp¶
Timestamp¶
- defepoch_to_datetime
- defparse
- defstring_to_datetime
- defto_epoch
- class Timestamp¶
Bases:
objectContains a lot of useful methods for working with timestamps.
- Parameters
time (Union[
str,int,float,datetime.datetime]) –
- staticmethod epoch_to_datetime(epoch)¶
Convert an epoch to a datetime object.
- Returns
The converted datetime object.
- Return type
- 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
- time: Optional[Union[
- 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
- string:
- staticmethod to_epoch(time)¶
Convert a datetime to an epoch.
- time:
datetime.datetime The datetime to convert.
- Returns
The epoch time integer.
- Return type
- time:
Types¶
MissingType¶
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.