Events

TSBot handles all kinds of events for you.
Bot emits built-in events and notifications from the TeamSpeak server.
You can attach handlers for any kind of event and react to them as you wish.

Event handlers

You can register event handlers to fire on given event.

On given event, all the event handlers registered to that event name are called with arguments handler(bot, ctx) where:

Arg

Explanation

bot

Instance of TSBot calling the handler.

ctx

Additional context of the event

@bot.on("cliententerview")
async def handle_client_enter(bot: TSBot, ctx: TSCtx):
    print("Client joined the server")
    # ...

You can also register once handler.
These handlers are only fired once when the given event happens.

from tsbot import query

lobby_id: str = "0"

@bot.once("connect")
async def find_lobby_id(bot: TSBot, ctx: None):
    # The bot is ready and connected to the server.
    # Find the channel id of the 'Lobby' channel.
    global lobby_id

    for channel in await bot.send_raw("channellist"):
        if "Lobby" in channel["channel_name"]:
            lobby_id = channel["cid"]
            break

Built-in events

TSBot has handful of useful built-in events. These are fired when the bot does something internally.

Event name

Called when:

Context type

run

The bot is starting up.

None

connect

The bot has connected to the server.

None

disconnect

The bot has lost the connection to the server.

None

reconnect

The bot has regained a connection to the server

None

close

The bot is shutting down.

None

send

The bot is sending a query to the server.

TSCtx

command_error

Handler raises TSCommandError exception.

TSCtx

permission_error

Handler raises TSPermissionError exception.

TSCtx

parameter_error

Handler raises TSInvalidParameterError exception.

TSCtx


Events from the server

TSBot automatically registers itself as a receiver of server notification.
These notifications are structured as {notify}{event}.
notify is omitted from the event and the event is passed as the event into the event system.


Custom events

Since event names are arbitrary str, the event system can handle custom events.
You can emit your own events with bot.emit() method.
bot.emit() accepts the event name as its first argument and arbitrary context type as the second argument.

This can be useful when passing events from one plugin to another.

score: defaultdict[str, int] = defaultdict(int)


@bot.on("increment_score")
async def increment_user_score(bot: TSBot, uid: str):
    score[uid] += 1


@bot.on("cliententerview")
async def handle_client_enter(bot: TSBot, ctx: TSCtx):
    bot.emit("increment_score", ctx["client_unique_identifier"])