Introduction
This scripting-documentation lists all available modules and their methods implemented in the current SinusBot Scripting Engine.
Check out our guide in the SinusBot Documentation for explanations on how to get started.
The code used to generate this documentation can be found here on GitHub. Contributions are welcome!
There is also a documentation available for the command-library that was introduced with sinusbot-1.0.0-alpha.
registerPlugin
This is the first and only top-level function that should be called in your script, everything else will be done in the function that is passed to it.
Parameters
manifest (Manifest)
The manifest determines which features are available to the script and contains metadata and variables that will be shown in the web interface.
mainFunction (mainFunction)
If the script is activated this function is called when the scripts are loaded. The function receives three parameters, the first one (
_
) is deprecated and should not be used anymore.
Example
registerPlugin({ name: 'Demo Script', version: '1.0', description: 'This example actually does nothing', author: 'Author <author[at]example.com>', vars: [] }, function(_, config, meta) { });
Manifest
Manifest
Type: object
Properties
name (string)
: Short name of your script
author (string)
: Your name and your email address in the form of:
your name <your-email@example.com>
description (string)
: A longer description - tell the user what exactly your script does
version (string)
: Start with something like 1.0 and increase it with every release
autorun (boolean?)
: Set to true, if you want the script to be run on every instance, without the option to disable it.
backends (Array<string>?)
: Per default scripts will only be available on TS3 instances. If your script supports Discord (or in the future maybe other backends) as well, you have to specify this explicitly by setting this variable to an array containing all backends:
backends: ["ts3", "discord"]
enableWeb (boolean?)
: If your script required own web content, you can set enableWeb to true and put files into the ./scripts/scriptname/html directory. After restart, the script title will be clickable and lead to an index.html inside that html-directory you just created.
From there you have access to the localStorage variables containing the login and may communicate with the bot api from your own pages.
engine (string?)
: Sets the required engine version (bot version). This uses
Semantic Versioning . Example:
engine: ">= 0.9.16"
hidden (boolean?)
: Hides the script from the settings page. Should be used together with autorun.
Hidden scripts can not have variables (vars), since they'd never be shown and thus not configurable.
requiredModules (Array<string>?)
: An array of protected modules (i.e. 'http' or 'db') that the script requires.
vars (Array<object>?)
: More information about the usage of variables can be found
here .
voiceCommands (Array<string>?)
: This parameter is only used for the speech recognition feature and may contain one or more strings that are to be detected for the given script. You can find more details on how to use it here:
Speech Recognition Related
registerPlugin
mainFunction
Type: Function
Parameters
_ (object?)
This parameter is deprecated and should not be used anymore.
config (object)
Configuration of the plugin that the user set from within the web interface (given you have added anything to the vars field of your script manifest).
meta (Manifest)
Manifest as specified in registerPlugin.
Related
registerPlugin modules
Modules which can be imported via require(<module name>)
engine
engine
Example
const engine = require('engine'); engine.log('Hello from a script!');
Static Members
Returns
string
: Current instances' unique identifier Returns
string
: Current bots' unique identifier Returns the name of the used backend (e.g. "ts3" or "discord")
Returns
string
: Backend ▸ setInstanceLogLevel(level) sets the log level of the instance
level | what gets logged ------|----------------- 0 | no log messages 1 | errors only 2 | errors and warnings 3 | errors, warnings, information 4 | ... 10 | most verbose 11 | most verbose + external backends
Parameters
level (number)
Log level to set
Returns
boolean
: Sets the log level of the bot
level | what gets logged ------|----------------- 0 | no log messages 1 | errors only 2 | errors and warnings 3 | errors, warnings, information 4 | ... 10 | most verbose 11 | most verbose + external backends
Parameters
level (number)
Log level to set
Returns
boolean
: Returns the log level of the instance
Returns
number
: The set loglevel Returns the log level of the bot
Returns
number
: The set loglevel Reloads all scripts; requires the corresponding setting in the config.ini to be enabled
Returns
boolean
: Returns the configured nickname - to get the actual nickname, use the backend module
Returns
string
: Sets the nick to a new value and updates it on the server
Parameters
Returns
boolean
: Gets the default channel ID
Returns
string
: ▸ setDefaultChannelID(channelID) Sets the default channel by its ID
Parameters
Returns
boolean
: Returns true if the backend of this instance has been started
Returns
boolean
: Sends a notification to all users that are currently using the webinterface; use this for startup errors
Parameters
message (string)
Message to send
Stores the given object as configuration for the current script
Parameters
Returns
boolean
: Logs to stdout / instance log.
Note:
- For some classes this may print
{}
because the values are returned by functions and not stored as properties. - In recent versions numbers and some other types may be logged as
<nil>
. To get the actual value in the log you need to convert it to a string first.
log(something: ...any)
Parameters
Example
const engine = require('engine'); engine.log('Hello from a script!'); const a = 42; const b = 1337; engine.log('a is ' + a + ', and b is ' + b + '.'); engine.log(`a is ${a}, and b is ${b}.`); const cat = {says: 'meow'}; engine.log(`cat: ${cat}`); engine.log(cat); engine.log(`cat: ${JSON.stringify(cat)}`); engine.log(JSON.stringify(aClientObj)) engine.log(aClientObj) engine.log([aClientObj, aClientObj])
▸ logf(format, something) logf(format:
string, something: ...any)
Parameters
Exports an object, so other Scripts are able to use functions or values of the Script
Note: Since SinusBot v1.0.0 you can now use the standard module.exports = {...};
instead, as shown below.
Parameters
obj (object)
object which should get exported
Example
var publicvariable = 'I get exportet!'; module.exports = { get: () => { return publicvariable; }, set: (value) => { publicvariable = value; } };
var event = require('event'); var engine = require('engine'); event.on('load', function() { var script = require('exportscript.js'); engine.log(script.get()); script.set('New Value'); engine.log(script.get()); });
removes the current avatar image
Returns
boolean
: ▸ setAvatarFromTrack(track) sets the avatar image to the album art of a given track
Parameters
track (Track)
Track to extract the album art from
Returns
boolean
: sets the avatar image to the manually uploaded image
Returns
boolean
: ▸ setAvatarFromBanner(bannerName) sets the avatar to the rendered output of a banner template
Since: 0.12.0
Parameters
bannerName (string)
banner template to use
Returns
boolean
: sets the avatar to the given image as URL
Since: 0.14.0
Parameters
Returns
boolean
: Gets the users of the SinusBot
Since: 0.13.37
Returns
Array<User>
: Gets a SinusBot user by his ID
Since: 0.13.37
Parameters
id (string)
ID of the SinusBot user
Returns
User?
: Gets a Sinusbot user by his name.
Since: 0.13.37
Parameters
name (string)
Name of the user
Returns
User?
: Adds a user.
Since: 1.0.0
Parameters
Returns
User?
: User or undefined if a user with the same name already exists ▸ setCommandPrefix(prefix) Sets the command prefix.
setCommandPrefix(prefix:
string)
Since: 0.14.0
Parameters
prefix (string)
Command prefix
Gets the command prefix.
Since: 0.14.0
Returns
string
: Command prefix Returns the SinusBot version.
Since: 1.0.0
Returns
string
: SinusBot version, for example: 1.0.0-alpha.7-a20212b
Since: 1.0.0
Returns
string
: OS (Operating-System, e.g. "linux") Disables the register command
disableRegistration()
Since: 1.0.0
Enables the register command
enableRegistration()
Since: 1.0.0
Returns whether registration is enabled
Since: 1.0.0-beta.6
Returns
boolean
: true if registration is enabled ▸ getChannelSubscriptions() ▸ getClientSubscriptions() ▸ setSubscriptionMode(bool) Since: 1.0.0-beta.8
Parameters
bool (boolean)
true
to enable subscription-mode,
false
to disable it.
▸ getIgnoreCommandsFromServerChat() getIgnoreCommandsFromServerChat():
boolean Since: 1.0.0-beta.9
Returns
boolean
: wether ignore commands on specific chat has been set ▸ getIgnoreCommandsFromChannelChat() the value of the checkbox from instance settings "ignore commands via channel-chat"
getIgnoreCommandsFromChannelChat():
boolean Since: 1.0.0-beta.9
Returns
boolean
: wether ignore setting has been set or not ▸ getIgnoreCommandsFromPrivateChat() the value of the checkbox from instance settings "ignore commands via private message"
getIgnoreCommandsFromPrivateChat():
boolean Since: 1.0.0-beta.9
Returns
boolean
: wether ignore setting has been set or not ▸ setIgnoreCommandsFromServerChat(bool) set the value of the checkbox from instance settings "ignore commands via server-chat"
setIgnoreCommandsFromServerChat(bool:
boolean)
Since: 1.0.0-beta.9
Parameters
bool (boolean)
reset/set specific setting
▸ setIgnoreCommandsFromChannelChat(bool) set the value of the checkbox from instance settings "ignore commands via channel-chat"
setIgnoreCommandsFromChannelChat(bool:
boolean)
Since: 1.0.0-beta.9
Parameters
bool (boolean)
reset/set specific setting
▸ setIgnoreCommandsFromPrivateChat(bool) set the value of the checkbox from instance settings "ignore commands via private message"
setIgnoreCommandsFromPrivateChat(bool:
boolean)
Since: 1.0.0-beta.9
Parameters
bool (boolean)
reset/set specific setting
store
store
Example
var store = require('store'); store.set('foo', 'bar');
Static Members
Stores a variable under the given key the values stored are only available for the current script, but shared between instances of it
Parameters
value (any)
Value to be stored; must be JSON.stringify()-able
Returns
boolean
: Example
var store = require('store'); store.set('foo', 'bar');
Gets a variable that has been stored previously by set() the values stored are only available for the current script, but shared between instances of it
Parameters
Returns
any
: Stored value - or undefined, if not found Example
var store = require('store'); var foo = store.get('foo');
Deletes a stored variable by its key the values stored are only available for the current script, but shared between instances of it
Parameters
Returns an array of all set keys the values stored are only available for the current script, but shared between instances of it
Returns
Array<string>
: Array of all stored keys Returns all stored items the values stored are only available for the current script, but shared between instances of it
Returns
object
: Keys of this object are the keys of each entry Stores a variable under the given key the values stored are available for every script of every instance
Parameters
value (any)
Value to be stored; must be JSON.stringify()-able
Returns
boolean
: Gets a variable that has been stored previously by set() the values stored are available for every script of every instance
Parameters
Returns
any
: Stored value - or undefined, if not found Deletes a stored variable by its key the values stored are available for every script of every instance
Parameters
Returns an array of all set keys the values stored are available for every script of every instance
Returns
Array<string>
: Array of all stored keys Returns all stored items the values stored are available for every script of every instance
Returns
object
: Keys of this object are the keys of each entry ▸ setInstance(key, value) Stores a variable under the given key the values stored are available only for the current instance of the script (not shared between instances and / or other scripts)
Parameters
value (any)
Value to be stored; must be JSON.stringify()-able
Returns
boolean
: Gets a variable that has been stored previously by set() the values stored are available only for the current instance of the script (not shared between instances and / or other scripts)
Parameters
Returns
any
: Stored value - or undefined, if not found Deletes a stored variable by its key the values stored are available only for the current instance of the script (not shared between instances and / or other scripts)
Parameters
Returns an array of all set keys the values stored are available only for the current instance of the script (not shared between instances and / or other scripts)
Returns
Array<string>
: Array of all stored keys Returns all stored items the values stored are available only for the current instance of the script (not shared between instances and / or other scripts)
Returns
object
: Keys of this object are the keys of each entry
backend
backend
Static Members
Connects to the server
Returns
boolean
: Disconnects from the server
Returns
boolean
: Returns true if the backend is connected to a server
Returns
boolean
: Returns
string
: Current bots' unique identifier Returns
Client
: Client of the bot Returns the actual nickname; To get the configured nickname, use engine.getNick() instead.
Returns
string
: Returns a channel if found
Parameters
Returns
Channel
: Example
var backend = require('backend'); var channel = backend.getChannelByID('6');
Returns the (primary) channel the bot is in
Returns
Channel
: Example
var backend = require('backend'); var channel = backend.getCurrentChannel();
Returns the matching channel if found
Parameters
Returns
Channel?
: Related
Backend#getChannelsByName() Example
var backend = require('backend'); var channel = backend.getChannelByName('Welcome Channel');
▸ getChannelsByName(name) Returns an array of channels matching the name
Since: 0.14.0
Parameters
Returns
Array<Channel>
: Example
var backend = require('backend'); var channels = backend.getChannelsByName('foobar');
Returns the total number of channels
Returns
number
: Example
var backend = require('backend'); var count = backend.getChannelCount();
Returns all channels
Returns
Array<Channel>
: Example
var backend = require('backend'); var engine = require('engine'); var channels = backend.getChannels(); channels.forEach(function(channel) { engine.log(channel.name()); });
Returns all clients
Returns
Array<Client>
: Example
var backend = require('backend'); var clients = backend.getClients(); clients.forEach(function(client) { client.chat('Hello ', + client.name() + '. I\'m a SinusBot!'); });
Returns a client by its temporary ID (changes when the client reconnects)
Parameters
Returns
Client
: Returns a client by its name/nickname
Parameters
Returns
Client
: Alias of getClientByName
Parameters
Returns
Client
: ▸ getClientByUniqueID(uniqueID) Returns an (online) client by its permanent id
Parameters
Returns
Client
: ▸ getClientByUID(uniqueID) Alias of getClientByUniqueID
Parameters
Returns
Client
: Sends a message to the server
Parameters
Example
var backend = require('backend'); backend.chat('Hello from SinusBot!');
▸ createChannel(channelParams) Creates a new channel
Since: 0.9.16.3
Parameters
Returns
Channel
: Channel which was created Returns a servergroup by its ID
Parameters
Returns
ServerGroup
: ▸ getChannelGroupByID(id) Returns a channelgroup by its ID
Parameters
Returns
ChannelGroup
: Returns the specific functions for Discord or TeamSpeak3
Since: 1.0.0-alpha.6
Returns
Extended
: Set the bot client as away on TeamSpeak.
Parameters
Returns
boolean
: success
audio
audio
Static Members
Applies a ffmpeg filter to the audio output.
Warning: This method is curretly not safe to use and leads to crashes!
Parameters
filter (string)
ffmpeg compatible filter string
Returns
boolean
: success ▸ setAudioReturnChannel(flags) Enables or disables audio return channel; required for speech recognition engine / recording
Since: 0.13.37
Parameters
flags (number)
bitmask; use 0x01 for general audio return (recording) or 0x02 for separated audio (for speech recognition) - 0x03 for both
Returns
boolean
: ▸ getAudioReturnChannel() getAudioReturnChannel():
number Since: 0.13.37
Returns
number
: Starts recording to a file
Returns
boolean
: Stops recording to a file
Returns
boolean
: ▸ streamToServer(url, username, password) Streams audio output to an icecast-server
Parameters
url (string)
Endpoint to stream to
username (string)
Username used for authentication
Returns
boolean
: Stops streaming started with streamToServer
Returns
boolean
: Returns the state of repeat-mode
Returns
boolean
: Sets the state of repeat-mode
Parameters
Returns the state of shuffle-mode
Returns
boolean
: Sets the state of shuffle-mode
Parameters
Returns the current volume (0-100)
Returns
number
: volume Sets the volume (0-100)
Parameters
Returns
boolean
: Returns the position of the current track
Returns
number
: position (in seconds) Seeks to a specific position
Parameters
pos (number)
New position (in seconds)
Returns if the audio output has been muted
Returns
boolean
: Enables/disables mute
Parameters
Returns
boolean
: Returns
boolean
: Whether the bot is playing music Plays audio returned from the text-to-speech engine
Parameters
locale (string?)
Locale to use
▸ setStreamVolume(streamID, volume) Sets the volume of a specific stream (0-100)
Parameters
streamID (string)
name or alias of the stream(s) to modify
Returns
boolean
: Sets the TTS URL
Since: 1.0.0-beta.6
Parameters
Returns
boolean
: ▸ setTTSDefaultLocale(locale) Sets the TTS default locale
Since: 1.0.0-beta.6
Parameters
Returns
boolean
:
helpers
helpers
Static Members
Returns a random numbers between zero and
Parameters
Returns
number
: Random number Returns a random permutation of numbers between zero and
Parameters
Returns
Array<number>
: A random permutation of numbers between zero and Creates an empty BytesWriter
Since: 1.0.0
Returns
BytesWriter
: Returns a BytesWriter for a given string
Since: 1.0.0
Parameters
Returns
BytesWriter
: Returns a BytesWriter for a given hex-string
Since: 1.0.0
Parameters
Returns
BytesWriter
: Returns a BytesWriter for a given base64-string
Since: 1.0.0
Parameters
Returns
BytesWriter
: Encodes a string to base64
Parameters
Returns
string
: Decodes a string from base64
Parameters
Returns
string
: Encodes a string to hex
Parameters
Returns
string
: Decodes a string from hex
Parameters
Returns
string
: Generate a hex-encoded MD5 checksum of the given input
Parameters
Returns
string
: Gets the string representation of an object
Deprecated: This function should not be used anymore, if possible.
Parameters
Returns
string
: Returns the documentation of an interface
Parameters
obj (any)
Interface to document
Returns
string
: JSDoc String
event
event
Example
var event = require('event'); var engine = require('engine'); event.on('chat', function(ev) { engine.log('Got message "'+ev.text +'" from '+ ev.client.name()); })
Static Members
▸ on(eventName, callback) Registers an event listener
Parameters
eventName (string)
Event to listen to
callback (function)
Gets called when the given event is triggered
Emits an event to the current instance
Parameters
eventName (string)
Name of the event to be emitted
data (object)
A data object to be sent with the event
▸ broadcast(eventName, data) Emits an event to all instances
Parameters
eventName (string)
Name of the event to be emitted
data (object)
A data object to be sent with the event
Events
Gets fired whenever api: is triggered via the http API. You can trigger this by sending a http request to {sinusbot address}/api/v1/bot/i/{instanceID}/event/{eventName}
with the POST
method and the correct headers. This can only be called by users that are logged in and authenticated via the Authorization
header. For a public api event see public:<your event name>
.
api:eventName
Parameters
Example
event.on('api:logMyFoo', ev => { engine.log(ev.data().foo); }); event.on('api:respondWithSomething', ev => ({ something: 'Hello browser, how are you doing?' }));
function sendDataToScript(instanceID) { $.ajax({ url: '/api/v1/bot/i/' + instanceID + '/event/logMyFoo', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'bearer ' + window.localStorage.token }, data: JSON.stringify({"foo": "bar"}) }); } function requestDataFromScript(instanceID) { $.ajax({ url: '/api/v1/bot/i/' + instanceID + '/event/respondWithSomething', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'bearer ' + window.localStorage.token }, data: '{}' }).done(function (data) { console.log("Response:"); console.log(data); }); }
Gets fired whenever public: is triggered via the http API. You can trigger this by sending a http request to {sinusbot address}/api/v1/b/i/{instanceID}/event/{eventName}
with the POST
method. This is similar to api:<your event name>
with the only difference being that no authentication is required.
public:eventName
Parameters
Example
event.on('public:foobar', ev => { engine.log('Received foobar event from api!'); });
This event gets triggered whenever a chat message has been received. This also counts for messages from the bot itself, so make sure to check.
chat
Parameters
Example
var event = require('event'); var engine = require('engine'); event.on('chat', function(ev) { engine.log('Got message "'+ev.text +'" from '+ ev.client.name()); });
Note: This event is only for discord messages. For both TS3 and Discord messages use the chat event.
This event gets triggered whenever a discord message has been received.
message
Parameters
Example
var event = require('event'); event.on('message', msg => { msg.createReaction('👍'); });
Gets fired whenever the bot is poked
poke
Parameters
Example
var event = require('event'); var engine = require('engine'); event.on('poke', function(msg) { engine.log('Got poke message "' + msg.text + '" from ' + msg.client.name()); });
Gets fired whenever a client starts typing in a chat with the bot
typing
Parameters
client (Client)
Client that started typing
Gets fired whenever a new track starts
track
Parameters
Gets fired whenever a track changes its information (like radio stations)
trackInfo
Parameters
Gets fired whenever a track has stopped playing
trackEnd
Parameters
callback (string)
Callback string
Gets fired whenever a track was successfully downloaded via ytdl
ytdl.success
Parameters
Name | Description |
ev.url string | YouTube URL |
ev.jobId string | Job ID |
ev.trackId string? | Track ID (only when downloaded) |
Example
event.on("ytdl.success", ev => { engine.log(`Successfully downloaded a YouTube Video: ${ev.url}, jobId: ${ev.jobId}, trackId: ${ev.trackId}`) })
Gets fired whenever a download via ytdl fails
ytdl.error
Parameters
Name | Description |
ev.url string | YouTube URL |
ev.jobId string | Job ID |
message (string)
Error Message
Example
event.on("ytdl.error", (ev, message) => { engine.log(`Error while downloading a YouTube Video: ${ev.url}, jobId: ${ev.jobId}, message: ${message}`) })
Gets fired whenever a connection with the server has been established
connect
Gets fired whenever the client is unable to connect to a server
connectionFailed
Parameters
Gets fired whenever the bots connection to the server is closed
disconnect
Gets fired whenever a client moves, joins or disconnects
clientMove
Parameters
Gets fired whenever a clients nickname is changed
clientNick
Parameters
Gets fired whenever a client becomes visible to the bot
clientVisible
Parameters
Gets fired whenever a client becomes invisible to the bot
clientInvisible
Parameters
Gets fired whenever a client gets kicked from the server
clientKicked
Parameters
▸ clientKickedFromChannel Gets fired whenever a client gets kicked from a channel
clientKickedFromChannel
Parameters
Gets fired whenever a clients IP address changes or has initially been fetched
clientIPAddress
Parameters
Gets fired whenever a client sets himself as away
clientAway
Parameters
Gets fired whenever a client removes himself as away
clientBack
Parameters
Gets fired whenever a client starts recording
clientRecord
Parameters
Gets fired whenever a client stops recording
clientRecordStop
Parameters
Gets fired whenever a client mutes his microphone
clientMute
Parameters
Gets fired whenever a client unmutes his microphone
clientUnmute
Parameters
Gets fired whenever a client mutes his sound
clientDeaf
Since: 0.9.18
Parameters
Gets fired whenever a client unmutes his sound
clientUndeaf
Since: 0.9.18
Parameters
Gets fired whenever a client is banned from a TS server
clientBanned
Since: 1.0.0-beta.6
Parameters
message (string)
the ban reason
invoker (Client)
user which created the ban
fromChannel (Channel)
the channel the client was in
client (Client)
user which has been banned
time (number)
the bantime in seconds
Gets fired whenever a client got added to a server group
serverGroupAdded
Parameters
Gets fired whenever a client got removed from a server group
serverGroupRemoved
Parameters
Gets fired whenever a channel is created
channelCreate
Parameters
channel (Channel)
Channel that got created
invoker (Client)
Client that created the channel
Gets fired whenever a channel is updated
channelUpdate
Parameters
channel (Channel)
Channel that got updated
invoker (Client)
Client that updated the channel
Gets fired whenever a channel is deleted
channelDelete
Parameters
channel (Channel)
Channel that got deleted
invoker (Client)
Client that deleted the channel
▸ clientConnectionInfoUpdate gets fired when a client connection info gets updated
clientConnectionInfoUpdate
Since: 1.0.0-beta.10
Parameters
client (Client)
the client which got updated
This event gets triggered whenever the bot recognizes a voice command that the script registered, assuming: 1) SpeechRecognition was installed 2) SpeechRecognition is enabled in the config.ini 3) The voice command was registered by the script in registerPlugin 4) AudioReturnChannel is set to 2
Check out the documentation for reqirements and instructions on how to install it.
speech
Since: 0.13.37
Parameters
Name | Description |
ev.client Client | Client |
ev.text string | Recognized text |
Example
var event = require('event'); var engine = require('engine'); var audio = require('audio'); audio.setAudioReturnChannel(2) event.on('speech', function(ev) { engine.log('Got speech command "' + ev.text + '" from ' + ev.client.name()); });
Gets fired whenever the number of users that are currently talking in the channel changes
talkerCount
Parameters
number (number)
Number of users that are currently talking in the channel
Gets fired whenever the script is going to be unloaded or reloaded; use this to clean up or save stuff
unload
Gets fired when all scripts have been loaded
load
This event gets triggered whenever a discord event got received. Every event will be emitted in uppercase and the spaces will be replaced by underscores. All available discord events can be found in the discord documentation
discord:eventName
Parameters
ev (object)
Discord event data
Example
var event = require('event'); var engine = require('engine'); event.on('discord:GUILD_CREATE', function (ev) { engine.log('GUILD_CREATE' + JSON.stringify(ev)); });
ws.connect
Since: 0.9.20
Parameters
id (string)
ID of the new connection
Related
ws ws.close
Since: 0.9.20
Parameters
id (string)
ID of the closed connection
Related
ws ws.error
Since: 0.9.20
Parameters
id (string)
ID of the connection
Related
ws ws.data
Since: 0.9.20
Parameters
id (string)
ID of the connection
type (number)
Type of the message
Related
ws
http
This module is protected. This means that you need to add 'http'
to requiredModules
in your script's Manifest in registerPlugin in order to use it - like shown here:
registerPlugin({ name: 'Demo http basic Script', version: '1.0.0', description: 'This example script sends a http request.', author: 'Author <author@example.com>', requiredModules: ['http'], vars: [] }, (_, config, meta) => { const engine = require('engine'); const http = require('http'); http.simpleRequest({ 'method': 'GET', 'url': 'https://example.com', 'timeout': 6000, }, function (error, response) { if (error) { engine.log("Error: " + error); return; } if (response.statusCode != 200) { engine.log("HTTP Error: " + response.status); return; } engine.log("Response: " + response.data.toString()); }); });
Examples can be found under simpleRequest.
http
Static Members
▸ simpleRequest(config, callback) Creates an http request
Since: 0.14.2
Parameters
config (object)
http configuration object
Name | Description |
config.method string? | Request Method to use (eg GET, POST, PUT, ...) |
config.url string | The URL endpoint which should be called |
config.timeout number? | timeout in milliseconds |
config.body string? | request body |
config.headers object? | request header |
Example
registerPlugin({ name: 'Demo http basic Script', version: '1.0.0', description: 'This example script sends a http request.', author: 'Author <author@example.com>', requiredModules: ['http'], vars: [] }, (_, config, meta) => { const engine = require('engine'); const http = require('http'); http.simpleRequest({ 'method': 'GET', 'url': 'https://example.com', 'timeout': 6000, }, function (error, response) { if (error) { engine.log("Error: " + error); return; } if (response.statusCode != 200) { engine.log("HTTP Error: " + response.status); return; } engine.log("Response: " + response.data.toString()); }); });
registerPlugin({ name: 'Demo http basic Script', version: '1.0.0', description: 'This example script sends a http request and sends+receives json data.', author: 'Author <author@example.com>', requiredModules: ['http'], vars: [] }, (_, config, meta) => { const engine = require('engine'); const http = require('http'); var sendData = JSON.stringify({ foo: 'bar' }); http.simpleRequest({ 'method': 'POST', 'url': 'https://example.com', 'timeout': 6000, 'body': sendData, 'headers': { 'Content-Type': 'application/json', 'Content-Length': sendData.length } }, function (error, response) { if (error) { engine.log("Error: " + error); return; } if (response.statusCode != 200) { engine.log("HTTP Error: " + response.status); return; } var res; try { res = JSON.parse(response.data.toString()); } catch (err) { engine.log(err.message); } if (res === undefined) { engine.log("Invalid JSON."); return; } engine.log(res); });
net
This module is protected. This means that you need to add 'net'
to requiredModules
in your script's Manifest in registerPlugin in order to use it.
The net module allows you to connect to any TCP/UDP port or ws (websocket) and send raw data. If you just need to send a http request then you should definitely use the http module instead.
net
Since: 0.9.16
Example
const engine = require('engine'); const net = require('net'); const conn = net.connect({ host: '127.0.0.1', port: 80 }, err => { if (err) { engine.log(err); } }); conn.on('data', data => { engine.log('received data'); engine.log(data.toString()); }) if (conn) { conn.write("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"); } else { engine.log('connection unavailable'); }
Static Members
▸ connect(params, callback) Parameters
Returns
NetClient?
: Client connection, or null if failed to setup a connection (e.g. wrong parameters; null does not mean that the connection failed, instead that it is handled in the callback)
ws
This module is protected. This means that you need to add 'ws'
to requiredModules
in your script's Manifest in registerPlugin in order to use it.
The ws module allows you to start a websocket server. If you want to connect to a websocket server instead then take look at the net module.
Please consider using http api events for simple communications instead, as they are simpler and also allow you to require authentication; See api:<your event name>
and public:<your event name>
for more.
ws
Since: 0.9.20
Example
const engine = require('engine'); const event = require('event'); const ws = require('ws'); event.on('ws.connect', id => { engine.log('new websocket connection; id ' + id); ws.broadcast(1, { blubb: 'blubb' }); }); event.on('ws.disconnect', id => { engine.log('websocket connection disconnected; id ' + id); }); event.on('ws.data', (id, type, data) => { engine.log('ws.data: id ' + id + '; data: ' + data.toString()); ws.write(id, type, data.toString()); });
var proto = (window.location.protocol == 'https:') ? 'wss' : 'ws'; var conn = new WebSocket(proto + "://" + document.location.host + "/api/v1/b/" + botId + "/i/" + instanceId + "/ws"); conn.onclose = function (evt) { console.log('close', evt); alert('Closed.'); }; conn.send(JSON.stringify({ type: 'ping' })); conn.onmessage = function (evt) { var data = JSON.parse(evt.data); };
Static Members
▸ write(connectionId, messageType, message) Writes some data to the connection with given connectionId
Parameters
message ((string | Bytes))
Actual message; can be given as string or byteshelper
▸ broadcast(messageType, message) Broadcasts some data to all connected clients
Parameters
message ((string | Bytes))
Actual message; can be given as string or byteshelper
Closes the connection
Parameters
db
This module is protected. This means that you need to add 'db'
to requiredModules
in your script's Manifest in registerPlugin in order to use it.
Use additional parameters to exec / query whenever you use untrusted/unknown data, as those will automatically be escaped and avoid SQL injection.
db
Since: 0.9.16.4
Related
DBConn Example
var db = require('db'); var engine = require('engine'); var helpers = require('helpers'); function parseString(numberBuffer) { if (!Array.isArray(numberBuffer)) return ""; const bytewriter = helpers.newBytes(); numberBuffer.forEach(num => bytewriter.append(helpers.bytesFromHex(num.toString(16)))); return bytewriter.toString(); } var dbc = db.connect({ driver: 'mysql', host: '127.0.0.1', username: 'demo', password: 'blah', database: 'foo' }, function(err) { if (err) { engine.log(err); } }); if (dbc) dbc.exec("INSERT INTO blah (foo, foo2) VALUES (?, ?)", 'bar', 'bar2'); if (dbc) dbc.query("SELECT * FROM blah", function(err, res) { if (!err) { res.forEach(function(row) { engine.log(parseString(row.foo)); }); } else { engine.log(err); } });
Static Members
▸ connect(params, callback) Parameters
callback (dbConnectCallback)
Callback gets called on success / error; If an error occured, exactly one parameter containing the error will be handed to the callback
Returns
DBConn?
: Database connection or null if failed
fs
This module is protected. This means that you need to add 'fs'
to requiredModules
in your script's Manifest in registerPlugin in order to use it.
fs
Since: 1.0.0
Static Members
Checks if a file exists
Since: 1.0.0
Parameters
path (string)
Path to the file (for example
/var/www/html/foo.txt
)
Returns
boolean
: Reads the content of a file
Since: 1.0.0
Parameters
path (string)
Path to the file
Returns
Bytes
: ▸ writeFile(path, data, mode) Writes data to a file
Since: 1.0.0
Parameters
path (string)
Path to the file
data (BytesWriter)
Data as Bytes, e.g. created by
helpers.bytesFromString()
or similar functions
Returns
boolean
: success Returns information about a file
Since: 1.0.0
Parameters
path (string)
Path to the file
Returns
FileInfo
: FileInfo Returns information about all files in a dirictory
Since: 1.0.0
Parameters
path (string)
Path to the directory
Returns
Array<FileInfo>
: Array of FileInfo Deletes a file or directory
Since: 1.0.0
Parameters
path (string)
Path to the file or directory
Returns
boolean
: success Creates a directory
Since: 1.0.0
Parameters
path (string)
Path of the directory
Returns
boolean
: success Creates every missing directory in a path
Since: 1.0.0
Parameters
path (string)
Path of the directory
Returns
boolean
: success Deletes a file or directory
Since: 1.0.0
Parameters
path (string)
Path to the file or directory
newPath (string)
New path to the file or directory
Returns
boolean
: success
graphics
This module is protected. This means that you need to add 'graphics'
to requiredModules
in your script's Manifest in registerPlugin in order to use it.
The best example on how to use the graphics module is the Avatar banner script by Filtik.
graphics
Since: 0.14.2
Static Members
Removes the banner.
Returns
boolean
: success ▸ setBanner(filename, bannerSettings, callback) Setbanner sets the avatar of the sinusbot client.
Parameters
filename (string)
filename without ending
Returns
boolean
: success Example
graphics.setBanner('banner', { "format": "png", "width": 260, "height": 120, "layers": [ ] }, function() { engine.setAvatarFromBanner('banner.png'); });
crypto
crypto
Since: 1.0.0
Static Members
▸ pbkdf2(hname, password, salt, iterations, keylength) Parameters
password (BytesWriter)
The master password from which a derived key is generated.
iterations (number)
Number of iterations.
keylength (number)
Desired bit-length of the derived key.
Returns
BytesWriter
: Keypair bytes Returns a given number of random bytes.
Parameters
number (number)
Number of random bytes to return
Returns
BytesWriter
: Random bytes
Client
Note: if the client is inivisible to the bot, some fields might not be available.
Client
Instance Members
Returns
string
: Name/nickname of the client Alias of name()
Returns
string
: Name/nickname of the client Returns
string
: Phonetic name of the client; useful for tts Returns
string
: Temporary ID of the client Returns
string
: Unique ID of the client Alias of uid()
Deprecated: Please use uid() instead.
Returns
string
: Unique ID of the client Returns
string
: TeamSpeak database ID of the client Alias of databaseID()
Returns
string
: TeamSpeak database ID of the client Returns
string
: Country of the client Returns
string
: Description of the client ▸ setDescription(description) Since: 0.9.19
Parameters
Returns
boolean
: success Returns true when this client is the bot itself
Returns
boolean
: Returns if the client is recording the conversation
Returns
string
: Returns if the client is muted (has its microphone disabled)
Returns
boolean
: Returns if the client is deaf (has its loudspeakers disabled)
Returns
boolean
: Returns if the client is away
Returns
boolean
: Returns the clients' away message (if set)
Returns
string
: Returns the clients' last ping time (latency)
Returns
number
: Returns the clients' ip address (if available)
Returns
string
: Returns the clients' online time (requires special permissions)
Returns
number
: in milliseconds Returns the clients' current idle time (requires special permissions)
Returns
number
: in milliseconds Returns the clients' packet loss percentage (requires special permissions)
Returns
number
: Returns the clients' amount of received data (requires special permissions)
Returns
number
: Returns the clients' amount of sent data (requires special permissions)
Returns
number
: Returns the total number of connections from that client On TS3, this information has to be actively requested from the server. If the bot is unable to get it or hasn't received an answer in time, it will return <= 0 here.
Returns
number
: Returns the time the client has been created / was first seen by the server On TS3, this information has to be actively requested from the server. If the bot is unable to get it or hasn't received an answer in time, it will return <= 0 here.
Returns
number
: Returns an array of all channels the client is in; even if TS only uses one channel for a client at a time, other backends might provide several
Returns
Array<Channel>
: Array of channels Returns
Channel
: Current audio channel the client is in Returns the TS3 client URL in the format client://0/uid~nickname
. On discord it returns an @-mention in the format <@uid>
.
Returns
string
: Client URL / mention Compares two clients
Parameters
Returns
boolean
: true, if both clients are the same Sends a message to the client
Parameters
Returns
boolean
: success Example
var backend = require('backend'); var client = backend.getClientByName('Bob'); client.chat('Hello, ' + client.name());
Pokes the client with a message
Parameters
Example
var backend = require('backend'); var client = backend.getClientByName('Bob'); client.chat('Pokeypoke, ' + client.name() + '!');
Bans a client
Parameters
time (number)
Amount of time (in seconds) the ban should last (-1 for permanent)
Example
var backend = require('backend'); var client = backend.getClientByName('Bob'); client.ban(100, 'See you in 100 seconds, ' + client.name() + '!');
Kicks the client from the server
Parameters
Kicks the client from the server
Parameters
Kicks the client from the channel
Parameters
▸ addToServerGroup(group) Adds a client to a specific ServerGroup
Parameters
▸ removeFromServerGroup(group) Removes a client from a specific ServerGroup
Parameters
▸ moveTo(target, password?) Moves a client to another channel
*Note: This can also be used to disconnect a discord bot-instance from the voice chat with backend.getBotClient().moveTo('')
.
Parameters
target ((Channel | string))
Channel the client should be moved to
password (string?)
Password for the target channel, if required
Enables / disables subscription for this client; requires subscription mode
Parameters
Returns the version of the client
Returns
string
: version ▸ requestConnectionInfoUpdate() Forces an update on the client
requestConnectionInfoUpdate():
boolean Since: 1.0.0-beta.10
Returns
boolean
: Returns the client type (Query=0; Normal=1)
Returns
string
: client type
Channel
Channel
Instance Members
Returns
Channel?
: Parent of channel or null if none is set Since: 0.9.16.3
Returns
number
: Order / position of this channel. For ts3 this is a numeric value determining the order in which channels are displayed below their parent. To set a new value, please use moveTo. delete the current channel
Since: 0.9.17
Returns
boolean
: Moves the channel to a new parent with a new position value
Since: 0.9.16.3
Parameters
order (number)
New order value
Returns
number
: Type (0 = voice, 1 = text) Since: 0.9.19
Returns
string
: Description ▸ setDescription(description) setDescription(description:
string)
Since: 0.9.16
Parameters
▸ setCodecQuality(quality) setCodecQuality(quality:
number)
Since: 0.9.16
Parameters
Returns
number
: Configured number of clients the channel can hold (-1 if unlimited) ▸ setMaxClients(maxClients) setMaxClients(maxClients:
number)
Since: 0.9.16
Parameters
maxClients (number)
Set to -1 for unlimited clients
▸ setMaxFamilyClients(maxFamilyClients) setMaxFamilyClients(maxFamilyClients:
number)
Since: 0.9.16
Parameters
Returns
boolean
: Whether channel is permanent or not ▸ setPermanent(permanent) Returns
boolean
: Whether channel is semi-permanent or not ▸ setSemiPermanent(permanent) setSemiPermanent(permanent:
boolean)
Since: 0.9.16
Parameters
Returns
boolean
: Whether channel is the default one Parameters
bool (boolean)
Whether channel is the default one
Returns
boolean
: Whether channel is password-protected or not Returns
boolean
: Whether channel is encrypted or not ▸ setEncrypted(encrypted) Compares two channels
Parameters
Returns
boolean
: True, if both channels are the same Sends a chat message to the channel
Parameters
Returns
boolean
: success Returns
Array<Client>
: Clients that are in this channel Returns
number
: Number of clients that are in the channel enables / disables subscription for this channel; requires subscription mode
Parameters
Updates multiple channel parameters at once
Since: 0.9.16.3
Parameters
▸ setChannelGroup(client, channelGroup) Assigns a client to a channel group
Since: 0.9.18
Parameters
Gets the permissions for the channel from the server - this is an expensive call as the permissions are not cached
Since: 0.13.37
Returns
Array<Permission>
: Adds/sets a new permission on the channel; you need to use the setters and then call save() to apply - can also be used to remove a permission by delete() afterwards
Since: 0.13.37
Parameters
id (string)
id of the permission to add; can also be supplied as name like i_channel_needed_join_power
Returns
Permission
: ▸ getMessages(params, callback)
User
User
Instance Members
Returns the ID of the user
Since: 0.13.37
Returns
string
: ID of the User Returns the name of the user
Since: 0.13.37
Returns
string
: Name of the User Returns the privileges of the user
Since: 0.13.37
Returns
number
: Privileges of the user Example
const ENQUEUE = 1 << 13; const SKIP_QUEUE = 1 << 14; const ADMIN_QUEUE = 1 << 15; const PLAYBACK = 1 << 12; const START_STOP = 1 << 8; const EDIT_BOT_SETTINGS = 1 << 16; const LOGIN = 1 << 0; const UPLOAD_FILES = 1 << 2; const DELETE_FILES = 1 << 3; const EDIT_FILES = 1 << 4; const CREATE_AND_DELETE_PLAYLISTS = 1 << 5; const EDIT_PLAYLISTS = 1 << 7; const EDIT_INSTANCES = 1 << 17; const EDIT_USERS = 1 << 9; function hasPlaybackPermission(user) { return (user.privileges() & PLAYBACK) != 0 }
Returns the instance privileges of the user
Since: 1.0.0-beta.9
Returns
number
: Instance privileges of the user Related
privileges Since: 0.13.37
Returns
string
: teamspeak or discord unique ID if bound to a client Related
uid Since: 1.0.0-alpha.6
Returns
string
: teamspeak or discord unique ID if bound to a client Related
tsUid Since: 0.13.37
Returns
string
: Group ID if bound to a teamspeak group or discord role Related
groupId Since: 1.0.0-alpha.6
Returns
string
: Group ID if bound to a teamspeak group or discord role Related
tsGroupId Checks if an user is an admin
Since: 0.13.37
Returns
boolean
: Admin status of the user Sets a new password to the user
Since: 0.13.37
Parameters
password (string)
new password of the user
Returns
boolean
: Success or not Sets the teamspeak/discord unique ID
Since: 0.13.37
Parameters
uid (string)
teamspeak/discord unique ID of the client
Returns
boolean
: Success or not Related
setUid Sets the teamspeak/discord unique ID
Since: 1.0.0-beta.9
Parameters
uid (string)
teamspeak/discord unique ID of the client
Returns
boolean
: Success or not Related
setTSUid Sets the group ID
Since: 1.0.0-alpha.6
Parameters
groupId (string)
teamspeak group ID or discord role ID
Returns
boolean
: Success or not ▸ setPrivileges(privileges) Sets the users privileges
Since: 0.13.37
Parameters
privileges (number)
New privileges of the user
Returns
boolean
: Success or not ▸ addPrivilege(privilege) Adds a privilege to a user
Since: 0.13.37
Parameters
privilege (number)
New privilege which should be added
Returns
boolean
: Success or not ▸ removePrivilege(privilege) Removes a privilege from a user
Since: 0.13.37
Parameters
privilege (number)
Privilege which should be removed
Returns
boolean
: Success or not ▸ setInstancePrivileges(privileges) Sets the users instance privileges
Since: 1.0.0-beta.9
Parameters
privileges (number)
New privileges of the user
Returns
boolean
: Success or not ▸ addInstancePrivilege(privilege) Adds an instance privilege to a user
Since: 1.0.0-beta.9
Parameters
privilege (number)
New privilege which should be added
Returns
boolean
: Success or not ▸ removeInstancePrivilege(privilege) Removes an instance privilege from a user
Since: 1.0.0-beta.9
Parameters
privilege (number)
Privilege which should be removed
Returns
boolean
: Success or not Deletes an user
Since: 0.13.37
Returns
boolean
: Success or not
Permission
handles channel, channelgroup and servergroup permissions; mainly for TS3
Permission
Since: 0.13.37
Instance Members
Since: 0.13.37
Returns
string
: ID of the permission Since: 0.13.37
Returns
string
: Name of the permission Since: 0.13.37
Returns
number
: permission value Since: 0.13.37
Returns
boolean
: true, if skip flag has been set - only applicable for ServerGroups Since: 0.13.37
Returns
boolean
: true, if negated flag has been set - only applicable for ServerGroups sets the value of the permission; you need to call save() to apply changes
Since: 0.13.37
Parameters
value (boolean)
true, if permission should be negated, false otherwise
Returns
boolean
: sets the skip flag - only applicable for ServerGroups; you need to call save() to apply changes
Since: 0.13.37
Parameters
value (boolean)
true, if permission should be skipped, false otherwise
Returns
boolean
: sets the negated flag - only applicable for ServerGroups; you need to call save() to apply changes
Since: 0.13.37
Parameters
value (number)
new value for the permission
Returns
boolean
: applies the changed settings
Since: 0.13.37
Returns
boolean
: delete the current permission
Since: 0.13.37
Returns
boolean
:
ChannelGroup
ChannelGroup
Instance Members
Returns
string
: ID of the channel group Returns
string
: Name of the channel group Since: 0.12.0
Returns
string
: ID of the icon used for the channel group Gets the permissions for the channelgroup from the server - this is an expensive call as the permissions are not cached
Since: 0.13.37
Returns
Array<Permission>
: Adds/sets a new permission to the channelgroup; you need to use the setters and then call save() to apply - can also be used to remove a permission by delete() afterwards
Since: 0.13.37
Parameters
id (string)
id of the permission to add; can also be supplied as name like i_channel_needed_join_power
Returns
Permission
:
ServerGroup
ServerGroup
Instance Members
Returns
string
: ID of the server group Returns
string
: Name of the server group Since: 0.12.0
Returns
string
: ID of the icon used for the channel group ▸ addClientByDatabaseId(client) Adds a client by database ID to the servergroup
Since: 0.13.37
Parameters
Returns
boolean
: status if the request was successful ▸ removeClientByDatabaseId(client) Removes a client by database ID from the servergroup
Since: 0.13.37
Parameters
Returns
boolean
: status if the request was successful Gets the permissions for the servergroup from the server - this is an expensive call as the permissions are not cached
Since: 0.13.37
Returns
Array<Permission>
: Adds/sets a new permission to the servergroup; you need to use the setters and then call save() to apply - can also be used to remove a permission by delete() afterwards
Since: 0.13.37
Parameters
id (string)
id of the permission to add; can also be supplied as name like i_channel_needed_join_power
Returns
Permission
:
Bytes
Bytes
Since: 0.9.16
Instance Members
Returns
string
: String representation of the bytes
BytesWriter
BytesWriter
Since: 0.9.16
Instance Members
Returns
string
: String representation of the bytes Parameters
int8 (number)
Write 8-bit integer.
Parameters
int16 (number)
Write 16-bit integer as big-endian.
Parameters
int16 (number)
Write 16-bit integer as little-endian.
Parameters
int32 (number)
Write 32-bit integer as big-endian.
Parameters
int32 (number)
Write 32-bit integer as little-endian.
Parameters
int64 (number)
Write 64-bit integer as big-endian.
Parameters
int64 (number)
Write 64-bit integer as little-endian.
Parameters
uint8 (number)
Write unsigned 8-bit integer.
Parameters
uint16 (number)
Write unsigned 16-bit integer as big-endian.
Parameters
uint16 (number)
Write unsigned 16-bit integer as little-endian.
Parameters
uint32 (number)
Write unsigned 32-bit integer as big-endian.
Parameters
uint32 (number)
Write unsigned 32-bit integer as little-endian.
Parameters
uint64 (number)
Write unsigned 64-bit integer as big-endian.
Parameters
uint64 (number)
Write unsigned 64-bit integer as little-endian.
PlaylistTrack
Track in a Playlist
PlaylistTrack
Instance Members
Returns
string
: Title of the track Returns
string
: Artist of the track Returns
string
: Album of the track Returns
string
: Url of the track (internal or external) Starts playback of the track
Returns
boolean
: success
Track
Track
Instance Members
Returns
string
: Unique ID of the track Returns
string
: Unique url for the track Returns
string
: Type of the file Returns
string
: Title of the track Returns
string
: Artist of the track Returns
string
: Temporary title of the track; e.g. when playing radio stations Returns
string
: Temporary artist of the track; e.g. when playing radio stations Returns
string
: Album of the track Since: 0.9.16
Returns
string
: Genre of the track Since: 0.9.16
Returns
number
: Duration of the track (in milliseconds) Since: 0.9.16
Returns
number
: Tracknumber of the track Returns
string
: Path to the thumbnail, if any Returns
string
: Original filename Starts playback of the track
Returns
boolean
: success Adds the track to the queue
Returns
boolean
: success Adds the track as the first entry in the queue
Returns
boolean
: success ▸ setThumbnailFromURL(url) Downloads a thumbnail from the internet and stores it for the given track
setThumbnailFromURL(url:
string)
Parameters
url (string)
Url to download the thumbnail from (limited to X MB)
Removes the thumbnail of a track
removeThumbnail()
Since: 1.0.0-beta2
Returns
string
:
ApiEvent
This type is passed to a (api|public):<eventName>
-event, see api:<eventName>
or public:<eventName>
for more.
ApiEvent
Instance Members
Returns
string
: Name of the event Returns
User?
: User that called the event (or null, if unset) Returns
string
: Remote address that triggered the call Since: 0.14
Returns
object
: Key/Value map of the query parameters in the url
Playlist
Playlist
Instance Members
Returns
string
: Unique identifier of the playlist Returns
string
: Name of the playlist Sets the playlist to active; will continue playing songs from this playlist
Returns
boolean
:
NetClient
NetClient
Since: 0.9.16
Instance Members
Sends data over the connection
Parameters
bytes ((string | Bytes | Array<number>))
Data that should be sent over the socket; one can also send an array of ints / bytes like [0, 255, 1, 1]
format (string?)
Optional, if given bytes will be decoded prior to sending; Can be either "hex" or "base64".
Registers a new event handler
Parameters
event (string)
Name of the event to listen to
Closes the current connection
close()
Events
Gets fired whenever data is received
data
Parameters
Gets fired whenever the connection is closed
close
Gets fired whenever an error occurred
error
Parameters
DBConn
DBConn
Since: 0.9.16.4
Instance Members
▸ query(queryString, parameters?, callback) ▸ exec(queryString, parameters?, callback?) Use this insted of query if you don't expect a result
Parameters
parameters (any?)
Zero or more parameters; e.g. for mysql, ? in the queryString will be replaced with these parameters
FileInfo
FileInfo
Since: 1.0.0
Instance Members
Since: 1.0.0
Returns
string
: Base name of the file Since: 1.0.0
Returns
string
: Length in bytes for regular files; system-dependent for others Since: 1.0.0
Returns
Date
: Modification time Since: 1.0.0
Returns
boolean
: Returns if the file is a directory
DiscordMessage
Parameter of the message event callback.
DiscordMessage
Instance Members
Returns
Client
: Client that sent the message. Returns
string
: ID of the client that sent the message. Returns
Channel
: Channel in which the message was posted. Returns
string
: ID of the channel in which the message was posted. Returns
string
: Content/Text of the message. ▸ createReaction(emoji, callback?) Create a reaction for the message. emoji
takes the form of name:id
for custom guild emoji, or Unicode characters.
Requires the READ_MESSAGE_HISTORY
permission. Additionally, if nobody else has reacted to the message using this emoji, this requires the ADD_REACTIONS
permission to be present on the current user.
Parameters
emoji (string)
Emoji in the form of
name:id
for custom guild emoji, or Unicode character.
Returns
boolean
: success Related
https://discordapp.com/developers/docs/resources/channel#create-reaction Deletes the message.
Parameters
Returns
boolean
: success ▸ deleteAllReactions(callback?) ▸ deleteOwnReaction(emoji, callback?) Delete a reaction the bot has made for the message.
Parameters
emoji (string)
Emoji in the form of
name:id
for custom guild emoji, or Unicode character.
Returns
boolean
: success ▸ deleteUserReaction(emoji, user, callback?) Delete a reaction that a given user has made for the message.
Since: 1.0.0-beta.2
Parameters
emoji (string)
Emoji in the form of
name:id
for custom guild emoji, or Unicode character.
Returns
boolean
: success ▸ editContent(content, callback?) Edits the content/text of the message.
Parameters
Returns
boolean
: success Returns
string
: ID of the guild the message was sent in. Returns
string
: ID of the Message. Returns
boolean
: Whether this was a TTS message. Posts a message in the same channel/chat that the original message was sent in.
Parameters
Returns
boolean
: success Returns
Date
: Timestamp when this message was sent. Returns
Date
: Timestamp when this message was edited (same as timestamp() if never).
ExtendedDiscord
ExtendedDiscord
Since: 1.0.0-alpha.6
Instance Members
▸ getGuild(guildId, callback) Retrieves info about the specific Guild
Since: 1.0.0-alpha.6
Parameters
guildId (string)
the guild id of which the info should be retrieved
▸ modifyGuild(guildId, guildObject, callback?) Modifys the guild
Since: 1.0.0-alpha.6
Parameters
Sends a presence or status update.
Since: 1.0.0-alpha.6
Parameters
Name | Description |
status.game object? | Activity |
status.game.name string? | Activity's name |
status.game.type number? | Activity's type: 0 (game), 1 (streaming), 2 (listening) |
status.game.url string? | Only https://twitch.tv/ urls work. |
status.status string | Status Type . Either online, dnd, idle, invisible or offline. |
status.afk boolean | Whether or not the client is afk. |
status.since number? | Unix time (in milliseconds) of when the client went idle, or null if the client is not idle. |
Related
https://discordapp.com/developers/docs/topics/gateway#update-status Example
const backend = require("backend") backend.extended().setStatus({ since: 0, game: { name: "hide and seek", type: 0, }, status: "online", afk: false })
const backend = require("backend") backend.extended().setStatus({ since: 0, game: {}, status: "dnd", afk: false })
▸ getChannel(channelId, callback) ▸ modifyChannel(channelId, data, callback?) ▸ deleteChannel(channelId, callback?) ▸ getChannelMessages(channelId, callback) Returns the messages for a channel. If operating on a guild channel, this endpoint requires the VIEW_CHANNEL
permission to be present on the current user. If the current user is missing the READ_MESSAGE_HISTORY
permission in the channel then this will return no messages (since they cannot read the message history).
Since: 1.0.0-alpha.6
Parameters
Related
https://discordapp.com/developers/docs/resources/channel#get-channel-messages ▸ getChannelMessage(channelId, callback) ▸ createMessage(channelId, data, callback?) Post a message to a guild text or DM channel. If operating on a guild channel, this endpoint requires the SEND_MESSAGES permission to be present on the current user. If the tts field is set to true, the SEND_TTS_MESSAGES
permission is required for the message to be spoken.
Since: 1.0.0-alpha.6
Parameters
Related
https://discordapp.com/developers/docs/resources/channel#create-message ▸ rawCommand(method, path, data, callback?) Sends a raw http request to the discord API and therefore allows potentially unsafe and arbitrary API calls. Check the discord documentation for available API calls.
Important: In previous SinusBot versions (1.0.0-beta.6 or older) this method was protected and only works if requiredModules: ['discord-dangerous']
is set in the script manifest.
Since: 1.0.0-alpha.6
Parameters
data (object)
Data (JSON Object)
ExtendedTS3
ExtendedTS3
Since: 1.0.0-alpha.6
Instance Members
Retrieves TeamSpeak Server Info
Since: 1.0.0-alpha.6
Returns
TeamSpeakServerInfo
: TeamSpeakServerInfo Object for current server ▸ requestExtendedServerInfo()
TeamSpeakServerInfo
TeamSpeakServerInfo
Since: 1.0.0-alpha.6
Instance Members
Since: 1.0.0-alpha.6
Returns
string
: server name Since: 1.0.0-alpha.6
Returns
string
: server uid Since: 1.0.0-alpha.6
Returns
string
: welcome message Note: Currently does not work; only returns 0
.
Since: 1.0.0-alpha.6
Returns
number
: version of the server Since: 1.0.0-alpha.6
Returns
string
: host message Since: 1.0.0-alpha.6
Returns
string
: banner url Since: 1.0.0-alpha.6
Returns
string
: gfx url of the banner ▸ hostBannerGFXInterval() hostBannerGFXInterval():
number Since: 1.0.0-alpha.6
Returns
number
: banner gfx interval in seconds Since: 1.0.0-alpha.6
Returns
string
: phoenetic server name Since: 1.0.0-alpha.6
Returns
number
: teamspeak server id Since: 1.0.0-alpha.6
Returns
number
: server icon id Since: 1.0.0-alpha.6
Returns
number
: amount of reserved slots Since: 1.0.0-alpha.6
Returns
number
: id of the default server group Since: 1.0.0-alpha.6
Returns
number
: id of the default channel group ▸ defaultChannelAdminGroup() defaultChannelAdminGroup():
number Since: 1.0.0-alpha.6
Returns
number
: id of the default channel admin group Retrieves the Encryption Mode of the server
Since: 1.0.0-alpha.6
Returns
number
: encryption mode (perChannel=0; GlobalOff=1; GlobalOn=2) Since: 1.0.0-alpha.6
Returns
number
: server creation timestamp Retrieve the raw object
Since: 1.0.0-alpha.6
Returns
object
: serverinfo as stringifyable object
TeamSpeakExtendedServerInfo
See backend.extended().requestExtendedServerInfo().
TeamSpeakExtendedServerInfo
Since: 1.0.0-alpha.6
Instance Members
Since: 1.0.0-alpha.6
Returns
number
: max clients which are allowed to connect to the server Since: 1.0.0-alpha.6
Returns
number
: amount of clients which are connected to the server Since: 1.0.0-alpha.6
Returns
number
: amount of created channels on the server Since: 1.0.0-alpha.6
Returns
number
: server uptime in seconds complainAutobanCount():
number Since: 1.0.0-alpha.6
Returns
number
: how many complains a client needs to have until he gets banned Since: 1.0.0-alpha.6
Returns
number
: autoban duration Since: 1.0.0-alpha.6
Returns
number
: seconds of when a complain gets removed ▸ minClientsInChannelBeforeForcedSilence() minClientsInChannelBeforeForcedSilence():
number Since: 1.0.0-alpha.6
Returns
number
: number of clients need to be connected to a channel until all get silenced (enforces talkpower) ▸ antifloodPointsTickReduce() Anti-Flood: Amount of reduced points per tick.
antifloodPointsTickReduce():
number Since: 1.0.0-alpha.6
Returns
number
: ▸ antifloodPointsNeededCommandBlock() Anti-Flood: Points needed for commands block.
antifloodPointsNeededCommandBlock():
number Since: 1.0.0-alpha.6
Returns
number
: ▸ antifloodPointsNeededIPBlock() Anti-Flood: Points needed for IP block.
antifloodPointsNeededIPBlock():
number Since: 1.0.0-alpha.6
Returns
number
: Amount of client connections.
Since: 1.0.0-alpha.6
Returns
number
: ▸ queryClientConnections() Amount of query client connections.
queryClientConnections():
number Since: 1.0.0-alpha.6
Returns
number
: Since: 1.0.0-alpha.6
Returns
number
: amount of query clients connected to the server Since: 1.0.0-alpha.6
Returns
number
: voiceservers port Since: 1.0.0-alpha.6
Returns
number
: wether the server is set to autostart or not Since: 1.0.0-alpha.6
Returns
string
: ▸ neededIdentitySecurityLevel() neededIdentitySecurityLevel():
number Since: 1.0.0-alpha.6
Returns
number
: needed security level to connect to the server Since: 1.0.0-alpha.6
Returns
number
: wether logging for clients actions is enabled Since: 1.0.0-alpha.6
Returns
number
: wether logging for query actions is enabled Since: 1.0.0-alpha.6
Returns
number
: wether logging for channel changes is enabled Since: 1.0.0-alpha.6
Returns
number
: wether logging for permissions changes is enabled Since: 1.0.0-alpha.6
Returns
number
: wether logging for server actions is enabled Since: 1.0.0-alpha.6
Returns
number
: wether logging for filetransfer actions is enabled Since: 1.0.0-alpha.6
Returns
number
: minimum client version needed to connect ▸ maxDownloadTotalBandwidth() maxDownloadTotalBandwidth():
number Since: 1.0.0-alpha.6
Returns
number
: max download bandwith which is allowed for filetransfer ▸ maxUploadTotalBandwidth() maxUploadTotalBandwidth():
number Since: 1.0.0-alpha.6
Returns
number
: max upload bandwith which is allowed for filetransfer Since: 1.0.0-alpha.6
Returns
number
: maximum bytes which are able to be downloaded via filetransfer Since: 1.0.0-alpha.6
Returns
number
: maximum bytes which are able to be uploaded via filetransfer monthBytesDownloaded():
number Since: 1.0.0-alpha.6
Returns
number
: amount of bytes which have been downloaded this month Since: 1.0.0-alpha.6
Returns
number
: amount of bytes which have been uploaded this month totalBytesDownloaded():
number Since: 1.0.0-alpha.6
Returns
number
: total amount of bytes which have been downloaded Since: 1.0.0-alpha.6
Returns
number
: total amount of bytes which have been uploaded Retrieve the raw object
Since: 1.0.0-alpha.6
Returns
object
: serverinfo as stringifyable object
CryptoKeypair
CryptoKeypair
Since: 1.0.0
Instance Members
Returns Keypair bytes.
Returns
BytesWriter
: Keypair bytes
Message
Message
Type: object
Properties
text (string)
: Text of the message
channel (Channel)
: Channel (if given) this message has been sent on
client (Client)
: Client that sent the message
mode (number)
: Number representing the way this message has been sent (1 = private, 2 = channel, 3 = server)
MoveInfo
MoveInfo
Type: object
Properties
fromChannel (Channel?)
: Old channel (or undefined if the client just got online/changed visibility)
toChannel (Channel?)
: New channel (or undefined if the client just went offline/changed visibility)
client (Client)
: Client that was moved
invoker (Client)
: Client that invoked the move
message (string?)
: move/ban/kick message (TS3; since 1.0.0-beta.6)
ChannelParams
Used to update or create a channel; When creating a channel parent and name are mandatory for TS3; When updating a channel parent will be ignored (use moveTo instead)
ChannelParams
Type: object
Properties
name (string)
: Displayname of the channel; mandatory on create
parent ((Channel | number | string))
: Parent channel (you can also use the channelId); ignored on update, mandatory on create
codec (number)
: See codec types for explanation
encrypted (boolean)
:
true
by default
maxClients (number)
: Set to
-1
for unlimited clients
default (boolean)
: Whether the channel is the default channel
neededTalkPower (number)
: TS3 only
deleteDelay (number)
: TS3 only
ClientServerGroupEvent
ClientServerGroupEvent
Type: object
Properties
client (Client)
: Client that has been added / removed
invoker (Client)
: Client that added client to the group
NetConnectParams
NetConnectParams
Type: object
Since: 0.9.16
Properties
host (string?)
: Host to connect to; required for mysql / postgres
url (string?)
: WebSocket URL to use
protocol (string?)
: can be udp, tcp or ws (websocket)
DBParams
DBParams
Type: object
Since: 0.9.16
Properties
driver (string)
: Database driver to use, sqlite3 (default; currently in-memory only), mysql or postgres
host (string?)
: Database server to connect to, required for mysql / postgres
BannerSettings
BannerSettings
Type: object
Since: 0.14.2
Properties
BannerLayer
BannerLayer
Type: object
Since: 0.14.2
simpleRequestCallback
Type: Function
Since: 0.14.2
Parameters
Name | Description |
response.data Bytes | Data; Needs to be converted to a string first, e.g. response.data.toString() . |
response.headers object | Headers |
response.status string | Status |
response.statusCode number | Status Code |
Related
module:http#simpleRequest
netConnectCallback
If an error occured, exactly one parameter containing the error will be handed to the callback.
netConnectCallback(error:
string?)
Type: Function
Since: 0.9.16
Parameters
Related
module:net#connect
dbConnectCallback
If an error occured, exactly one parameter containing the error will be handed to the callback
dbConnectCallback(error:
string?)
Type: Function
Since: 0.9.16.4
Parameters
Related
module:db#connect
dbQueryCallback
Gets called with two parameters, err and result - both are mutually exclusive. Result contains an array of rows, each containing an object with the column names as key.
Type: Function
Since: 0.9.16.4
Parameters
Related
DBConn#query DBConn#exec