Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ts3-nodejs-library

Multivit4min2.1kMIT3.5.1TypeScript support: included

TeamSpeak Server Query API

teamspeak, teamspeak3, ts, ts3, query, serverquery

readme

TS3-NodeJS-Library

Build Status npm Coverage Status Discord

The TS3 NodeJS Library has been strongly influenced by PlanetTeamSpeaks TS3 PHP Framework

Introduction

This library can connect to a TeamSpeak Server Query interface, send and receive commands aswell as upload and download files via Filetransfer!

With vscode you will receive powerful autocomplete of functions and their return values, so vscode is highly recommended!

Install

npm install --save ts3-nodejs-library

Documentation

You can find all necessary documentation here!

Example

Send a message to all non Query Clients connected:

//import with typescript
import { TeamSpeak, QueryProtocol } from "ts3-nodejs-library"
//import with javascript
//const { TeamSpeak } = require("ts3-nodejs-library")

//create a new connection
TeamSpeak.connect({
  host: "localhost",
  protocol: QueryProtocol.RAW, //optional
  queryport: 10011, //optional
  serverport: 9987,
  username: "serveradmin",
  password: "",
  nickname: "NodeJS Query Framework"
}).then(async teamspeak => {
  const clients = await teamspeak.clientList({ clientType: 0 })
  clients.forEach(client => {
    console.log("Sending 'Hello!' Message to", client.nickname)
    client.message("Hello!")
  })
}).catch(e => {
  console.log("Catched an error!")
  console.error(e)
})

Quickstart

Connecting to a TeamSpeak Server

There are 2 ways to connect with the TeamSpeak Server: using the wrapper TeamSpeak.connect() or by instanciating the TeamSpeak class by yourself

to connect with TeamSpeak.connect():

import { TeamSpeak } from "ts3-nodejs-library"

TeamSpeak.connect({
  host: "127.0.0.1",
  queryport: 10011
}).then(teamspeak => {
  //you are now connected
}).catch(e => {
  //an error occured during connecting
})

when instanciating it by yourself:

import { TeamSpeak } from "ts3-nodejs-library"

const teamspeak = new TeamSpeak({
  host: "127.0.0.1",
  queryport: 10011
})

teamspeak.on("ready", () => {
  //teamspeak connected successfully
})

teamspeak.on("error", () => {
  //teamspeak had an error
})

Configuration

Parameter Default Description
host "127.0.0.1" hostname to connect to
queryport 10011 queryport to connect to
protocol "raw" either use telnet or ssh to connect to the server
serverport empty the server port to select when connecting
username empty the username to login with (required when using ssh)
password empty the password to login with (required when using ssh)
nickname empty the nickname to connect with when selecting a server
readyTimeout 10000 timeout in ms to wait for the connection to be built
keepAlive true wether a keepalive should be sent to the teamspeak server
localAddress empty local address the socket should connect from

Error handling when connecting

the method TeamSpeak.connect() will do error handling for you, when the query fails to connect or some of the commands which are being initially used to connect may encounter an error then the query will disconnect and reject the Promise with an error

However when instanciating TeamSpeak by yourself an error event might get thrown but the ready event will never fire

thats why TeamSpeak.connect() is more preferable to build a connection

Basic Usage

Sending a command

Sending a command is simple, every command will return a Promise. If you do not know what a Promise is then please read the documentation first: developer.mozilla.org > Promise

When using NodeJS then Promises are essential for further progress

Using Promises

teamspeak.whoami().then(whoami => {
  console.log(whoami)
})

Using Async/Await

(async () => {
  const whoami = await teamspeak.whoami()
  console.log(whoami)
})()

whoami will then give you an object like

{
  virtualserver_status: "online",
  virtualserver_unique_identifier: "t1lytXTeyvmHXvNJ4ZcBBd15ugs=",
  virtualserver_port: 9987,
  virtualserver_id: 1,
  client_id: 2,
  client_channel_id: 1,
  client_nickname: "serveradmin",
  client_database_id: 0,
  client_login_name: "serveradmin",
  client_unique_identifier: "serveradmin",
  client_origin_server_id: 0
}

Events

You can use teamspeak.on() to register to various events, you can find a list of all events here: https://multivit4min.github.io/TS3-NodeJS-Library/classes/teamspeak.html#on Note: with 3.x its not necessary to subscribe to events anymore, this will be done automatically now!

teamspeak.on("textmessage", ev => {
  console.log(`${ev.invoker.nickname} just send the message "${ev.msg}"`)
})

Flood Protection

Flooding will be handled automatically.

When the Query gets accused of Flooding then it will return error with id 524 and an error message which states how much time needs to be waited.

This will be parsed automatically and the Query will wait for the given time (normally its 1 second) + 100 additional milliseconds (sometimes it happens the query gets banned when still sending too early)

Reconnecting

With version 2.3 this library is able to reconnect to its TeamSpeak Server when the connection has been lost. It restores its full context this includes:

  • selecting the server
  • logging in with the last credentials
  • subscribing to all used events
  • selecting the correct nickname

all commands which have been added in meantime while the teamspeak server was not connected will be still executed after and all pending commands will be sent AFTER connecting and restoring the context

an example on how this looks like:

import { TeamSpeak, QueryProtocol } from "./src/TeamSpeak"

TeamSpeak.connect({
  host: "127.0.0.1",
  queryport: 10011,
  serverport: 9987,
  protocol: QueryProtocol.RAW,
  username: "serveradmin",
  password: "xxx",
  nickname: "test"
}).then(async teamspeak => {

  teamspeak.on("close", async () => {
    console.log("disconnected, trying to reconnect...")
    await teamspeak.reconnect(-1, 1000)
    console.log("reconnected!")
  })

})

Update Notes from 1.x to 2.x

With version 2.x support for Client Events has been dropped instead use the events from the main class TeamSpeak. Additionally it comes with TeamSpeak.connect() in order to use a promise to connect to a teamspeak server. Multiple node methods have been replaced with a getter for ex: client.getDBID() -> client.databaseId, client.getUID() -> client.uniqueIdentifier, channel.getID() -> channel.cid The testing environment now runs via jest which makes mocking and testing easier. Since this project now is written in TypeScript vscode should now be completely capable to autocomplete, so there is no need to update docs on @types. Documentation software has been switched from documentation to typedoc

Update Notes to 2.3

The close event now only gets fired when a connection has been successfully established first! In order to get errors when connecting to a server use the error event instead. This was required in order to implement the reconnect logic.

Update Notes to 3.0

Some Parameters are now strings instead of numbers

With the free Beta TeamSpeak Servers for the TeamSpeak 5 Client there are IDs which use a 64 bit format. Since JavaScript starts to round at 53 bits those IDs will not be displayed correctly. In order to compensate this all IDs are now strings instead of numbers!

Function renames

Renamed some function in order to comply with JavaScript Standard

TeamSpeak#getClientByID -> TeamSpeak#getClientById\ TeamSpeak#getClientByUID -> TeamSpeak#getClientByUid\ TeamSpeak#getClientByDBID -> TeamSpeak#getClientByDbid\ ......\ TeamSpeak#getChannelByID -> TeamSpeak#getChannelById\

Update to Permissions

Permissions will now be handled differently, if you for example want to add a Permission onto a ServerGroup then you can use

const group = await teamspeak.getServerGroupById(10)
if (!group) throw new Error("could not find group with id 10")
//old await teamspeak.serverGroupAddPerm(10, "i_channel_subscribe_power", 10, 0, 1)
await teamspeak.serverGroupAddPerm(group, {
  permname: "i_channel_subscribe_power",
  permvalue: 10,
  skip: false,
  negate: true
})
//or alternatively you can use it via the permission object
await teamspeak.serverGroupAddPerm(group)
  .perm("i_channel_subscribe_power")
  .value(10)
  .skip(false)
  .negate(true)
  .update()

Permission List commands will now not give back a raw object but will give you an array of Permission class which you can dynamically update after, for example if you want to add all existing permissions the skip flag

const group = await teamspeak.getServerGroupById(10)
if (!group) throw new Error("could not find group with id 10")
const permlist = await group.permList()
await Promise.all(permlist.map(perm => perm.skip(true).update()))

or if you want to remove all permissions:

const group = await teamspeak.getServerGroupById(10)
if (!group) throw new Error("could not find group with id 10")
const permlist = await group.permList()
await Promise.all(permlist.map(perm => perm.remove()))

To retrieve the permission name or value you can use perm.getValue(), perm.getPerm(), perm.getSkip(), perm.getNegate()

Update to all parameters

all Parameters are now returned as camelcase and require camelcase characters in object properties

console.log(await teamspeak.whoami())
/**
 * with < 3.0 it looked like:
 * {
 *   virtualserver_status: "unknown",
 *   virtualserver_unique_identifier: undefined,
 *   virtualserver_port: 0,
 *   virtualserver_id: 0,
 *   client_id: 0,
 *   client_channel_id: 0,
 *   client_nickname: undefined,
 *   client_database_id: 0,
 *   client_login_name: undefined,
 *   client_unique_identifier: undefined,
 *   client_origin_server_id: 0
 * }
 * with converted to camelcase the response will look like:
 * {
 *   virtualserverStatus: "unknown",
 *   virtualserverUniqueIdentifier: undefined,
 *   virtualserverPort: 0,
 *   virtualserverId: 0,
 *   clientId: 0,
 *   clientChannelId: 0,
 *   clientNickname: undefined,
 *   clientDatabaseId: 0,
 *   clientLoginName: undefined,
 *   clientUniqueIdentifier: undefined,
 *   clientOriginServerId: 0
 * }
 */

the same is for parameters given to update certain things for example:

const channel = await teamspeak.getChannelById(10)
if (!channel) throw new Error("could not find channel with id 10")
//with version < 3.0
channel.edit({
  channel_name: "foo",
  channel_password: "bar",
  channel_description: "lorem ipsum"
})
//with version >= 3.0
channel.edit({
  channelName: "foo",
  channelPassword: "bar",
  channelDescription: "lorem ipsum"
})

In favor to have TeamSpeak#uploadIcon() a new dependency has been added buffer-crc32 Upload Icon takes as first argument the icon buffer and returns after a finnished upload the crc32 value of the buffer

Events

With 3.0 you do not need to subscribe to server events manually anymore! This will now done automatically when necessary! So you can remove those lines from your code:

Promise.all([
  teamspeak.registerEvent("server"),
  teamspeak.registerEvent("channel", 0),
  teamspeak.registerEvent("textserver"),
  teamspeak.registerEvent("textchannel"),
  teamspeak.registerEvent("textprivate")
])

Authors

See also the list of contributors who participated in this project.

changelog

Changelog

3.5.1 - 19.09.2023

  • fix type of clientTalkRequest

3.5.0 - 06.07.2023

  • fix customSearch and customInfo response entry to be an array
  • both above functions will now return an empty array when no entry has been found instead of throwing an error

3.4.0 - 08.10.2021

  • WARNING changed crc32 return value from TeamSpeak#uploadIcon function from a signed int to an unsigned int
  • added empty string for multiple file transfer functions for property cpw
  • update dependencies

3.3.0 - 14.04.2020

  • added TeamSpeak#self in order to get Query client from the current connection
  • added TeamSpeak#sendChannelMessage which will send a message to a specific channel and will move into and back from the channel if necessary
  • added TeamSpeakChannel#message which will utilize TeamSpeak#sendChannelMessage in order to send a message to a channel
  • update packages
  • fixed some types

3.2.0 - 13.11.2020

  • set SSH as default connection if no parameter has been set (raw will be disabled by default with TeamSpeak Server version 3.14.0 as stated in TeamSpeaks Changelog)
  • add optional parameter continueOnError on clientKick, clientMove and banClient
  • add clientEstimatedLocation to TeamSpeak client
  • fix a bug where in some cases paramters are not getting converted from snakecase to camelcase

3.1.0 - 23.10.2020

  • improve typings
  • update dev dependencies

3.1.0 - 12.08.2020

  • implement snapshot version 3

3.0.9 - 02.08.2020

  • fix emitted data from clientdisconnect event
  • update dependencies

3.0.8 - 10.07.2020

  • fix paths to local scripts

3.0.7 - 05.07.2020

  • renamed functions to conform JS camelcase standard
    • getChannelByID -> getChannelById
    • getClientByID -> getClientById
    • getClientByDBID -> getClientByDbid
    • getClientByUID -> getClientByUid
    • clientDBList -> clientDbList
    • clientDBInfo -> clientDbInfo
    • clientDBEdit -> clientDbEdit
    • clientDBDelete -> clientDbDelete
  • all command parameters and responses are now camelcase instead of snakecase
  • all ids are now strings instead of numbers (TeamSpeak 5 Servers have ids >53bit which JavaScript will start to round)
  • all functions which require a channel id, client id etc can now be given the TeamSpeakClient class / TeamSpeakChannel class etc
  • created some overloads for some functions where necessary
  • TeamSpeak#registerEvent now does not need to be called manually instead when a new event listener gets registered then the library will automatically subscribe to necessary events
  • fixed a bug in event context update where only one event gets added to subscription list
  • fixed a bug where invoker can be undefined when a temporary channel gets deleted
  • TeamSpeak#channelEdit will now check if the channel name is already being used by itself
  • TeamSpeak#uploadIcon has been added
  • Errors now should have better stack traces in order to get the correct location of the error

2.4.4 - 06.04.2020

  • update type definitions for serverinfo response

2.4.3 - 28.03.2020

  • fix typings for clientdisconnect event

2.4.2 - 25.03.2020

  • update dependencies

2.4.1 - 22.02.2020

  • made the duration till a keepalive is being sent configurable with keepAliveTimeout

2.4.0 - 20.02.2020

  • added option to ignore query clients allover
  • added apikeyadd, apikeylist, apikeydel commands for teamspeak server beta 3.12.0
  • when query events are getting triggered it should now check if all required entities to fire the final event from the TeamSpeak Library otherwise it will throw an EventError

2.3.3 - 27.01.2020

  • removed channel_cpid
  • added cpid to channeledit props

2.3.2 - 15.01.2020

  • update dependencies
  • add token_customset to return parameter of privilegekeylist for server version 3.11
  • add -banners flag to channellist method and added getters to the TeamSpeakChannel class
  • ResponseError has now the property source which holds the Command instance which generated the error
  • internally change input of clientAddServerGroup and serverGroupDelClient

2.3.1 - 13.12.2019

  • added more exports for the index file
  • added 3rd parameter cldbid to channelGroupClientList

2.3.0 - 25.11.2019

  • added context
  • added TeamSpeak3#reconnect() which is able to reconnect to a TeamSpeak Server with the previous context
  • command parser code improvements (should parse 30% faster now)
  • update dependencies

2.2.0 - 07.11.2019

  • add clientedit()
  • add clientFind()
  • add clientGetIds()
  • add clientGetDbidFromUid()
  • add clientGetNameFromUid()
  • add clientGetUidFromClid()
  • add clientGetNameFromDbid()
  • add channelClientPermList()
  • add serverGroupsByClientId()
  • add channelFind()
  • add banClient()
  • add clientSetServerQueryLogin()
  • add createSnapshot()
  • add deploySnapshot()
  • rewrote some internal function in order to be parse snapshot commands

2.1.0 - 21.09.2019

  • added event tokenused thanks to xIAlexanderIx for the pull request

2.0.2 - 04.08.2019

  • changed property client_flag_avatar to get now really parsed as a string thanks to KhaledSoliman

2.0.1 - 04.08.2019

  • fixed a bug in getAvatar() which did not resolve on error
  • changed property client_flag_avatar to get parsed as a string instead of a number

2.0.0 - 22.07.2019

  • added method TeamSpeak.connect() in order to be able to connect via a Promise wrapper to a Server
  • added listenAddress to connection parameters
  • rewrote code in typescript
  • switch testing framework to jest
  • switch documentation framework to typedoc
  • removed all deprecated methods
  • removed support for client events

1.16.1 - 22.07.2019

  • add -virtual flag to use command
  • updated dependencies

1.16.0 - 25.06.2019

  • added TeamSpeak3#serverTempPasswordAdd()
  • added TeamSpeak3#serverTempPasswordDel()
  • added TeamSpeak3#serverTempPasswordDel()
  • added TeamSpeak3#clientAddServerGroup() (available in server 3.9.0)
  • added TeamSpeak3#clientDelServerGroup() (available in server 3.9.0)
  • added TeamSpeakClient#addGroups() to add multiple groups
  • added TeamSpeakClient#delGroups() to delete multiple groups
  • added deprecation warning for TeamSpeakClient#serverGroupAdd()
  • added deprecation warning for TeamSpeakClient#serverGroupDel()
  • changed output format of clientdbinfo and clientinfo to an array response in order to allow info for multiple clients
  • removed type icon_id from channeledit command (removed in server 3.9.0)
  • less strict type checking for teamspeak connection configuration

1.15.0 - 08.06.2019

  • added pagination parameter to TeamSpeak3#banList for server version 3.8.0
  • added deprecation warning to Abstract#getCache()
  • added tokencustomset parameter to TeamSpeak3#privilegekeyadd()
  • added TeamSpeak3#forceQuit() method
  • library supports now intellisense autocomplete
  • added detailed response documentation for each query command
  • removed some unnecessary Promises
  • fixed TeamSpeak3#messageAdd parameter
  • fixed a non catchable error when connecting with ssh to a server
  • get client properties from clientlist when teamspeak event clientconnect gets fired
  • improved documentation for Client/Server/Channel/... getters
  • added nearly all types
  • changed behaviour of the return value from TeamSpeak3#execute to always return an array with the responses

1.14.0 - 24.5.2019

  • added possibility to ban clients using the mytsid
  • added TeamSpeak3#ban method
  • deprecated TeamSpeak3#banAdd method

1.13.1 - 19.4.2019

  • fixed null type when adding it as flag

1.13.0 - 13.4.2019

  • improved general filetransfer
    • added fileDownload method
    • improved optional parameters like cpw always requires an empty string
  • added method toJSON() to the Abstract class in order to make a client class stringifyable
  • added new way to read cached items from a client to make it more like the javascript way

    for examle on a client class the property client_is_channel_commander will translate to isChannelCommander it will remove the client_ prefix and after each subsequent underscore it will remove the underscore and and make the next character to an UpperCase char. Side Note: only properties which are readable from clientlist, channellist, ... are available like that

      //before
      client.getCache().client_unique_identifier
      client.getCache().client_nickname
      client.getCache().client_is_channel_commander
      channel.getCache().channel_flag_permanent
      channel.getCache().channel_name
      //now
      client.uniqueIdentifier
      client.nickname
      client.isChannelCommander
      channel.flagPermanent
      channel.name
  • added FileTransfer to automated tests

1.12.5 - 10.3.2019

  • fixed a possible memory leak when remove clients/channels/etc from the teamspeak cache object - thanks to elipeF for reporting

1.12.4 - 6.2.2019

  • changes to all *List Commands to return an array

1.12.3 - 4.2.2019

  • fixed event channelcreate
  • refactored code to use .eslintrc.json

1.12.2 - 30.1.2019

  • fixed privilegekeyadd thanks to IronicPickle for the detailed report

1.12.1 - 21.1.2019

  • added getID to channel property

1.12.0 - 15.1.2019

  • update to TeamSpeak Server Version 3.6.0
  • added queryloginadd command
  • added querylogindel command
  • added queryloginlist command
  • updated dependencies

1.11.3 - 12.12.2018

  • fixed invalid serverid upon connect for teamspeak servers < 3.5.0 thanks to Janl1

1.11.2 - 14.11.2018

  • changed requires to not use __dirname anymore
  • removed finally in initialization in order to support older nodejs versions

1.11.1 - 4.11.2018

  • added method channelSetPerms

1.11.0 - 4.11.2018

  • added possibility to provide multiple options within a command, this should fix issue #26

1.10.3 - 12.10.2018

  • fixed errors in handling of socket closing, correct ResponseError Object should now get emitted
  • added parameter readyTimeout to prematurely close a connection while its still connecting

1.10.2 - 1.10.2018

  • added ip parameter to clientList
  • added initial variable for this._data in ssh
  • fixed close event not displaying correct error data

1.10.1 - 22.9.2018

  • fixed typo in ssh keepalive

1.10 - 22.9.2018

  • added function channelGroupPrivilegeKeyAdd
  • added function serverGroupPrivilegeKeyAdd
  • fixed upercase function names for
    • privilegek**eyList > privilegeK**eyList
    • privilegek**eyAdd > privilegeK**eyAdd
    • privilegek**eyDelete > privilegeK**eyDelete
    • privilegek**eyUse > privilegeK**eyUse