Skip to content

hikari.impl.rest_bot#

Standard implementations of a Interaction based REST-only bot.

RESTBot #

RESTBot(token: Union[str, TokenStrategy], token_type: Union[TokenType, str, None] = None, public_key: Union[bytes, str, None] = None, *, allow_color: bool = True, banner: Optional[str] = 'hikari', suppress_optimization_warning: bool = False, executor: Optional[Executor] = None, force_color: bool = False, http_settings: Optional[HTTPSettings] = None, logs: Union[None, str, int, dict[str, Any], PathLike[str]] = 'INFO', max_rate_limit: float = 300.0, max_retries: int = 3, proxy_settings: Optional[ProxySettings] = None, rest_url: Optional[str] = None)

Bases: RESTBotAware, InteractionServer

Basic implementation of an interaction based REST-only bot.

PARAMETER DESCRIPTION
token

The bot or bearer token.

TYPE: Union[str, TokenStrategy]

token_type

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

This should be left as None when hikari.api.rest.TokenStrategy is passed for token.

TYPE: Union[TokenType, str, None] DEFAULT: None

allow_color

Whether to 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.

TYPE: bool DEFAULT: True

banner

The package to search for a banner.txt in.

Setting this to None will disable the banner being shown.

TYPE: Optional[str] DEFAULT: 'hikari'

suppress_optimization_warning

By default, Hikari warns you if you are not running your bot using optimizations (-O or -OO). If this is True, you won't receive these warnings, even if you are not running using optimizations.

TYPE: bool DEFAULT: False

executor

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.

TYPE: Optional[Executor] DEFAULT: None

force_color

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.

TYPE: bool DEFAULT: False

http_settings

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.

TYPE: Optional[HTTPSettings] DEFAULT: None

logs

The flavour to set the logging to.

This can be None to not enable logging automatically.

If you pass a str or a int, it is interpreted as the global logging level to use, and should match one of "DEBUG", "INFO", "WARNING", "ERROR" or "CRITICAL". The configuration will be set up to use a colorlog coloured logger, and to use a sane logging format strategy. The output will be written to sys.stdout using this configuration.

If you pass a dict, it is treated as the mapping to pass to logging.config.dictConfig. If the dict defines any handlers, default handlers will not be setup if incremental is not specified.

If you pass a str to an existing file or a os.PathLike, it is interpreted as the file to load config from using logging.config.fileConfig.

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

TYPE: Union[None, str, int, dict[str, Any], PathLike[str]] DEFAULT: 'INFO'

max_rate_limit

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.

TYPE: float DEFAULT: 300.0

max_retries

Maximum number of times a request will be retried if it fails with a 5xx status.

Defaults to 3 if set to None.

TYPE: int DEFAULT: 3

proxy_settings

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

TYPE: Optional[ProxySettings] DEFAULT: None

public_key

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.

TYPE: Union[bytes, str, None] DEFAULT: None

rest_url

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.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION
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.

Examples:

Simple logging setup:

hikari.RESTBot("TOKEN", logs="INFO")  # Registered logging level
# or
hikari.RESTBot("TOKEN", logs=20)  # Logging level as an int

File config:

# See https://docs.python.org/3/library/logging.config.html#configuration-file-format for more info
hikari.RESTBot("TOKEN", logs="path/to/file.ini")

Setting up logging through a dict config:

# See https://docs.python.org/3/library/logging.config.html#dictionary-schema-details for more info
hikari.RESTBot(
    "TOKEN",
    logs={
        "version": 1,
        "incremental": True,  # In incremental setups, the default stream handler will be setup
        "loggers": {
            "hikari.gateway": {"level": "DEBUG"},
            "hikari.ratelimits": {"level": "TRACE_HIKARI"},
        },
    },
)

entity_factory property #

entity_factory: EntityFactory

Entity factory implementation for this object.

executor property #

executor: Optional[Executor]

Executor to use for blocking operations.

This may return None if the default asyncio thread pool should be used instead.

http_settings property #

http_settings: HTTPSettings

HTTP settings in use by this component.

interaction_server property #

interaction_server: InteractionServer

Interaction server this app is bound to.

is_alive property #

is_alive: bool

Whether the application is running or not.

This is useful as some functions might raise hikari.errors.ComponentStateConflictError if this is False.

on_shutdown property #

on_shutdown: Sequence[Callable[[RESTBot], Coroutine[Any, Any, None]]]

Sequence of the bot's asynchronous shutdown callbacks.

on_startup property #

on_startup: Sequence[Callable[[RESTBot], Coroutine[Any, Any, None]]]

Sequence of the bot's asynchronous startup callbacks.

proxy_settings property #

proxy_settings: ProxySettings

Proxy settings in use by this component.

rest property #

rest: RESTClient

REST client to use for HTTP requests.

add_shutdown_callback #

add_shutdown_callback(callback: Callable[[RESTBot], Coroutine[Any, Any, None]]) -> None

Add an asynchronous callback to be called when the bot shuts down.

PARAMETER DESCRIPTION
callback

The asynchronous shutdown callback to add.

TYPE: Callable[[RESTBotAware], Coroutine[Any, Any, None]]

add_startup_callback #

add_startup_callback(callback: Callable[[RESTBot], Coroutine[Any, Any, None]]) -> None

Add an asynchronous callback to be called when the bot starts up.

PARAMETER DESCRIPTION
callback

The asynchronous startup callback to add.

TYPE: Callable[[RESTBotAware], Coroutine[Any, Any, None]]

close async #

close() -> None

Kill the application by shutting all components down.

get_listener #

get_listener(interaction_type: type[_InteractionT_co]) -> Optional[ListenerT[_InteractionT_co, InteractionResponseBuilder]]

Get the listener registered for an interaction.

PARAMETER DESCRIPTION
interaction_type

Type of the interaction to get the registered listener for.

TYPE: type[_InteractionT_co]

RETURNS DESCRIPTION
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.

join async #

join() -> None

Wait indefinitely until the application closes.

This can be placed in a task and cancelled without affecting the application runtime itself. Any exceptions raised by shards will be propagated to here.

on_interaction async #

on_interaction(body: bytes, signature: bytes, timestamp: bytes) -> Response

Handle an interaction received from Discord as a REST server.

PARAMETER DESCRIPTION
body

The interaction payload.

TYPE: bytes

signature

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

TYPE: bytes

timestamp

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

TYPE: bytes

RETURNS DESCRIPTION
Response

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

print_banner staticmethod #

print_banner(banner: Optional[str], allow_color: bool, force_color: bool, extra_args: Optional[dict[str, str]] = None) -> None

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.

PARAMETER DESCRIPTION
banner

The package to find a banner.txt in.

TYPE: Optional[str]

allow_color

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.

TYPE: bool

force_color

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.

TYPE: bool

extra_args

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

TYPE: Optional[dict[str, str]] DEFAULT: None

RAISES DESCRIPTION
ValueError

If extra_args contains a default $-substitution.

remove_shutdown_callback #

remove_shutdown_callback(callback: Callable[[RESTBot], Coroutine[Any, Any, None]]) -> None

Remove an asynchronous shutdown callback from the bot.

PARAMETER DESCRIPTION
callback

The shutdown callback to remove.

TYPE: Callable[[RESTBotAware], Coroutine[Any, Any, None]]

RAISES DESCRIPTION
ValueError

If the callback was not registered.

remove_startup_callback #

remove_startup_callback(callback: Callable[[RESTBot], Coroutine[Any, Any, None]]) -> None

Remove an asynchronous startup callback from the bot.

PARAMETER DESCRIPTION
callback

The asynchronous startup callback to remove.

TYPE: Callable[[RESTBotAware], Coroutine[Any, Any, None]]

RAISES DESCRIPTION
ValueError

If the callback was not registered.

run #

run(asyncio_debug: bool = False, backlog: int = 128, check_for_updates: bool = True, close_loop: bool = True, close_passed_executor: bool = False, coroutine_tracking_depth: Optional[int] = None, enable_signal_handlers: Optional[bool] = None, host: Optional[Union[str, Sequence[str]]] = None, path: Optional[str] = None, port: Optional[int] = None, propagate_interrupts: bool = False, reuse_address: Optional[bool] = None, reuse_port: Optional[bool] = None, shutdown_timeout: float = 60.0, socket: Optional[socket] = None, ssl_context: Optional[SSLContext] = None) -> None

Open this REST server and block until it closes.

PARAMETER DESCRIPTION
asyncio_debug

If True, then debugging is enabled for the asyncio event loop in use.

TYPE: bool DEFAULT: False

backlog

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

TYPE: int DEFAULT: 128

check_for_updates

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

TYPE: bool DEFAULT: True

close_loop

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.

TYPE: bool DEFAULT: True

close_passed_executor

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.

TYPE: bool DEFAULT: False

coroutine_tracking_depth

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.

TYPE: Optional[int] DEFAULT: None

enable_signal_handlers

Defaults to True if this is called 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.

TYPE: Optional[bool] DEFAULT: None

host

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

TYPE: Optional[Union[str, Sequence[str]]] DEFAULT: None

port

TCP/IP port for the HTTP server.

TYPE: Optional[int] DEFAULT: None

path

File system path for HTTP server unix domain socket.

TYPE: Optional[str] DEFAULT: None

reuse_address

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

TYPE: Optional[bool] DEFAULT: None

reuse_port

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

TYPE: Optional[bool] DEFAULT: None

socket

A pre-existing socket object to accept connections on.

TYPE: Optional[socket] DEFAULT: None

shutdown_timeout

A delay, in seconds, to wait for graceful server shut down before forcefully disconnecting all open client sockets.

TYPE: float DEFAULT: 60.0

ssl_context

SSL context for HTTPS servers.

TYPE: Optional[SSLContext] DEFAULT: None

set_listener #

set_listener(interaction_type: type[_InteractionT_co], listener: Optional[ListenerT[_InteractionT_co, InteractionResponseBuilder]], /, *, replace: bool = False) -> None

Set the listener callback for this interaction server.

PARAMETER DESCRIPTION
interaction_type

The type of interaction this listener should be registered for.

TYPE: type[_InteractionT_co]

listener

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.

TYPE: Optional[ListenerT[_InteractionT_co, InteractionResponseBuilder]]

replace

Whether this call should replace the previously set listener or not.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
TypeError

If replace is False when a listener is already set.

start async #

start(backlog: int = 128, check_for_updates: bool = True, host: Optional[Union[str, Sequence[str]]] = None, port: Optional[int] = None, path: Optional[str] = None, reuse_address: Optional[bool] = None, reuse_port: Optional[bool] = None, socket: Optional[socket] = None, shutdown_timeout: float = 60.0, ssl_context: Optional[SSLContext] = None) -> None

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.

PARAMETER DESCRIPTION
backlog

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

TYPE: int DEFAULT: 128

check_for_updates

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

TYPE: bool DEFAULT: True

host

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

TYPE: Optional[Union[str, Sequence[str]]] DEFAULT: None

port

TCP/IP port for the HTTP server.

TYPE: Optional[int] DEFAULT: None

path

File system path for HTTP server unix domain socket.

TYPE: Optional[str] DEFAULT: None

reuse_address

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

TYPE: Optional[bool] DEFAULT: None

reuse_port

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

TYPE: Optional[bool] DEFAULT: None

socket

A pre-existing socket object to accept connections on.

TYPE: Optional[socket] DEFAULT: None

shutdown_timeout

A delay, in seconds, to wait for graceful server shut down before forcefully disconnecting all open client sockets.

TYPE: float DEFAULT: 60.0

ssl_context

SSL context for HTTPS servers.

TYPE: Optional[SSLContext] DEFAULT: None