SinusBot Scripting Engine

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.

generic

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.

registerPlugin(manifest: Manifest, mainFunction: mainFunction)
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) {
    // your code goes here
});

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

mainFunction(_: object?, config: object, meta: Manifest)

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
getInstanceID()
getBotID()
getBackend()
setInstanceLogLevel(level)
setBotLogLevel(level)
getInstanceLogLevel()
getBotLogLevel()
reloadScripts()
getNick()
setNick(nick)
getDefaultChannelID()
setDefaultChannelID(channelID)
isRunning()
notify(message)
saveConfig(config)
log(something)
logf(format, something)
export(obj)
removeAvatar()
setAvatarFromTrack(track)
setDefaultAvatar()
setAvatarFromBanner(bannerName)
setAvatarFromURL(url)
getUsers()
getUserById(id)
getUserByName(name)
addUser(username)
setCommandPrefix(prefix)
getCommandPrefix()
version()
os()
disableRegistration()
enableRegistration()
registrationEnabled()
isSubscriptionMode()
getChannelSubscriptions()
getClientSubscriptions()
setSubscriptionMode(bool)
getIgnoreCommandsFromServerChat()
getIgnoreCommandsFromChannelChat()
getIgnoreCommandsFromPrivateChat()
setIgnoreCommandsFromServerChat(bool)
setIgnoreCommandsFromChannelChat(bool)
setIgnoreCommandsFromPrivateChat(bool)

store

store
Example
var store = require('store');
store.set('foo', 'bar');
Static Members
set(key, value)
get(key)
unset(key)
getKeys()
getAll()
setGlobal(key, value)
getGlobal(key)
unsetGlobal(key)
getKeysGlobal()
getAllGlobal()
setInstance(key, value)
getInstance(key)
unsetInstance(key)
getKeysInstance()
getAllInstance()

backend

backend
Static Members
connect()
disconnect()
isConnected()
getBotClientID()
getBotClient()
getNick()
getChannelByID(id)
getCurrentChannel()
getChannelByName(name)
getChannelsByName(name)
getChannelCount()
getChannels()
getClients()
getClientByID(id)
getClientByName(name)
getClientByNick(name)
getClientByUniqueID(uniqueID)
getClientByUID(uniqueID)
chat(msg)
createChannel(channelParams)
getServerGroupByID(id)
getChannelGroupByID(id)
getServerGroups()
getChannelGroups()
extended()
setAway(away, reason)

media

media
Static Members
playURL(url)
getCurrentTrack()
getTrackByID(id)
getTracks()
search(searchString)
enqueue(url)
playAsNext(url)
playNext()
playPrevious()
stop(trackID?)
getQueue()
getPlaylists()
getPlaylistByID(id)
getActivePlaylist(id)
removeFromQueue(index)
clearQueue()
clearPlaylist()
yt(url)
ytStream(url)
ytdl(url, play)
enqueueYt(url)
enqueueYtdl(url)
playQueueNext()
resumeQueue()
clearIdleTrack()
clearStartupTrack()
setIdleTrackURL(url)
setStartupTrackURL(url)
playlistPlayByID(playlist, index)

audio

audio
Static Members
setAudioFilter(filter)
setAudioReturnChannel(flags)
getAudioReturnChannel()
startRecording()
stopRecording()
streamToServer(url, username, password)
stopStream()
isRepeat()
setRepeat(val)
isShuffle()
setShuffle(val)
getVolume()
setVolume(volume)
getTrackPosition()
seek(pos)
isMute()
setMute(mute)
isPlaying()
say(text, locale?)
setStreamVolume(streamID, volume)
setTTSURL(url)
setTTSDefaultLocale(locale)

format

format
Static Members
color(text, color)
italic(text)
bold(text)
underline(text)
code(text)

helpers

helpers
Static Members
getRandom(max)
getRandPerm(max)
newBytes()
bytesFromString(value)
bytesFromHex(value)
bytesFromBase64(value)
base64Encode(input)
base64Decode(input)
hexEncode(input)
hexDecode(input)
MD5Sum(input)
SHA1Sum(input)
SHA256Sum(input)
toString(obj)
document(name, obj)

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)
emit(eventName, data)
broadcast(eventName, data)
Events
api:eventName
public:eventName
chat
message
poke
typing
track
trackInfo
trackEnd
ytdl.success
ytdl.error
connect
connectionFailed
disconnect
clientMove
clientNick
clientVisible
clientInvisible
clientKicked
clientKickedFromChannel
clientIPAddress
clientAway
clientBack
clientRecord
clientRecordStop
clientMute
clientUnmute
clientDeaf
clientUndeaf
clientBanned
serverGroupAdded
serverGroupRemoved
channelCreate
channelUpdate
channelDelete
clientConnectionInfoUpdate
speech
talkerCount
unload
load
discord:eventName
ws.connect
ws.close
ws.error
ws.data
serverinfo_int

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>',
    //...
    // define the protected modules that you require:
    requiredModules: ['http'],
    //...
    vars: []
}, (_, config, meta) => {
    const engine = require('engine');
    // and then you can require and use the module in here:
    const http = require('http');
    
    // send request
    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;
        }
        
        // success!
        engine.log("Response: " + response.data.toString());
    });
});

Examples can be found under simpleRequest.

http
Static Members
simpleRequest(config, callback)

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');

// connect to a tcp port
const conn = net.connect({
    host: '127.0.0.1',
    port: 80
}, err => {
    // log connection errors if any
    if (err) {
        engine.log(err);
    }
});

// start listening for data
conn.on('data', data => {
    engine.log('received data');
    engine.log(data.toString());
})

// write data if connection is available
if (conn) {
    // write data
    conn.write("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n");
} else {
    engine.log('connection unavailable');
}
Static Members
connect(params, 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
// ### SinusBot script: ###

const engine = require('engine');
const event = require('event');
const ws = require('ws');

// listen for connections
event.on('ws.connect', id => {
    engine.log('new websocket connection; id ' + id);
    // broadcast data to all connected clients
    ws.broadcast(1, { blubb: 'blubb' });
});
// listen for disconnections
event.on('ws.disconnect', id => {
    engine.log('websocket connection disconnected; id ' + id);
});
// listen for data
event.on('ws.data', (id, type, data) => {
    engine.log('ws.data: id ' + id + '; data: ' + data.toString());
    // respond with data
    ws.write(id, type, data.toString());
});
// ### Client Side (served html files via the enableWeb script option): ###

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)
broadcast(messageType, message)
close(connectionId)

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');

// see https://forum.sinusbot.com/threads/mysql-varchar-returned-as-array-of-ascii-chars.7459/#post-42918
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)

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
exists(path)
readFile(path)
writeFile(path, data, mode)
stat(path)
readDir(path)
remove(path)
mkDir(path)
mkDirAll(path)
rename(path, newPath)

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
removeBanner()
setBanner(filename, bannerSettings, callback)

crypto

crypto
Since: 1.0.0
Static Members
generateKeypair()
loadKeypair(keypair)
seal(secret, message)
open(secret, message)
pbkdf2(hname, password, salt, iterations, keylength)
randomBytes(number)

interfaces

Client

Note: if the client is inivisible to the bot, some fields might not be available.

Client
Instance Members
name()
nick()
phoneticName()
id()
uid()
uniqueId()
databaseID()
databaseId()
country()
description()
setDescription(description)
isSelf()
isRecording()
isMuted()
isDeaf()
isAway()
getServerGroups()
getChannelGroup()
getAwayMessage()
getPing()
getIPAddress()
getOnlineTime()
getIdleTime()
getPacketLoss()
getBytesReceived()
getBytesSent()
getTotalConnections()
getCreationTime()
getChannels()
getAudioChannel()
getURL()
equals(otherClient)
chat(msg)
poke(msg)
ban(time, msg)
kick(msg)
kickFromServer(msg)
kickFromChannel(msg)
addToServerGroup(group)
removeFromServerGroup(group)
moveTo(target, password?)
subscribe(val)
getPlatform()
getVersion()
requestConnectionInfoUpdate()
type()

Channel

Channel
Instance Members
id()
name()
parent()
position()
setPosition(pos)
delete()
moveTo(parent, order)
setName(name)
type()
topic()
setTopic(topic)
description()
setDescription(description)
codec()
setCodec(codec)
codecQuality()
setCodecQuality(quality)
maxClients()
setMaxClients(maxClients)
maxFamilyClients()
setMaxFamilyClients(maxFamilyClients)
isPermanent()
setPermanent(permanent)
isSemiPermanent()
setSemiPermanent(permanent)
isDefault()
setDefault(bool)
isPassworded()
setPassword(password)
isEncrypted()
setEncrypted(encrypted)
equals(otherChannel)
chat(msg)
getClients()
getClientCount()
subscribe(val)
update(channelParams)
setChannelGroup(client, channelGroup)
getPermissions()
addPermission(id)
getURL()
getMessages(params, callback)

User

User
Instance Members
id()
name()
privileges()
instancePrivileges()
tsUid()
uid()
tsGroupId()
groupId()
isAdmin()
setPassword(password)
setTSUid(uid)
setUid(uid)
setGroupId(groupId)
setPrivileges(privileges)
addPrivilege(privilege)
removePrivilege(privilege)
setInstancePrivileges(privileges)
addInstancePrivilege(privilege)
removeInstancePrivilege(privilege)
delete()

Permission

handles channel, channelgroup and servergroup permissions; mainly for TS3

Permission
Since: 0.13.37
Instance Members
id()
name()
value()
skip()
negated()
setNegated(value)
setSkip(value)
setValue(value)
save()
delete()

ChannelGroup

ChannelGroup
Instance Members
id()
name()
icon()
getPermissions()
addPermission(id)

ServerGroup

ServerGroup
Instance Members
id()
name()
icon()
addClientByDatabaseId(client)
removeClientByDatabaseId(client)
getPermissions()
addPermission(id)

Bytes

Bytes
Since: 0.9.16
Instance Members
bytes()
string(length)
cString()
int16be()
int16le()
int32be()
int32le()
length()
pos()
seek(pos)
toBase64()
toHex()
toString()
uint8()
uint16be()
uint16le()
uint32be()
uint32le()

BytesWriter

BytesWriter
Since: 0.9.16
Instance Members
append(bytes)
bytes()
length()
newReader()
toBase64()
toHex()
toString()
writeString(str)
writeCString(str)
writeInt8(int8)
writeInt16be(int16)
writeInt16le(int16)
writeInt32be(int32)
writeInt32le(int32)
writeInt64be(int64)
writeInt64le(int64)
writeUint8(uint8)
writeUint16be(uint16)
writeUint16le(uint16)
writeUint32be(uint32)
writeUint32le(uint32)
writeUint64be(uint64)
writeUint64le(uint64)

PlaylistTrack

Track in a Playlist

PlaylistTrack
Instance Members
title()
artist()
album()
url()
play()

Track

Track
Instance Members
id()
url()
type()
title()
artist()
tempTitle()
tempArtist()
album()
genre()
duration()
trackNumber()
thumbnail()
filename()
play()
enqueue()
addNext()
setThumbnailFromURL(url)
removeThumbnail()
sourceURL()

ApiEvent

This type is passed to a (api|public):<eventName>-event, see api:<eventName> or public:<eventName> for more.

ApiEvent
Instance Members
name()
data()
user()
remoteAddr()
queryParams()

Playlist

Playlist
Instance Members
id()
name()
getTracks()
setActive()

NetClient

NetClient
Since: 0.9.16
Instance Members
write(bytes, format?)
on(event, callback)
close()
Events
data
close
error

DBConn

DBConn
Since: 0.9.16.4
Instance Members
query(queryString, parameters?, callback)
exec(queryString, parameters?, callback?)

FileInfo

FileInfo
Since: 1.0.0
Instance Members
name()
size()
mode()
modTime()
isDir()

DiscordMessage

Parameter of the message event callback.

DiscordMessage
Instance Members
author()
authorID()
channel()
channelID()
content()
createReaction(emoji, callback?)
delete(callback?)
deleteAllReactions(callback?)
deleteOwnReaction(emoji, callback?)
deleteUserReaction(emoji, user, callback?)
editContent(content, callback?)
guildID()
ID()
isTTS()
reply(text, callback?)
timestamp()
timestampEdited()

Extended

Either ExtendedDiscord or ExtendedTS3

Extended
Related
{ExtendedDiscord} {ExtendedTS3}

ExtendedDiscord

ExtendedDiscord
Since: 1.0.0-alpha.6
Instance Members
getGuild(guildId, callback)
modifyGuild(guildId, guildObject, callback?)
setStatus(status)
getChannel(channelId, callback)
modifyChannel(channelId, data, callback?)
deleteChannel(channelId, callback?)
getChannelMessages(channelId, callback)
getChannelMessage(channelId, callback)
createMessage(channelId, data, callback?)
rawCommand(method, path, data, callback?)

ExtendedTS3

ExtendedTS3
Since: 1.0.0-alpha.6
Instance Members
getServerInfo()
requestExtendedServerInfo()

TeamSpeakServerInfo

TeamSpeakServerInfo
Since: 1.0.0-alpha.6
Instance Members
name()
uid()
welcomeMessage()
platform()
version()
hostMessage()
hostBannerURL()
hostBannerGFXURL()
hostBannerGFXInterval()
hostButtonURL()
hostButtonGFXURL()
namePhonetic()
serverID()
iconID()
reservedSlots()
defaultServerGroup()
defaultChannelGroup()
defaultChannelAdminGroup()
codecEncryptionMode()
created()
asObject()

TeamSpeakExtendedServerInfo

See backend.extended().requestExtendedServerInfo().

TeamSpeakExtendedServerInfo
Since: 1.0.0-alpha.6
Instance Members
maxClients()
clientsOnline()
channelsOnline()
uptime()
complainAutobanCount()
complainAutobanTime()
complainRemoveTime()
minClientsInChannelBeforeForcedSilence()
antifloodPointsTickReduce()
antifloodPointsNeededCommandBlock()
antifloodPointsNeededIPBlock()
clientConnections()
queryClientConnections()
queryClientsOnline()
port()
autostart()
machineID()
neededIdentitySecurityLevel()
logClient()
logQuery()
logChannel()
logPermissions()
logServer()
logFiletransfer()
minClientVersion()
maxDownloadTotalBandwidth()
maxUploadTotalBandwidth()
downloadQuota()
uploadQuota()
monthBytesDownloaded()
monthBytesUploaded()
totalBytesDownloaded()
totalBytesUploaded()
asObject()

CryptoKeypair

CryptoKeypair
Since: 1.0.0
Instance Members
export()
sharedKey(something)

types

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
description (string)
topic (string)
password (string)
codec (number) : See codec types for explanation
codecQuality (number)
encrypted (boolean) : true by default
permanent (boolean)
semiPermanent (boolean)
position (number)
maxClients (number) : Set to -1 for unlimited clients
maxFamilyClients (number)
default (boolean) : Whether the channel is the default channel
neededTalkPower (number) : TS3 only
deleteDelay (number) : TS3 only
icon (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
serverGroup (ServerGroup) : Server Group

NetConnectParams

NetConnectParams

Type: object

Since: 0.9.16
Properties
host (string?) : Host to connect to; required for mysql / postgres
port (number?) : Port to use
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
username (string?)
password (string?)
port (number?)

BannerSettings

BannerSettings

Type: object

Since: 0.14.2
Properties
format (string) : e.g. "png"
width (number)
height (number)
layers (Array<BannerLayer>)

BannerLayer

BannerLayer

Type: object

Since: 0.14.2

callbacks

simpleRequestCallback

simpleRequestCallback(error: string?, response: object?)

Type: Function

Since: 0.14.2
Parameters
error (string?)
response (object?)
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
error (string?)
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
error (string?)
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.

dbQueryCallback(error: string?, result: Array<object>?)

Type: Function

Since: 0.9.16.4
Parameters
error (string?)
result (Array<object>?)
Related
DBConn#query DBConn#exec