hikari.impl.rest_bot#
Standard implementations of a Interaction based REST-only bot.
Module Contents#
- class hikari.impl.rest_bot.RESTBot(token, *, public_key = None, allow_color = True, banner = 'hikari', executor = None, force_color = False, http_settings = None, logs = 'INFO', max_rate_limit = 300.0, max_retries = 3, proxy_settings = None, rest_url = None) RESTBot(token, token_type, public_key = None, *, allow_color = True, banner = 'hikari', executor = None, force_color = False, http_settings = None, logs = 'INFO', max_rate_limit = 300.0, max_retries = 3, proxy_settings = None, rest_url = None)[source]#
Bases:
hikari.traits.RESTBotAware
,hikari.api.interaction_server.InteractionServer
Basic implementation of an interaction based REST-only bot.
- Parameters
- token
typing.Union
[str
,hikari.api.rest.TokenStrategy
] The bot or bearer token.
- token_type
typing.Union
[str
,hikari.applications.TokenType
,None
] The type of token in use. This should only be passed when
str
is passed fortoken
, can be"Bot"
or"Bearer"
.This should be left as
None
whenhikari.api.rest.TokenStrategy
is passed fortoken
.
- token
- Other Parameters
- allow_colorbool
Defaulting to
True
, this will enable coloured console logs on any platform that is a TTY. Setting a"CLICOLOR"
environment variable to any non `0` value will override this setting.Users should consider this an advice to the application on whether it is safe to show colours if possible or not. Since some terminals can be awkward or not support features in a standard way, the option to explicitly disable this is provided. See
force_color
for an alternative.- banner
typing.Optional
[str
] The package to search for a
banner.txt
in. Defaults to"hikari"
for the"hikari/banner.txt"
banner. Setting this toNone
will disable the banner being shown.- executor
typing.Optional
[concurrent.futures.Executor
] Defaults to
None
. If non-None
, then this executor is used instead of theconcurrent.futures.ThreadPoolExecutor
attached to theasyncio.AbstractEventLoop
that the bot will run on. This executor is used primarily for file-IO.While mainly supporting the
concurrent.futures.ThreadPoolExecutor
implementation in the standard lib, Hikari’s file handling systems should also work withconcurrent.futures.ProcessPoolExecutor
, which relies on all objects used in IPC to be pickleable. Many third-party libraries will not support this fully though, so your mileage may vary on using ProcessPoolExecutor implementations with this parameter.- force_colorbool
Defaults to
False
. IfTrue
, then this application will __force__ colour to be used in console-based output. Specifying a"CLICOLOR_FORCE"
environment variable with a non-"0"
value will override this setting.This will take precedence over
allow_color
if both are specified.- http_settings
typing.Optional
[hikari.config.HTTPSettings
] Optional custom HTTP configuration settings to use. Allows you to customise functionality such as whether SSL-verification is enabled, what timeouts
aiohttp
should expect to use for requests, and behavior regarding HTTP-redirects.- logs
typing.Union
[None
,LoggerLevel
,typing.Dict
[str
,typing.Any
]] Defaults to
"INFO"
.If
None
, then the Python logging system is left uninitialized on startup, and you will need to configure it manually to view most logs that are output by components of this library.If one of the valid values in a
LoggerLevel
, then this will match a call tocolorlog.basicConfig
(a facade forlogging.basicConfig
with additional conduit for enabling coloured logging levels) with thelevel
kwarg matching this value.If a
typing.Dict[str, typing.Any]
equivalent, then this value is passed tologging.config.dictConfig
to allow the user to provide a specialized logging configuration of their choice. If any handlers are defined in the dict, default handlers will not be setup.As a side note, you can always opt to leave this on the default value and then use an incremental
logging.config.dictConfig
that applies any additional changes on top of the base configuration, if you prefer. An example of can be found in theExample
section.Note that
"TRACE_HIKARI"
is a library-specific logging level which is expected to be more verbose than"DEBUG"
.- max_rate_limit
float
The max number of seconds to backoff for when rate limited. Anything greater than this will instead raise an error.
This defaults to five minutes if left to the default value. This is to stop potentially indefinitely waiting on an endpoint, which is almost never what you want to do if giving a response to a user.
You can set this to
float("inf")
to disable this check entirely.Note that this only applies to the REST API component that communicates with Discord, and will not affect sharding or third party HTTP endpoints that may be in use.
- max_retries
typing.Optional
[int
] Maximum number of times a request will be retried if it fails with a
5xx
status. Defaults to 3 if set toNone
.- proxy_settings
typing.Optional
[hikari.impl.config.ProxySettings
] Custom proxy settings to use with network-layer logic in your application to get through an HTTP-proxy.
- public_key
typing.Union
[str
,bytes
,None
] The public key to use to verify received interaction requests. This may be a hex encoded
str
or the rawbytes
. If left asNone
then the client will try to work this value out based ontoken
.- rest_url
typing.Optional
[str
] Defaults to the Discord REST API URL if
None
. Can be overridden if you are attempting to point to an unofficial endpoint, or if you are attempting to mock/stub the Discord API for any reason. Generally you do not want to change this.
- Raises
- static print_banner(banner, allow_color, force_color, extra_args=None)[source]#
Print the banner.
This allows library vendors to override this behaviour, or choose to inject their own “branding” on top of what hikari provides by default.
Normal users should not need to invoke this function, and can simply change the
banner
argument passed to the constructor to manipulate what is displayed.- Parameters
- banner
typing.Optional
[str
] The package to find a
banner.txt
in.- allow_colorbool
A flag that allows advising whether to allow color if supported or not. Can be overridden by setting a
"CLICOLOR"
environment variable to a non-"0"
string.- force_colorbool
A flag that allows forcing color to always be output, even if the terminal device may not support it. Setting the
"CLICOLOR_FORCE"
environment variable to a non-"0"
string will override this.This will take precedence over
allow_color
if both are specified.- extra_args
typing.Optional
[typing.Dict
[str
,str
]] If provided, extra $-substitutions to use when printing the banner. Default substitutions can not be overwritten.
- banner
- Raises
ValueError
If
extra_args
contains a default $-substitution.
- async on_interaction(body, signature, timestamp)[source]#
Handle an interaction received from Discord as a REST server.
- Parameters
- Returns
Response
Instructions on how the REST server calling this should respond to the interaction request.
- run(asyncio_debug=False, backlog=128, check_for_updates=True, close_loop=True, close_passed_executor=False, coroutine_tracking_depth=None, enable_signal_handlers=None, host=None, path=None, port=None, propagate_interrupts=False, reuse_address=None, reuse_port=None, shutdown_timeout=60.0, socket=None, ssl_context=None)[source]#
Open this REST server and block until it closes.
- Other Parameters
- asyncio_debugbool
Defaults to
False
. IfTrue
, then debugging is enabled for the asyncio event loop in use.- backlog
int
The number of unaccepted connections that the system will allow before refusing new connections.
- check_for_updatesbool
Defaults to
True
. IfTrue
, will check for newer versions ofhikari
on PyPI and notify if available.- close_loopbool
Defaults to
True
. IfTrue
, then once the bot enters a state where all components have shut down permanently during application shut down, then all asyncgens and background tasks will be destroyed, and the event loop will be shut down.This will wait until all
hikari
-ownedaiohttp
connectors have had time to attempt to shut down correctly (around 250ms), and on Python 3.9 and newer, will also shut down the default event loop executor too.- close_passed_executorbool
Defaults to
False
. IfTrue
, any customconcurrent.futures.Executor
passed to the constructor will be shut down when the application terminates. This does not affect the default executor associated with the event loop, and will not do anything if you do not provide a custom executor to the constructor.- coroutine_tracking_depth
typing.Optional
[int
] Defaults to
None
. If an integer value and supported by the interpreter, then this many nested coroutine calls will be tracked with their call origin state. This allows you to determine where non-awaited coroutines may originate from, but generally you do not want to leave this enabled for performance reasons.- enable_signal_handlers
typing.Optional
[bool] Defaults to
True
if this is started in the main thread.If on a non-Windows OS with builtin support for kernel-level POSIX signals, then setting this to
True
will allow treating keyboard interrupts and other OS signals to safely shut down the application as calls to shut down the application properly rather than just killing the process in a dirty state immediately. You should leave this enabled unless you plan to implement your own signal handling yourself.- host
typing.Optional
[typing.Union
[str
,aiohttp.web.HostSequence
]] TCP/IP host or a sequence of hosts for the HTTP server.
- port
typing.Optional
[int
] TCP/IP port for the HTTP server.
- path
typing.Optional
[str
] File system path for HTTP server unix domain socket.
- reuse_address
typing.Optional
[bool] Tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.
- reuse_port
typing.Optional
[bool] Tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are also bound to.
- socket
typing.Optional
[socket.socket
] A pre-existing socket object to accept connections on.
- shutdown_timeout
float
A delay to wait for graceful server shut down before forcefully disconnecting all open client sockets. This defaults to 60 seconds.
- ssl_context
typing.Optional
[ssl.SSLContext
] SSL context for HTTPS servers.
- async start(backlog=128, check_for_updates=True, host=None, port=None, path=None, reuse_address=None, reuse_port=None, socket=None, shutdown_timeout=60.0, ssl_context=None)[source]#
Start the bot and wait for the internal server to startup then return.
Note
For more information on the other parameters such as defaults see AIOHTTP’s documentation.
- Other Parameters
- backlog
int
The number of unaccepted connections that the system will allow before refusing new connections.
- check_for_updatesbool
Defaults to
True
. IfTrue
, will check for newer versions ofhikari
on PyPI and notify if available.- host
typing.Optional
[typing.Union
[str
,aiohttp.web.HostSequence
]] TCP/IP host or a sequence of hosts for the HTTP server.
- port
typing.Optional
[int
] TCP/IP port for the HTTP server.
- path
typing.Optional
[str
] File system path for HTTP server unix domain socket.
- reuse_address
typing.Optional
[bool] Tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.
- reuse_port
typing.Optional
[bool] Tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are also bound to.
- socket
typing.Optional
[socket.socket
] A pre-existing socket object to accept connections on.
- shutdown_timeout
float
A delay to wait for graceful server shut down before forcefully disconnecting all open client sockets. This defaults to 60 seconds.
- ssl_context
typing.Optional
[ssl.SSLContext
] SSL context for HTTPS servers.
- backlog
- get_listener(interaction_type, /)[source]#
- get_listener(interaction_type: Type[hikari.interactions.component_interactions.ComponentInteraction], /) Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.component_interactions.ComponentInteraction, _ModalOrMessageResponseBuilderT]]
- get_listener(interaction_type: Type[hikari.interactions.command_interactions.AutocompleteInteraction], /) Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.command_interactions.AutocompleteInteraction, hikari.api.special_endpoints.InteractionAutocompleteBuilder]]
- get_listener(interaction_type: Type[hikari.interactions.modal_interactions.ModalInteraction], /) Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.modal_interactions.ModalInteraction, _MessageResponseBuilderT]]
- get_listener(interaction_type: Type[_InteractionT_co], /) Optional[hikari.api.interaction_server.ListenerT[_InteractionT_co, hikari.api.special_endpoints.InteractionResponseBuilder]]
Get the listener registered for an interaction.
- Parameters
- interaction_type
typing.Type
[hikari.interactions.base_interactions.PartialInteraction
] Type of the interaction to get the registered listener for.
- interaction_type
- Returns
typing.Optional
[ListenersT
[hikari.interactions.base_interactions.PartialInteraction
,hikari.api.special_endpoints.InteractionResponseBuilder
]The callback registered for the provided interaction type if found, else
None
.
- set_listener(interaction_type, listener, /, *, replace=False)[source]#
- set_listener(interaction_type: Type[hikari.interactions.component_interactions.ComponentInteraction], listener: Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.component_interactions.ComponentInteraction, _ModalOrMessageResponseBuilderT]], /, *, replace: bool = False) None
- set_listener(interaction_type: Type[hikari.interactions.command_interactions.AutocompleteInteraction], listener: Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.command_interactions.AutocompleteInteraction, hikari.api.special_endpoints.InteractionAutocompleteBuilder]], /, *, replace: bool = False) None
- set_listener(interaction_type: Type[hikari.interactions.modal_interactions.ModalInteraction], listener: Optional[hikari.api.interaction_server.ListenerT[hikari.interactions.modal_interactions.ModalInteraction, _MessageResponseBuilderT]], /, *, replace: bool = False) None
Set the listener callback for this interaction server.
- Parameters
- interaction_type
typing.Type
[hikari.interactions.base_interactions.PartialInteraction
] The type of interaction this listener should be registered for.
- listener
typing.Optional
[ListenerT
[hikari.interactions.base_interactions.PartialInteraction
,hikari.api.special_endpoints.InteractionResponseBuilder
]] The asynchronous listener callback to set or
None
to unset the previous listener.
- interaction_type
- Other Parameters
- replacebool
Whether this call should replace the previously set listener or not. This call will raise a
ValueError
if set toFalse
when a listener is already set.
- Raises