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:
tokentyping.Union[str, hikari.api.rest.TokenStrategy]

The bot or bearer token.

token_typetyping.Union[str, hikari.applications.TokenType, None]

The type of token in use. This should only be passed when str is passed for token, can be "Bot" or "Bearer".

This should be left as None when hikari.api.rest.TokenStrategy is passed for 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.

bannertyping.Optional[str]

The package to search for a banner.txt in. Defaults to "hikari" for the "hikari/banner.txt" banner. Setting this to None will disable the banner being shown.

executortyping.Optional[concurrent.futures.Executor]

Defaults to None. If non-None, then this executor is used instead of the concurrent.futures.ThreadPoolExecutor attached to the asyncio.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 with concurrent.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. If True, 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_settingstyping.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.

logstyping.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 to colorlog.basicConfig (a facade for logging.basicConfig with additional conduit for enabling coloured logging levels) with the level kwarg matching this value.

If a typing.Dict[str, typing.Any] equivalent, then this value is passed to logging.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 the Example section.

Note that "TRACE_HIKARI" is a library-specific logging level which is expected to be more verbose than "DEBUG".

max_rate_limitfloat

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_retriestyping.Optional[int]

Maximum number of times a request will be retried if it fails with a 5xx status. Defaults to 3 if set to None.

proxy_settingstyping.Optional[hikari.impl.config.ProxySettings]

Custom proxy settings to use with network-layer logic in your application to get through an HTTP-proxy.

public_keytyping.Union[str, bytes, None]

The public key to use to verify received interaction requests. This may be a hex encoded str or the raw bytes. If left as None then the client will try to work this value out based on token.

rest_urltyping.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:
ValueError
  • If token_type is provided when a token strategy is passed for token.

  • if token_type is left as None when a string is passed for token.

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_typetyping.Type[hikari.interactions.base_interactions.PartialInteraction]

Type of the interaction to get the registered listener for.

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.

async on_interaction(body, signature, timestamp)[source]#

Handle an interaction received from Discord as a REST server.

Parameters:
bodybytes

The interaction payload.

signaturebytes

Value of the "X-Signature-Ed25519" header used to verify the body.

timestampbytes

Value of the "X-Signature-Timestamp" header used to verify the body.

Returns:
Response

Instructions on how the REST server calling this should respond to the interaction request.

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:
bannertyping.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_argstyping.Optional[typing.Dict[str, str]]

If provided, extra $-substitutions to use when printing the banner. Default substitutions can not be overwritten.

Raises:
ValueError

If extra_args contains a default $-substitution.

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. If True, then debugging is enabled for the asyncio event loop in use.

backlogint

The number of unaccepted connections that the system will allow before refusing new connections.

check_for_updatesbool

Defaults to True. If True, will check for newer versions of hikari on PyPI and notify if available.

close_loopbool

Defaults to True. If True, 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-owned aiohttp 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. If True, any custom concurrent.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_depthtyping.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_handlerstyping.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.

hosttyping.Optional[typing.Union[str, aiohttp.web.HostSequence]]

TCP/IP host or a sequence of hosts for the HTTP server.

porttyping.Optional[int]

TCP/IP port for the HTTP server.

pathtyping.Optional[str]

File system path for HTTP server unix domain socket.

reuse_addresstyping.Optional[bool]

Tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

reuse_porttyping.Optional[bool]

Tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are also bound to.

sockettyping.Optional[socket.socket]

A pre-existing socket object to accept connections on.

shutdown_timeoutfloat

A delay to wait for graceful server shut down before forcefully disconnecting all open client sockets. This defaults to 60 seconds.

ssl_contexttyping.Optional[ssl.SSLContext]

SSL context for HTTPS servers.

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_typetyping.Type[hikari.interactions.base_interactions.PartialInteraction]

The type of interaction this listener should be registered for.

listenertyping.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.

An asynchronous listener can be either a normal coroutine or an async generator which should yield exactly once. This allows sending an initial response to the request, while still later executing further logic.

Other Parameters:
replacebool

Whether this call should replace the previously set listener or not. This call will raise a ValueError if set to False when a listener is already set.

Raises:
TypeError

If replace is False when a listener is already set.

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:
backlogint

The number of unaccepted connections that the system will allow before refusing new connections.

check_for_updatesbool

Defaults to True. If True, will check for newer versions of hikari on PyPI and notify if available.

hosttyping.Optional[typing.Union[str, aiohttp.web.HostSequence]]

TCP/IP host or a sequence of hosts for the HTTP server.

porttyping.Optional[int]

TCP/IP port for the HTTP server.

pathtyping.Optional[str]

File system path for HTTP server unix domain socket.

reuse_addresstyping.Optional[bool]

Tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

reuse_porttyping.Optional[bool]

Tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are also bound to.

sockettyping.Optional[socket.socket]

A pre-existing socket object to accept connections on.

shutdown_timeoutfloat

A delay to wait for graceful server shut down before forcefully disconnecting all open client sockets. This defaults to 60 seconds.

ssl_contexttyping.Optional[ssl.SSLContext]

SSL context for HTTPS servers.