Deprecated: Use of "parent" in callables is deprecated in /var/www/html/forum/src/vendor/league/flysystem-eventable-filesystem/src/EventableFilesystem.php on line 431
  • If you need help or want to discuss things, you now can also join us on our Discord Server!
  • A first preview of the unlimited version of SinusBot can be found in the Upcoming Changes thread. A version for Windows will follow, but we don't have a release date, yet.

EN Usage of ForEach Loop

Status
Not open for further replies.

r3flex

Active Member
Contributor
How do I implement the foreach iteration?
I use the following code but unfortunately doesnt work, any ideas?
<code> // Gets a list of all clients and sends them a message
var backend = require('backend');
var clients = backend.getClients();
clients.forEach(function(client) {
client.chat('Hello ', + client.Name() + '. I'm a SinusBot!');
});
</code>
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
First of all, what does you mean with "doesn't work"? No output, An error? Wrong output?

Because your string looks odd with this , in it and the tripple ' on the 2nd part of your string [ '. I'm a SinusBot!')]

Normally the code should look like this:

client.chat("Hello " + client.Name() + ". I'm a SinusBot!");

This stops the compiler confusing from the I'm
 

r3flex

Active Member
Contributor
Im just giving the raw example from official sinusbot docs, and yes I know I about the '.
No output, it should say hello to my every client on ts3 but meanwhile it doesnt my full code is:

registerPlugin({
name: 'DB Ranks',
version: '2.0',
description: 'This plugin will let the bot greet everyone.',
author: 'Michael Friese <[email protected]>',
vars: [{
name: 'message',
title: 'The message that should be displayed. (%n = nickname)',
type: 'string'
}, {
name: 'type',
title: 'Message-Type',
type: 'select',
options: [
'Private chat',
'Poke'
]
}]
}, function(sinusbot, config) {

var db = require('db');
var engine = require('engine');
var backend = require('backend');

var dbc = db.connect({ driver: 'mysql', host: '127.0.0.1', username: 'root', password: '123', database: 'ts3' }, function(err) {
if (err) { engine.log(err); }
});

var clients = backend.getClients();
clients.forEach(function(client) {
client.chat('Hello ', + client.Name() + '. Im a SinusBot!');
var Uid = "123";

dbc.exec('INSERT INTO czas (uid) VALUES (?)', Uid);

});
});

There is no new input into the DB and it doesn't send the messages to the client.
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
ah.. yeah ofc you arent using it in an event

This code gets fired, but only when you press the save button in the script page. So when the bot isn't connected yet, nothing wil happen (because getClient() is empty.

You can check with an engine.log("Number of clients founds: " + clients.length); after your filled the clients var

To get it fired for every new conencted client you need something liek this:

Code:
var event = require('event');

//fires every time a client connect and ONLY messages THE CONNECTED client.
event.on('clientMove', function(ev){
  if(!ev.fromChannel){
     ev.client.chat("Hello " + client.Name() + ". I'm a SinusBot!");
  }
}

//messages every client online once, when the BOT CONNECTS
event.on('connect', function(){
  backend.getClients().forEach(function(client){
     ev.client.chat("Hello " + client.Name() + ". I'm a SinusBot!");
  });
}
 

r3flex

Active Member
Contributor
Wierd, thought my script would work when I start the sinusbot, just like it did when I set up simple DB insertions which actually worked.
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
Wierd, thought my script would work when I start the sinusbot, just like it did when I set up simple DB insertions which actually worked.
Mh then dunno, maybe I'm overseeing something. But normally what I said should be the case.

Dose also nothing happen when you click on save script setting while the bot is connected?
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
yep, like I said. The scripts gets loaded when the bot boots up, but the backend cant get the clients, because the bot isnt online yet
 

r3flex

Active Member
Contributor
My main goal is to create TS3 DB Ranks, my main concept is to make the script refresh every x interval and add the time difference to the overall time spent in DB, then assign a server group to the client based on how many hrs he spent on srv.
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
How about starting an

Code:
setInterval(functionToExecute, NUMBER_OF_MILLISECONDS_BETWEEN_EXECUTIONS);

setInterval(testfunction, 5000);

via the connect#event

Remember, you can also work with client.getOnlineTime(). Which returns the amount of time the client is online in milliseconds. https://www.sinusbot.com/docs/scripting/#Client#getOnlineTime
So you don't need to work with the interval or iteration times or so, because it sounded like you want to do it like that.
 

r3flex

Active Member
Contributor
I want to use client.getOnlineTime(). but also I have to run the script every x time again to update the DB right?
I thought the sinus script runs on event and if there isn't an firing event e.g( event.on('client.move',) ) cuz that seems impractical for me, sometimes client dont actually that often.
I wanted a interval to run the same script to update the DB, get info of the clients online time and parse it into DB.
 

Diesmon

Tuetchen Dominator
is awesome!
Contributor
Insider
did you read what I said?
I gave you a solution to run the code every x secondes. Just start a javascript interval via setInterval(x,y) https://www.w3schools.com/jsref/met_win_setinterval.asp

And the best place to start it is in the bot connect event (after the bot actually connected to a server).
Or start it in the normal code, but then you could have "logic" errors depending on what you are doing exactly in there, because unless the bot isn't connect the clients and stuff are just empty arrays.
 

r3flex

Active Member
Contributor
Now I have yet another problem, I do not have a clue how to check if the db entry already exists.
I did this code but unfortunately it doesn't work as expected.

Code:
if (dbc) dbc.query('SELECT * FROM czas WHERE uid = (?)', Uid, function(err, res) {
if (!err) {
var exists = res.forEach(function(row) {
result = row.uid;
return result;
});
}
});

If there are existing entries it outputs them correctly (if I add an engine.log function), but the variable doesn't change to true or false which would've been my solution.
 

r3flex

Active Member
Contributor
Thanks it actually works now! :)
Code:
if (dbc) dbc.query('SELECT * FROM czas WHERE uid = (?)', Uid, function(err, res) {

     if (!res.length) {
        dbc.exec('INSERT INTO czas (nick, uid, czas) VALUES (?, ?, ?)', Nick, Uid, Seconds);
        engine.log("Inserted");
     } else {
        dbc.exec('UPDATE czas SET czas = (?) WHERE uid = (?)', Seconds, Uid);
        engine.log("Updated");
     } 
});
 

r3flex

Active Member
Contributor
I want to calculate the difference between db executions, but the problem is when client disconnects the variable TimeStamp wont reset which will endup in false results.
Code:
var clients = backend.getClients();
clients.forEach(function loop(client) {

    var Nick = client.nick();
    var Uid = client.uid();
    var Time = client.getOnlineTime();
    if (TimeStamp != null) {
        var TrueTime = Math.abs(Time) - TimeStamp;
    } else {
        var TrueTime = Math.abs(Time);
    }
    var Seconds = (TrueTime/1000000);
    var Minutes = (Seconds/60);
    var Hours = (Minutes/60);
    var TimeStamp = client.getOnlineTime();

if (dbc) dbc.query('SELECT * FROM czas WHERE uid = (?)', Uid, function select(err, res) {

if (!err) res.forEach(function(row) { });

     if (!res.length) {
        dbc.exec('INSERT INTO czas (nick, uid, czas) VALUES (?, ?, ?)', Nick, Uid, Seconds);
        engine.log("Inserted " + Nick); 
     } else {
        dbc.exec('UPDATE czas SET czas = czas + (?) WHERE uid = (?)', Seconds, Uid);
        engine.log("Updated " + Nick);
     }  
});
});
 
Status
Not open for further replies.
Top