Api Reference

class tsbot.bot.TSBot(username, password, address, port=None, *, protocol='ssh', server_id=1, nickname=None, invoker='!', connection_retries=3, connection_retry_timeout=10, ratelimited=False, ratelimit_calls=10, ratelimit_period=3, query_timeout=5, default_plugins=default_plugins.DEFAULT_PLUGINS)
Parameters:
  • username (str) – Login name of the query account.

  • password (str) – Generated password for the query account.

  • address (str) – Address of the TeamSpeak server.

  • port (int | None) – Port for the connection.

  • protocol (Literal['ssh', 'raw']) – Type of the connection.

  • server_id (int) – Id of the virtual server.

  • nickname (str | None) – Display name for the bot client.

  • invoker (str) – Command indicator.

  • connection_retries (int) – The amount of connection attempts on each connection.

  • connection_retry_timeout (float) – The period between each connection attempt in seconds.

  • ratelimited (bool) – If the connection should be ratelimited.

  • ratelimit_calls (int) – Calls per period.

  • ratelimit_period (float) – Period interval.

  • query_timeout (float) – Timeout for each query command in seconds.

  • default_plugins (Iterable[plugin.TSPlugin]) – Plugins that will be loaded by default.

property uid: str

Bots UID.

property clid: str

Bots current client id.

property cldbid: str

Bots client database id.

property connected: bool

Is the bot currently connected to a server.

emit(event_name, ctx=None)

Creates TSEvent instance and emits it.

This event is passed to the event system and all the handlers registered for the event are called with the given context.

Parameters:
  • event_name (str) – Name of the event being emitted.

  • ctx (Any | None) – Additional context for the event.

Return type:

None

emit_event(event)

Emits an event to be handled.

Given event is passed to the event system and all the handlers registered for the event are called with the given context defined in the event.

Parameters:

event (TSEvent) – Event to be emitted.

Return type:

None

@on(event_type: event_types.BUILTIN_EVENTS) Callable[[events.EventHandler[context.TSCtx]], events.EventHandler[context.TSCtx]]
@on(event_type: event_types.BUILTIN_NO_CTX_EVENTS) Callable[[events.EventHandler[None]], events.EventHandler[None]]
@on(event_type: event_types.TS_EVENTS) Callable[[events.EventHandler[context.TSCtx]], events.EventHandler[context.TSCtx]]
@on(event_type: str) Callable[[events.EventHandler[Any]], events.EventHandler[Any]]

Decorator to register event handlers.

This decorator factory method registers async functions as an event handler.

When an event is emitted with the event_type name, the decorated async function is called with the bot instance and the event context.

Parameters:

event_type – Name of the event.

register_event_handler(event_type: event_types.BUILTIN_EVENTS, handler: events.EventHandler[context.TSCtx]) TSEventHandler
register_event_handler(event_type: event_types.BUILTIN_NO_CTX_EVENTS, handler: events.EventHandler[None]) TSEventHandler
register_event_handler(event_type: event_types.TS_EVENTS, handler: events.EventHandler[context.TSCtx]) TSEventHandler
register_event_handler(event_type: str, handler: events.EventHandler[Any]) TSEventHandler

Register an event handler.

This method registers async functions as an event handler.

When an event is emitted with the event_type name, the decorated async function is called with the bot instance and the event context.

Parameters:
  • event_type – Name of the event.

  • handler – Async function to handle the event.

Returns:

The instance of TSEventHandler created.

@once(event_type: event_types.BUILTIN_EVENTS) Callable[[events.EventHandler[context.TSCtx]], events.EventHandler[context.TSCtx]]
@once(event_type: event_types.BUILTIN_NO_CTX_EVENTS) Callable[[events.EventHandler[None]], events.EventHandler[None]]
@once(event_type: event_types.TS_EVENTS) Callable[[events.EventHandler[context.TSCtx]], events.EventHandler[context.TSCtx]]
@once(event_type: str) Callable[[events.EventHandler[Any]], events.EventHandler[Any]]

Decorator to register once event handlers.

This decorator factory method registers async functions as an event handler.

When an event is emitted with the event_type name, the decorated async function is called with the bot instance and the event context.

The registered event handler will be removed after it is ran once.

Parameters:

event_type – Name of the event.

register_once_handler(event_type: event_types.BUILTIN_EVENTS, handler: events.EventHandler[context.TSCtx]) TSEventOnceHandler
register_once_handler(event_type: event_types.BUILTIN_NO_CTX_EVENTS, handler: events.EventHandler[None]) TSEventOnceHandler
register_once_handler(event_type: event_types.TS_EVENTS, handler: events.EventHandler[context.TSCtx]) TSEventOnceHandler
register_once_handler(event_type: str, handler: events.EventHandler[Any]) TSEventOnceHandler

Register an event handler to be ran once on an event, and remove it afterwards.

This method registers async functions as an event handler. When an event is emitted with the event_type name, the decorated async function is called with the bot instance and the event context.

Parameters:
  • event_type – Name of the event.

  • handler – Async function to handle the event.

Returns:

The instance of TSEventOnceHandler created.

remove_event_handler(event_handler)

Remove an event handler.

This method removes an event handler from the event system.

The event_handler argument is an instance of TSEventHandler returned by the register_event_handler() and register_once_handler() methods.

Parameters:

event_handler (TSEventHandler) – Instance of the TSEventHandler to be removed.

Return type:

None

@command(*command: str, help_text: str = '', raw: Literal[True], hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) Callable[[commands.RawCommandHandler], commands.RawCommandHandler]
@command(*command: str, help_text: str = '', raw: Literal[False] = False, hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) Callable[[commands.CommandHandler], commands.CommandHandler]

Decorator to register command handlers.

This decorator factory method registers async functions as a command handler.

When invoked in a text channel, the decorated async function is called with the bot instance, the textmessage event context and parsed arguments from the message.

Parameters:
  • command – Name(s) of the command.

  • help_text – Text to be displayed when using !help.

  • raw – Skip message parsing and pass the rest of the message as the sole argument.

  • hidden – Hide this command from !help.

  • checks – List of async functions to be called before the command is executed.

register_command(command: str | tuple[str, ...], handler: commands.RawCommandHandler, *, help_text: str = '', raw: Literal[True], hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) TSCommand
register_command(command: str | tuple[str, ...], handler: commands.CommandHandler, *, help_text: str = '', raw: Literal[False] = False, hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) TSCommand

Register a command.

This method registers async functions as a command handler.

When invoked in a text channel, the decorated async function is called with the bot instance, the textmessage event context and parsed arguments from the message.

Parameters:
  • command – Name(s) of the command.

  • handler – Async function to be called when invoked.

  • help_text – Text to be displayed when using !help.

  • raw – Skip message parsing and pass the rest of the message as the sole argument.

  • hidden – Hide this command from !help.

  • checks – List of async functions to be called before the command is executed.

Returns:

The instance of TSCommand created.

remove_command(command)

Remove a command handler.

This method removes a command handler from the command system.

The command argument is an instance of TSCommand returned by the register_command() and get_command_handler() methods.

Parameters:

command (TSCommand) – Instance of the TSCommand to be removed.

Return type:

None

get_command_handler(command)

Get TSCommand instance associated with a given command.

Parameters:

command (str) – Command that invokes TSCommand

Returns:

TSCommand associated with command if found.

Return type:

TSCommand | None

register_task(handler, *args, name=None)

Register a background task.

This method registers an async functions as a background task.

Tasks are started as soon as the bots run() method is called. If the bot is already running, the task is started immediately.

The handler is called with the bot instance and optional arguments, and wrapped with asyncio.create_task().

Once the handler returns or raises an exception, the task is removed from the task system.

Parameters:
  • handler (tasks.TaskHandler[Unpack[_Ts]]) – Async function to be called when the task is started.

  • args (Unpack[_Ts]) – Optional arguments to be passed to the handler.

  • name (str | None) – Name of the task.

Returns:

Instance of TSTask created.

Return type:

tasks.TSTask

register_every_task(seconds, handler, *args, name=None, immediate=False)

Register a background task.

This method works similar to register_task(), but the handler is called every seconds seconds.

Tasks are started as soon as the bots run() method is called. If the bot is already running, the task is started immediately.

The handler is called with the bot instance and optional arguments,

If the handler raises an exception or the task is cancelled, the task is removed from the task system.

Parameters:
  • seconds (float) – How often the task is executed.

  • handler (tasks.TaskHandler[Unpack[_Ts]]) – Async function to be called when the task is executed.

  • args (Unpack[_Ts]) – Optional arguments to be passed to the handler.

  • name (str | None) – Name of the task.

  • immediate (bool) – If the task handler should be executed immediately.

Returns:

Instance of TSTask created.

Return type:

tasks.TSTask

remove_task(task)

Remove a background task.

This method removes a background task from the task system. If the task is still running, it is cancelled.

Parameters:

task (TSTask) – Instance of the TSTask to be removed.

Return type:

None

async send(query)

Send a query to the server.

This method sends a query to the server and returns the response.

If the server responds with an error, a TSResponseError is raised.

Parameters:

query (TSQuery) – Instance of TSQuery to be send to the server.

Returns:

Response from the server as a TSResponse instance.

Return type:

TSResponse

async send_raw(raw_query)

Send raw commands to the server.

this method sends a raw query to the server and returns the response.

If the server responds with an error, a TSResponseError is raised.

Parameters:

raw_query (str) – Raw query command to be send to the server.

Returns:

Response from the server as a TSResponse instance.

Return type:

TSResponse

async send_batched(queries)

Send multiple queries to the server.

This method sends multiple queries to the server without waiting for the response.

If the server responds with an error, it is ignored.

Parameters:

queries (Iterable[TSQuery]) – Iterable of TSQuery instances to be send to the server.

Return type:

None

async send_batched_raw(raw_queries)

Send multiple raw queries to the server.

This method sends multiple raw queries to the server without waiting for the response.

If the server responds with an error, it is ignored.

Parameters:

raw_queries (Iterable[str]) – Iterable of raw query commands to be send to the server.

Return type:

None

close()

Close the bot.

This method closes the bot gracefully.

  • The bot will emit close event to notify that it is closing.

  • The bot will cancel all the background tasks and wait until they are finished.

  • The bot will handle all the events still in the queue.

  • If the connection is still open, the bot will send a quit command.

Return type:

None

async run()

Run the bot.

This method starts the bot.

  • Connects the bot to the server.

  • Schedules background tasks.

  • Registers the server to send events to the bot.

Awaits until the bot is closed or the connection is lost.

Return type:

None

load_plugin(*plugins)

Loads TSPlugin instances into the bot.

This method loads all the event handlers and commands defined with the following decorators:

Once the plugin is loaded, the on_load() callback is called. You can override this method in your plugin to do side effects when the plugin is loaded by the bot.

Parameters:

plugins (TSPlugin) – Instances of TSPlugin to be loaded.

Return type:

None

unload_plugin(*plugins)

Unloads TSPlugin instances from the bot.

This method unloads all the event handlers and commands defined with the following decorators:

Once the plugin is unloaded, the on_unload() callback is called. You can override this method in your plugin to clean up side effects when the plugin is unloaded.

Parameters:

plugins (TSPlugin) – Instances of TSPlugin to be unloaded.

Return type:

None

async respond(ctx, message)

Sends a message to the same text channel where the ctx was created.

This method can be used to respond to command invocations. The context has to be from a textmessage event (eg. command invocation).

@bot.command("hello")
async def greet(bot: TSBot, ctx: TSCtx):
    await bot.respond(ctx, f"Hello, {ctx['invokername']}!")
Parameters:
  • ctx (TSCtx) – Context of the textmessage event.

  • message (str) – Message to be sent.

Return type:

None

async respond_to_client(ctx, message)

Sends a message to the client that invoked the message.

The message will be sent to the client with a direct message.

This method can be used to respond to command invocations. The context has to be from a textmessage event (eg. command invocation).

@bot.command("hello")
async def greet(bot: TSBot, ctx: TSCtx):
    await bot.respond_to_client(ctx, f"Hello, {ctx['invokername']}!")
Parameters:
  • ctx (TSCtx) – Context of the textmessage event.

  • message (str) – Message to be sent.

Return type:

None


Handlers

type tsbot.events.EventHandler[_TC] = Callable[[bot.TSBot, _TC], Coroutine[None, None, None]]

A handler signature for event handlers.

async def event_handler(bot: TSBot, ctx: TSCtx) -> None: ...
type tsbot.commands.CommandHandler = Callable[[Concatenate[bot.TSBot, context.TSCtx, ...]], Coroutine[None, None, None]]

A handler signature for command handlers.

async def command_handler(bot: TSBot, ctx: TSCtx, arg1: str, arg2: str) -> None: ...
type tsbot.commands.RawCommandHandler = Callable[[bot.TSBot, context.TSCtx, str], Coroutine[None, None, None]]

A handler signature for raw command handlers.

async def raw_command_handler(bot: TSBot, ctx: TSCtx, msg: str) -> None: ...
type tsbot.tasks.TaskHandler[*_Ts] = Callable[[bot.TSBot, Unpack[_Ts]], Coroutine[None, None, None]]

A handler signature for task handlers.

async def task_handler(bot: TSBot) -> None: ...

Context

class tsbot.context.TSCtx(ctx)

Thin wrapper around Pythons dictionary.

Parameters:

ctx (collections.abc.Mapping[str, str])

Return type:

collections.abc.Mapping[str, str]


Query Builder

tsbot.query_builder.query

alias of TSQuery

class tsbot.query_builder.TSQuery(command, options=None, parameters=None, parameter_blocks=None)

Class to represent query commands to the TeamSpeak server.

Parameters:
  • command (commands.Commands) – Base query command.

  • options (tuple[Stringable, ...] | None) – Options attached to the query.

  • parameters (dict[str, Stringable] | None) – Parameters attached to the query.

  • parameter_blocks (tuple[dict[str, Stringable], ...] | None) – Parameter blocks attached to the query.

option(*args)

Add options to the command eg. -groups.

Parameters:

args (Stringable) – Tuple of options to be attached.

Returns:

New tsbot.query_builder.TSQuery instance with added params

Return type:

Self

params(**kwargs)

Add parameters to the command eg. cldbid=12.

Parameters:

kwargs (Stringable) – Keyword to be attached.

Returns:

New tsbot.query_builder.TSQuery instance with added parameters

Return type:

Self

param_block(blocks=None, /, **kwargs)

Add parameter blocks eg. clid=1 | clid=2 | clid=3 to the command.

Takes in either an iterable of parameters in form of dict[str, Stringable] or one block at a time.

Parameters:
  • blocks (Iterable[Mapping[str, Stringable]] | None) – Iterable of parameter blocks to be attached.

  • kwargs (Stringable) – Parameters to be attached to single block.

Returns:

New tsbot.query_builder.TSQuery instance with added parameter blocks

Return type:

Self

compile()

Compiles the query into a raw command.

Returns:

The compiled query command.

Return type:

str


Responses

class tsbot.response.TSResponse(data, error_id, msg)

Class to represent the response to a query from a Teamspeak server.

Parameters:
data: tuple[dict[str, str], ...]

The response data.

error_id: int

Id of the error if any.

msg: str

Message of the error if any.

__getitem__(key)

Get the value of a key from the first response dict.

Parameters:

key (str)

Return type:

str

property first: dict[str, str]

The first dict from the response data.

property last: dict[str, str]

The last dict from the response data.

get(key: str, /) str | None
get(key: str, default: str, /) str

Get the value of a key from the first response dict.


Plugins

class tsbot.plugin.TSPlugin(*args, **kwargs)

Base class for plugins.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

Self

on_load(bot)

Callback called when the plugin is loaded to the bot.

This method can be overridden and used to do side effects when the plugin is loaded. For example, registering event handlers, commands, etc.

Parameters:

bot (bot.TSBot) – Instance of TSBot that loaded the plugin.

Return type:

None

on_unload(bot)

Callback called when the plugin is unloaded from the bot.

This method can be overridden and used to clean up side effects when the plugin is unloaded. For example, removing event handlers, commands, etc.

Parameters:

bot (bot.TSBot) – Instance of TSBot that unloaded the plugin.

Return type:

None

Handlers

type tsbot.plugin.PluginCommandHandler[_TP: TSPlugin] = Callable[[Concatenate[_TP, bot.TSBot, context.TSCtx, ...]], Coroutine[None, None, None]]

A handler signature for plugin command handlers.

async def plugin_command_handler(self, bot: TSBot, ctx: TSCtx, arg1: str) -> None: ...
type tsbot.plugin.PluginRawCommandHandler[_TP: TSPlugin] = Callable[[_TP, bot.TSBot, context.TSCtx, str], Coroutine[None, None, None]]

A handler signature for plugin raw command handlers.

async def plugin_raw_command_handler(self, bot: TSBot, ctx: TSCtx, msg: str) -> None: ...
type tsbot.plugin.PluginEventHandler[_TP: TSPlugin, _TC] = Callable[[_TP, bot.TSBot, _TC], Coroutine[None, None, None]]

A handler signature for plugin event handlers.

async def plugin_event_handler(self, bot: TSBot, ctx: TSCtx) -> None: ...

Decorators

@tsbot.plugin.command(*command: str, help_text: str = '', raw: Literal[True], hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) Callable[[PluginRawCommandHandler[_TP]], PluginRawCommandHandler[_TP]]
@tsbot.plugin.command(*command: str, help_text: str = '', raw: Literal[False] = False, hidden: bool = False, checks: Sequence[commands.CommandHandler] = ()) Callable[[PluginCommandHandler[_TP]], PluginCommandHandler[_TP]]

Decorator to register plugin commands.

Parameters:
  • command – Name(s) of the command.

  • help_text – Text to be displayed when using !help.

  • raw – Skip message parsing and pass the rest of the message as the sole argument.

  • hidden – Hide this command from !help.

  • checks – List of async functions to be called before the command is executed.

@tsbot.plugin.on(event_type: event_types.BUILTIN_EVENTS) Callable[[PluginEventHandler[_TP, context.TSCtx]], PluginEventHandler[_TP, context.TSCtx]]
@tsbot.plugin.on(event_type: event_types.BUILTIN_NO_CTX_EVENTS) Callable[[PluginEventHandler[_TP, None]], PluginEventHandler[_TP, None]]
@tsbot.plugin.on(event_type: event_types.TS_EVENTS) Callable[[PluginEventHandler[_TP, context.TSCtx]], PluginEventHandler[_TP, context.TSCtx]]
@tsbot.plugin.on(event_type: str) Callable[[PluginEventHandler[_TP, Any]], PluginEventHandler[_TP, Any]]

Decorator to register plugin events.

Parameters:

event_type – Name of the event.

@tsbot.plugin.once(event_type: event_types.BUILTIN_EVENTS) Callable[[PluginEventHandler[_TP, context.TSCtx]], PluginEventHandler[_TP, context.TSCtx]]
@tsbot.plugin.once(event_type: event_types.BUILTIN_NO_CTX_EVENTS) Callable[[PluginEventHandler[_TP, None]], PluginEventHandler[_TP, None]]
@tsbot.plugin.once(event_type: event_types.TS_EVENTS) Callable[[PluginEventHandler[_TP, context.TSCtx]], PluginEventHandler[_TP, context.TSCtx]]
@tsbot.plugin.once(event_type: str) Callable[[PluginEventHandler[_TP, Any]], PluginEventHandler[_TP, Any]]

Decorator to register plugin events to be ran only once.

Parameters:

event_type – Name of the event.


Tasks

class tsbot.tasks.TSTask(handler: 'TaskHandler[Unpack[tuple[Any, ...]]]', args: 'tuple[Any, ...]' = (), name: 'str | None' = None, task: 'asyncio.Task[None] | None' = None)
Parameters:
cancel()

Cancel the the underlying task.

Return type:

None


Exceptions

exception tsbot.exceptions.TSException

Bases: Exception

Exception related to TSBot.

exception tsbot.exceptions.TSResponseError(msg, error_id)

Bases: TSException

Raised when a response from server has error_id set to other than 0.

Parameters:
Return type:

None

exception tsbot.exceptions.TSResponsePermissionError(msg, error_id, perm_id)

Bases: TSResponseError

Raised when a response has error_id of ‘2568’, indicating that the client doesn’t have the proper permissions to execute this query.

Parameters:
Return type:

None

exception tsbot.exceptions.TSCommandError

Bases: TSException

Command handlers can raise this exception to indicate that something went wrong while running the handler.

exception tsbot.exceptions.TSPermissionError

Bases: TSException

Command handlers can raise this exception to indicate that the user running this command doesn’t have the proper permissions.

exception tsbot.exceptions.TSInvalidParameterError

Bases: TSException, TypeError

Raised when a call to a command handler doesn’t match the signature of the handler.