Coder Social home page Coder Social logo

multivit4min / ts3-nodejs-library Goto Github PK

View Code? Open in Web Editor NEW
148.0 6.0 17.0 4.93 MB

TeamSpeak 3 Server Query Library supports SSH and RAW Query

Home Page: https://multivit4min.github.io/TS3-NodeJS-Library/

License: MIT License

JavaScript 0.07% TypeScript 99.93%
teamspeak ts3 query telnet nodejs node teamspeak3 teamspeak-query teamspeakquery ssh

ts3-nodejs-library's Introduction

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.

ts3-nodejs-library's People

Contributors

brandonschmitt avatar dalexhd avatar dependabot[bot] avatar elipef avatar felixgerberding avatar janpfischer avatar multivit4min avatar mxschmitt avatar p4sca1 avatar syscaller-dev avatar thetruerandom avatar timche avatar xialexanderix avatar zerefdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ts3-nodejs-library's Issues

On channeledit get description?

Hi, I am trying to arrange channel_description through

ts3.on("channeledit", ev => {
    var channel = ev.channel
    console.log(channel.getCache())
})

but he receives the following result

{ cid: 64,
  pid: 0,
  channel_order: 90,
  channel_name: '[cspacer2] ٠ Welcome ! ٠',
  channel_topic: undefined,
  channel_flag_default: 1,
  channel_flag_password: 0,
  channel_flag_permanent: 1,
  channel_flag_semi_permanent: 0,
  channel_codec: 4,
  channel_codec_quality: 6,
  channel_needed_talk_power: 100,
  channel_icon_id: 0,
  seconds_empty: -1,
  total_clients_family: 4,
  channel_maxclients: -1,
  channel_maxfamilyclients: -1,
  total_clients: 4,
  channel_needed_subscribe_power: 0 
}

How can I reach the channel_description as much as possible?

Event not getting triggered

The clientconnect event doesn't get triggered. Same as clientdisconnect event.
ready gets called. I can also read all online clients!

const Teamspeak = require("ts3-nodejs-library");

var ts3 = new Teamspeak(/* Connection config */);

ts3.on("clientconnect", client => {
    console.log("[+]" + client.nickname);
});

ts3.on("clientdisconnect", client => {
    console.log("[-]" + client.nickname);
});

serveredit event return not all values

Describe the bug
When change logs values in serveredit, event return empty object instead of values which changed.

To Reproduce
ts3.on("serveredit", ev => {
console.log(ev.modified);
})

Expected behavior
When you disable filetransfer log it should return:
{virtualserver_log_filetransfer: 0}
but already it's:
{}

Versions used

  • 3.7.1
  • v11.12.0
  • ^1.12.5

Support custom events.

Hi, I whould like to have some custom events onto your lib.
onServerErrorEvent
onTextMessageEvent
onClientPokeEvent
onServerPermissionErrorEvent
onFileTransferStatusEvent
onAvatarUpdated
onBanListEvent
onChannelDescriptionUpdateEvent
onChannelMoveEvent
onChannelPasswordChangedEvent
onClientBanFromServerEvent
onClientChannelGroupChangedEvent
onClientChatClosedEvent
onClientChatComposingEvent
onClientDisplayNameChanged
onClientKickFromChannelEvent
onClientKickFromServerEvent
onClientMoveEvent
Connected
Disconnected
Switched
onClientMoveMovedEvent
onClientMoveSubscriptionEvent
onClientMoveTimeoutEvent
onClientSelfVariableUpdateEvent
onConnectStatusChangeEvent
Connected
Disconnected
onDelChannelEvent
onMessageGetEvent
onNewChannelCreatedEvent
onPluginCommandEvent (#28)
onServerEditedEvent
onServerGroupClientAddedEvent
onServerGroupClientDeletedEvent
onServerStopEvent
onUpdateChannelEditedEvent

subChannelList

Hi there is there any way you could add a subChannelList method to this library I would do it myself but I'm not too familiar with EventEmitters.

Thanks for creating this amazing library and sharing it with us!

Client permList

Describe the bug
If the permsid parameter is false, I get error: TypeError: Cannot read property 'constructor' of null
But if the parameter is true, the function work like a charm.

To Reproduce

ts3.getClientByUID(uuid).then(function(client)
{
    client.permList(false).then(function(permlist)
    {
        console.log(permlist);
    }
}

Versions used

  • TeamSpeak Server Version: TeaSpeak 1.3.11
  • NodeJS Version: v8.15.1
  • Library Version: 1.13.0

**EDIT: Maybe this issue because of teaspeak...

Possible memory leak - maximum listeners cap hit

Describe the bug
registering <5 events triggers following message:
"(node:7339) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit"

To Reproduce

// g_teamspeak = ts3 class
g_teamspeak.on('ready', () => {
Promise.all([
g_teamspeak.registerEvent('server'),
g_teamspeak.registerEvent('channel', 0),
g_teamspeak.registerEvent('textserver'),
g_teamspeak.registerEvent('textchannel'),
g_teamspeak.registerEvent('textprivate')
])
}

Expected behavior
Maximum listeners should be more than just 10 to avoid memory leaks.

Versions used

  • 3.6.0 (16.01.2019 08:50:10)
  • v11.10.0
  • latest (as of 08.03.2019)

Additional context
Adding
this._parent.setMaxListeners(100) // as example
to ts3-nodejs-library/property/Abstract.js (function .on(name, cb), line 40) should fix the issue.

Working with sockets.io

Hi another time :-)
How can I get data from a sockets request.

socket.on('req_clientList', function(message){
	io.sockets.emit("res_clientList", ts3.channelList());
});

I know that the problem comes with asynchronous stuff, but I cant get it working even with promises...

How to use channelSetPerm to set multiple permissions?

Hi, bit confused with this.

To do this I'm presently looping channelSetPerm and each time passing a permsid and value from an array.

async function setChannelPerms() {
	let result = "Permissions set successfully";
	// loop through channel array
	for (let c of channels) {
		// loop through channel's permissions object
		for (let perm in c.permissions) {
			// Set channel perms one-by-one
			await ts3.channelSetPerm(c.cid, perm, c.permissions[perm], true).catch(err => {
				result = config.messages.extError + err.message;
				console.error("CATCHED", err.message, "ON", c.name);
			});
		}
	}
	return result;
}

This is working, however, when investigation the channelSetPerm function further in the TS3-NodeJS-Library I found this line:

  • Multiple permissions can be added by providing the two parameters of each permission.

Now, maybe I'm completely missing something, but I'm not understanding how to achieve this. If my interpretation is correct I should be able to pass multiple permsids and values using a single call to channelSetPerm. Avoiding the need to use a loop for however many permissions need setting. However, I'm not sure how to do this. I've tried using an array storing permsids as strings and another array storing the values, then passing these arrays as parameters, this did not work as I expected. I also tried a string of all the permsids separated with ',' or spaces which also did not work.

Any advise would be appreciated, thanks!

Unhandled 'error' event

After shutting down the TeamSpeak3 Server, the event "close" gets fired, but the app crashes a few seconds later:

events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: This socket has been ended by the other party
    at Socket.writeAfterFIN [as write] (net.js:401:12)
    at Timeout._antispamTimeout.setTimeout [as _onTimeout] (C:\xampp\htdocs\project\nodebot\node_modules\ts3-nodejs-library\transport\TS3Query.js:209:26)
    at ontimeout (timers.js:427:11)
    at tryOnTimeout (timers.js:289:5)
    at listOnTimeout (timers.js:252:5)
    at Timer.processTimers (timers.js:212:10)
Emitted 'error' event at:
    at Socket._socket.on.err (C:\xampp\htdocs\project\nodebot\node_modules\ts3-nodejs-library\transport\TS3Query.js:105:50)
    at Socket.emit (events.js:182:13)
    at Socket.writeAfterFIN [as write] (net.js:404:8)
    at Timeout._antispamTimeout.setTimeout [as _onTimeout] (C:\xampp\htdocs\project\nodebot\node_modules\ts3-nodejs-library\transport\TS3Query.js:209:26)
    [... lines matching original stack trace ...]
    at Timer.processTimers (timers.js:212:10)

Connection failed, invalid serverID

a2f0590b89dfed0cfd00fba94a6df227
Describe the bug
Connecting to the teamspeak server allways returns an invalid serverID error

To Reproduce
Use the example code from the readme and try to connect to a server

Expected behavior
Establish the connection

Versions used

  • TeamSpeak Server Version: 3.3.0
  • NodeJS Version (check with node -v): 11.4.0
  • Library Version: 1.11.2

Additional context
My teamspeak server is not using the default port.
I specified the port as serverport in the TeamSpeak3 objects parameters.
However the connection allways returns "Error invalid serverID".

Is there a special way to set the serverID or to set the option that the library should use the port to determine the serverID?
I looked up the server id of my server with yatqa and it equals 1.

High memory usage over time

Describe the bug
Saturation of the memory by the bot without any errors

To Reproduce

const ts3 = new TeamSpeak3({
  host: 'blabla',
  queryport: 10022,
  protocol: 'ssh',
  serverport: 'blabla',
  username: 'blabla',
  password: 'blabla',
  nickname: 'blabla',
  keepalive: true,
});

ts3.on('error', err => {
  console.log(err);
});

ts3.setMaxListeners(0);

ts3.on('clientconnect', async ev => {
  const { client } = ev;
  // for example simple if to check if client nickname include some char
});

ts3.on('ready', async () => {
  try {
    await ts3.registerEvent('server');
    const users = await ts3.clientList();
    for (const user of users) {
      // same of as higher
    }
  } catch (e) {
    console.log(e);
  }
});

Expected behavior
To clear or reduce memory usage somehow.

Versions used

  • 3.6.1
  • v11.11.0 checked on older too
  • 1.12.4

Additional context
Nothing special happened here, but this "nothing" takes 4GB of RAM and that's terrifying. The use of memory grows over time and does not diminish. Even if there is zero traffic on the server, the memory usage increases. I think it's the fault of the "clientconnect" event which probably saves information about the user but does not clean them after the user left the server (Correct me if I'm wrong)

Misstake in the Code example

There is a missing closing bracket in line 26 of your code example !

ts3.on("ready", () => {
    //Retrieves a List of non Query Clients
    ts3.clientList({client_type:0}).then(clients => {
        clients.forEach(client => {
            console.log("Sending Message to", client.getCache().client_nickname);
            //Sends to every Client a "Hello"
            client.message("Hello!")
        } )<---
    }).catch(e => console.log("CATCHED", e))
})

BBcode is escaped!

Hi,

The following command:

ts3.execute(`gm msg=${chosenMessage}`)
// or ts3.gm(...)
.then(() => console.log("message send!"))
.catch(e => console.log("Something went wrong:", e.message));

Escapes my special characters... I really need to use bbcode inside of my text messages. Is there, at least, a workaround to deal with it?

Thanks.

TypeScript typings?

Are there any plans on adding TypeScript typings to this project?
I would like to assist in adding them, but I need a starting point, as I never added types to a js project.

Custom Nickname of TeamSpeak3 Instance

Describe the bug
Im not sure if this is a Bug or something i dont understand why its happening:

The Nickname in the Object passed to the TeamSpeak3 Instance Constructor will be ignored if the functions TeamSpeak3#useByPort or TeamSpeak3#useBySid are used correctly. Instead the the Nickname from the TeamSpeak3 Database will be used for the Connection.
But, if i try to Connect with a invalid Port or SID (No Virtual Server binded to Port or SID) the Nickname from the Instance Constructer is used.

To Reproduce

const TeamSpeak3 = require("ts3-nodejs-library");
const conCfg = {
  host: "localhost",
  queryport: 10011,
  serverport: 9987,
  username: "queryLoginUsername",
  password: "Somepwd",
  nickname: "My_Desired_Nickname",
  keepalive: true
}

// throws an Error, connects anyway
ts3.useByPort(1, "queryLoginUsername"); // whoami: My_Desired_Nickname ( from conCfg.nickname )
ts3.useBySig(9987, "queryLoginUsername"); // whoami: My_Desired_Nickname ( from conCfg.nickname )

// as it should be used
ts3.useByPort(9987, "queryLoginUsername"); // whoami: Nickname in DB (e.g. queryLoginUsername
ts3.useBySig(1, "queryLoginUsername"); // whoami: Nickname in DB (e.g. queryLoginUsername

Expected behavior

Versions used

  • TeamSpeak Server Version: 3.7.0 on Windows
  • NodeJS Version: 10.15.3
  • Library Version: 1.13.0

Additional context
I am using the standard TeamSpeak Server SQLite Database, no MySQL.
The TeamSpeak has only one Virtual Server Instance (SID: 1) running on Port 9987.

Error from "To Repreoduce":

Unhandled Rejection at: { [ResponseError: invalid serverID]
  id: 1024,
  msg: 'invalid serverID',
  extra_msg: undefined,
  failed_permid: undefined,
  message: 'invalid serverID' }
Promise {
  <rejected> { ResponseError: invalid serverID
    id: 1024,
    msg: 'invalid serverID',
    extra_msg: undefined,
    failed_permid: undefined,
    message: 'invalid serverID' } }

Problem with error 'Error args is not defined'

Hi.
My problem (called 'Error args is not defined') is fired when i try create channel. I have registered all events in 'Engine' for further processing. After research in your code propably i found a problem in main TeamSpeak3.js file on line 307. There is trying access to undefined variable 'args' ?

_evchanneldeleted() function fix.

Hello :-)
I´m currently working with your project, and I noticed that there is an error on the _evchanneldeleted() function (Located on TeamSpeak3.js).

  • Previous code:
_evchanneldeleted() {
    this.getClientByID(arguments[0].clid)
    .then(client => {
        this.emit("channeldelete", {invoker: client, cid: arguments[0].cid})
    }).catch(e => this.emit("error", e))
}
  • Fixed code:
_evchanneldeleted() {
    this.getClientByID(arguments[0].invokerid)
    .then(client => {
        this.emit("channeldelete", {invoker: client, cid: arguments[0].cid})
    }).catch(e => this.emit("error", e))
}

Why clientdisconnect only return client id?

Describe the bug

When i listen to 'clientdisconnect' event, the client array only have 'clientid' on it ...
it's kind of useless .. isn't possible to return 'client dbid' at least?!

Event 'clientconnect' doesn't work.

Describe the bug
Event 'clientconnect' and 'clientdisconnect' doesn't work.

To Reproduce
Create an TS3-Instance, and create an 'ts3.on("clientconnect", () => { // Code goes here })'.
FYI: I called it outside and inside of the Ready-Event.

Expected behavior
The Event should be called if a Client connect to the Teamspeak Server or a Client disconnects.

Versions used

  • TeamSpeak Server Version: 3.5.1
  • NodeJS Version: v8.11.4
  • Library Version: ^1.11.3

Additional context
I dumped the created "ts3" var and found the "_events" in "_ts3: TS3Query { _events:", there is no "clientconnect" or "clientdisconnect", but it is in the Documentation, did it got removed? Events like 'debug', 'ready' do indeed work.

Private messages

hello, someone can help me?

when i send a massage to my bot, it write me back this -> This ServerQuery client did not register for the private text message event using "servernotifyregister event=textprivate". The text message was not received.

http://prntscr.com/j7giug

Not listening to channel messages

Describe the bug
Does not fire TeamSpeak3#textmessage. Only private Messages and Messages in the same Channels as the Bot fires the Event but not the Messages of Clients in other Channels.

To Reproduce

const TeamSpeak3 = require("ts3-nodejs-library")

const ts3 = new TeamSpeak3({
      host: "localhost",
      queryport: 10011,
      serverport: 9987,
      username: "serveradmin",
      password: "some",
      nickname: "Bot",
      keepalive: true
    })
ts3.useBySid(1, "serveradmin");

ts3.on("ready", () => {
  Promise.all([
    ts3.registerEvent("server"),
    ts3.registerEvent("channel", 0),
    ts3.registerEvent("textserver"),
    ts3.registerEvent("textchannel"),
    ts3.registerEvent("textprivate")
  ]).then(() => {
      console.log("Subscribed to all Events")
  }).catch(e => {
      console.log("CATCHED", e.message)
  })
})
ts3.on("textmessage", ev => { console.log(ev) })

Expected behavior
I already read other Issues like #14 but i can not fix the this in my Script.
As far as i understand, a Message in any Channel should fire TeamSpeak3#textmessage

Versions used

  • TeamSpeak Server Version: 3.3.1 on Linux
  • NodeJS Version: v10.15.3
  • Library Version: 1.13.0

Additional context

Privilege key list

Describe the bug
If there is no privilege keys, its return with error: ResponseError: database empty result set

To Reproduce

ts3.privilegeKeyList().then((keylist) => 
{
    console.log(JSON.stringify(keylist));
})
.catch((err) =>
{
    console.log('Err: ' + err);
});

Expected behavior
Return false or NULL

Versions used

  • TeamSpeak Server Version: TeamSpeak 3.7.1 (2019. 03. 28. 08:46:26)
  • NodeJS Version: v8.15.1
  • Library Version: 1.13.1

How to get an specific icon.

I´m trying to get server groups, channel groups, channel, and clients icons in base64 format. How can I retrieve this data on the following structure?

socket.on('req_test', async function(message){
	var alldata = new Array();
	alldata.server = (await ts3.serverInfo());
	alldata.channel = (await ts3.channelList()).map(c => c.getCache());
	alldata.clients = (await ts3.clientList()).map(c => c.getCache());
	alldata.sgroups = (await ts3.serverGroupList()).map(c => c.getCache());
	alldata.cgroups = (await ts3.channelGroupList()).map(c => c.getCache());
	for (var i = 0; i < alldata.channel.length; i++) {
		var icon = //Here is where i want to get the channel icon in base64
	}
});	

Creating a privilege key returns 'parameter not found'

Describe the bug
The 'privilegeKeyAdd' method throws 'parameter not found' regardless of the parameters set.

To Reproduce
ts3.privilegeKeyAdd(0, $sgid) .then(function(data) { console.log(data) }) .catch(function(err) { console.log("Caught: " + err.message) });

Expected behaviour
Should create and output a privilege key.

Versions used

  • TeamSpeak Server Version: 3.3.1 on Linux
  • NodeJS Version: v10.14.1
  • Library Version: 1.12.1

Additional context
After doing some digging, the error seems to be caused by the 'tokenid2' parameter being omitted when 'tokentype' is equal to 0, though it should be defined regardless according to the serverquery manual.

ts3.privilegekeyadd returns invalid argument?

//ts start
ts3.on("ready", () => {
ts3.useByPort(port).then(function(result){
ts3.getServerGroupByName("Server Admin").then(function(result){
ts3.privilegekeyAdd(result._propcache.type, result._propcache.sgid).then(function(result){
console.log("Token Added:")
}).catch(e => console.log("CATCHED", e))
}).catch(e => console.log("CATCHED, e.message"))
}).catch(e => console.log("CATCHED", e.message))
})
//end start code

Pretty sure i got this right but maybe you could help by pointing out my error?

Problem with the sorucecode

Describe the bug
My bot is running on my local pc running ubuntu and can't connect to the ts3 server. But when I start the same bot on the server where my ts3 server is running everything is woking.

Version

  • latest version node
  • latest version npm
  • ubuntu 18.04
  • latest version ts3

Thx for your help

Output by console:

/home/medienteam/Schreibtisch/Bot/tsbot/node_modules/ts3-nodejs-library/TeamSpeak3.js:88
              .finally(() => {
                      ^

TypeError: this.version(...).then(...).catch(...).finally is not a function
    at TS3Query.TeamSpeak3._ts3.on (/home/medienteam/Schreibtisch/Bot/tsbot/node_modules/ts3-nodejs-library/TeamSpeak3.js:88:23)
    at emitNone (events.js:106:13)
    at TS3Query.emit (events.js:208:7)
    at TS3Query.handleConnect (/home/medienteam/Schreibtisch/Bot/tsbot/node_modules/ts3-nodejs-library/transport/TS3Query.js:75:12)
    at emitNone (events.js:106:13)
    at RAW.emit (events.js:208:7)
    at RAW._handleConnect (/home/medienteam/Schreibtisch/Bot/tsbot/node_modules/ts3-nodejs-library/transport/protocols/raw.js:54:10)
    at emitNone (events.js:111:20)
    at Socket.emit (events.js:208:7)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1173:10)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node bot.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/medienteam/.npm/_logs/2018-11-14T09_48_28_421Z-debug.log

getClientByUID returns serverquery

Describe the bug
When I use the getClientByUID method of the main teamspeak query class, I would expect to receive an instance of TeamspeakClient of the supplied uid. Instead it seems to return the server query account which is used for connecting but with the supplied uid in it.

To Reproduce

this.ts3.getClientByUID(tsUid).then((tsClient) => {
    tsClient.getInfo().then((tsClientInfo) => {
        tsClient.message("Your skill group has not changed!").then().catch(() => {
            console.log("Shiat");
        });
        this.logger.debug(`Rank of ${tsClientInfo.client_nickname} has not changed!`)
    })
    .catch((err) => {
        console.log(err);
    });

You can find the complete source code here. It is in the 'setRank' method

Expected behavior
A instance of TeamspeakClient with the correct data of the requested uid

Versions used

  • TeamSpeak Server Version: 3.7.0
  • NodeJS Version: 8.15.1
  • Library Version: 1.12.5

Some Icon ID's are invalid

Describe the bug
Some Icon id's are going negative. Pattern unknown. Seems like it's completly random what icons are affected.
Trying to set the obtained icon id to a server/channel-group or server/channel returns "convert error".

I obtain the iconid by getChannelGroupByID() -> object.getCache(), which returns following:
{ cgid: 158, name: 'MyChannelGroup', type: '1', iconid: '-164414261', savedb: '1', sortid: '14500', namemode: '0', n_modifyp: '50', n_member_addp: '75', n_member_removep: '25' }

To Reproduce
g_teamspeak.getChannelGroupByID(client['client_channel_group_id']).then(function(obj) { console(obj.getCache().iconid); // returns -543746121, valid icon id would be 1958946389 });

Expected behavior
Valid channelgroup icon id that I can set as channel icon

Versions used

  • 3.6.0 (16.01.2019 08:50:10)
  • v11.11.0
  • latest (as of 09.03.2019)

Additional context
I'm getting the channelgroup icon of a user, the user creates a channel in a certain area, gets channel admin and the created channel should get the icon that the user had before he created the channel.

Ban using mytsid

i would like to ask to implement the feature introduced in ts3 server 3.5 release
the ability to ban a client using his MyTeamSpeakId ( mytsid ) ( client_myteamspeak_id )

Added: Option added to ban users via mytsid or for not having a mytsid.
Example: banadd mytsid=AaqQu8Z/CzDMxRZ87P5oWpYempDPoO9K3l3VErhVPo+j banreason=banned\smytsid
Example: banadd mytsid=empty banreason=banned\severyone\sthat\sdoesn't\shave\sa\smytsi

thanks :)

Same Identity Count Question

I just would like to ask, is there a way to get clients connected more than 2 times with the same identity

i mean for example i have an identity and i connected it to server 1
then i connected with the same identity in a new tab to server 1

i want the easiest way to output who every have more than 2 same identity connected to the same server

i just couldn't think of a way for it lol

thanks ..

( i know i also hate to open questions in issues tab, i wish you had somewhere else to discuss and talk about the api )

invalid serverID Docker

Describe the bug
Docker Container cant start:
Output

CATCHED invalid serverID
{ Error: invalid serverID

at Command.getError (/nodeapp/node_modules/ts3-nodejs-library/src/transport/Command.js:143:12)
at TS3Query.handleQueryError (/nodeapp/node_modules/ts3-nodejs-library/src/transport/TS3Query.js:142:44)
at TS3Query.handleLine (/nodeapp/node_modules/ts3-nodejs-library/src/transport/TS3Query.js:116:12)
at RAW.emit (events.js:198:13)
at lines.forEach.line (/nodeapp/node_modules/ts3-nodejs-library/src/transport/protocols/raw.js:81:32)
at Array.forEach (<anonymous>)
at RAW._handleData (/nodeapp/node_modules/ts3-nodejs-library/src/transport/protocols/raw.js:81:11)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:265:13)
id: 1024,
msg: 'invalid serverID',
extra_msg: undefined,
failed_permid: undefined }

Versions used

  • TeamSpeak Server Version
    3.8.0
  • NodeJS Version (check with node -v)
    v10.15.1
  • Library Version
    ^1.15.0

Additional context
Local does the program work with hardcoded settings. With Docker environment settings it doesnt work.

Thank you for the amazing library.

Strange behaviour after x random connected time with TS3-NodeJS-Library.

My project: A website connected with this library via sockets and express.
Version used: 1.7.1
Server version: 3.4.0 [Build: 1536564584]
NodeJS version: 10.9.0
Used protocol: SSH

What works correctly with out interruption: Subscribe to events of ts3 and pass those events to my socket.io interface.

What works correctly during x random time and then interrupts: Sending any query commands.

Personal explanation: Idk where does the problem come from, at least, after debugging socket.io I realised that it wasn't the problem. The problem comes when the app is online x random time. In my opinion this seems to be a problem with server or library itself.
For example, if I visit my website viewer after 4 hours of running app, maybe it would not be rendered, as the query seems to "stop" accepting commands.

Video reproducing the issue: https://www.youtube.com/watch?v=cCfd7qt7_nQ

  1. 0:04: I refresh the page and then, on the right side, you can see that the socket interface is receiving that new connection event.
  2. 0:10: On the left side, on socket frames log, it should appear some data handled by socket.io io.sockets.on('connection', function (socket) { event, where socket.io will make a request to the ts3 query getting clientlist and current_clients_number/max_slots, and then send this data to the socket.id (connected client, not globally). But as you can see, this data is not retrieved,
  3. 0:25: I stop the ts3 website backend screen, and then, it would start automatically (dont worry, it´s just a shell script that check if some screens are running, and if not, start them).
  4. 0:36: On the left side, you will see those events that where not appearing on the second step.

Error on start

When I start, a example script

nodejs serverinfo.js
This returned:

class TeamSpeak3 extends EventEmitter {
^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/home/nodejs/examples/serverinfo.js:1:82)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)

And i install TS3-NodeJS-Library (npm install ts3-nodejs-library), I have:

npm ERR! Linux 4.4.0-137-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "ts3-nodejs-library"
npm ERR! node v4.2.6
npm ERR! npm v3.5.2
npm ERR! code ENOSELF
npm ERR! Refusing to install ts3-nodejs-library as a dependency of itself

  • TeamSpeak Server Version - 3.6.1
  • NodeJS Version - v4.2.6
  • Library Version -

Send a message to specific client

Hello,

how can i send a message to specific client?

i found this funtion -> teamSpeak3.sendTextMessage(target, targetmode, msg)
But i don't understand what i should pass into target

i passed the client object

ts3.clientList().then(users => {
    users.forEach(user => {
        if (xefnc.xeCheckEsInEs(user._propcache.client_servergroups,dati.stuffPermissions)) {
            //Prints admins name
            console.log(user._propcache.client_nickname)

            //should send a message to administrator
            ts3.sendTextMessage(user, 1, `${client._propcache.client_nickname} needs help`).catch(e => {
                  console.log(e)
            });
        };
    });
});

From console.log(e) i get this error:

{ id: 1540, msg: 'convert error' }

Someone can help me? 😄

Add ServerGroup

Hello Im new in nodejs, so I have a question, Its possible register Guest Users when they enter to a specific Channel?

Unhandled 'error' event

Hi,

when I try to connect to a not reachable server I get the following error which can't be catched.

events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: Timed out while waiting for handshake
    at Timeout._onTimeout (C:\xxx\Dev\teamspeak-node-rest-api\teamspeak-node-rest-api\node_modules\ssh2\lib\client.js:694:19)    at ontimeout (timers.js:424:11)
    at tryOnTimeout (timers.js:288:5)
    at listOnTimeout (timers.js:251:5)
    at Timer.processTimers (timers.js:211:10)
Emitted 'error' event at:
    at TS3Query.TeamSpeak3._ts3.on.e (C:\xxx\Dev\teamspeak-node-rest-api\teamspeak-node-rest-api\node_modules\ts3-nodejs-library\TeamSpeak3.js:84:38)
    at TS3Query.emit (events.js:182:13)
    at TS3Query.handleError (C:\xxx\Dev\teamspeak-node-rest-api\teamspeak-node-rest-api\node_modules\ts3-nodejs-library\transport\TS3Query.js:168:10)
    at SSH.emit (events.js:182:13)
    at SSH._handleError (C:\xxx\Dev\teamspeak-node-rest-api\teamspeak-node-rest-api\node_modules\ts3-nodejs-library\transport\protocols\ssh.js:75:10)
    at Client.emit (events.js:182:13)
    at Timeout._onTimeout (C:\xxx\Dev\teamspeak-node-rest-api\teamspeak-node-rest-api\node_modules\ssh2\lib\client.js:696:14)    at ontimeout (timers.js:424:11)
    at tryOnTimeout (timers.js:288:5)
    at listOnTimeout (timers.js:251:5)

My Code:
index.js

...
let connection = new Teamspeak(username, password, host, server_port, query_port, protocol);
    try {
        let response = await connection.getClientList();
        return res.send(response);
    } catch (e) {
        return res.status(400).send({
            message: e
        });
    }
...

TeamSpeak Contructor

import TeamSpeak3 from 'ts3-nodejs-library';
import consola from 'consola';

function Teamspeak(username, password, host, server_port, query_port, protocol) {
  this.username = username;
  this.password = password;
  this.host = host;
  this.server_port = server_port;
  this.query_port = query_port;
  this.protocol = protocol;
}

Teamspeak.prototype.connect = async function () {
  try {
    let connection = await new TeamSpeak3({
      username: this.username,
      password: this.password,
      host: this.host,
      serverport: this.server_port,
      queryport: this.query_port,
      protocol: this.protocol
    });
    connection.setMaxListeners(100);
    await connection.useByPort(this.server_port, 'Node JS Bot');
  } catch (e) {
    throw e;
  }

  return connection;
};

Teamspeak.prototype.getClientList = async function () {
  try {
    const connection = await this.connect();
    //Retrieves a List of non Query Clients
    const clients = await connection.clientList({
      client_type: 0
    });
    return clients;
  } catch (e) {
    throw e;
  }
};

module.exports = Teamspeak;

'channel_needed_subscribe_power' is always 0

Hey there,

It seems like the channel_needed_subscribe_power returned by channel.getCache() is always 0.
This is what I used to get it:

ts3.getChannelByID(whatver).then(channel => {
   console.log(channel.getCache().channel_needed_subscribe_power)
})

Am I doing it right or is there an issue in the Library?

Best regards,
Felix

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.