Git Product home page Git Product logo

turntable-api's Introduction

Turntable API


Join us on Discord https://discord.gg/4AA2DqWpVc


A simple nodejs wrapper for the turntable API. You'll need to find your AUTH, USERID and ROOMID information with this bookmarklet.

Ttapi is also available in Python and Ruby.

See also turntabler (Ruby) maintained by obrie.

Installation

npm install ttapi

Examples

Chat bot

This bot responds to anybody who writes "/hello" in the chat.

var Bot = require('ttapi');
var bot = new Bot(AUTH, USERID, ROOMID);

bot.on('speak', function (data) {
  // Respond to "/hello" command
  if (data.text.match(/^\/hello$/)) {
    bot.speak('Hey! How are you @'+data.name+' ?');
  }
});

Logger

This bot logs the room activity in the console.

var Bot    = require('ttapi');
var AUTH   = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var USERID = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var ROOMID = 'xxxxxxxxxxxxxxxxxxxxxxxx';

var bot = new Bot(AUTH, USERID);

bot.on('ready',        function (data) { bot.roomRegister(ROOMID); });
bot.on('roomChanged',  function (data) { console.log('The bot has changed room.', data); });

bot.on('speak',        function (data) { console.log('Someone has spoken', data); });
bot.on('update_votes', function (data) { console.log('Someone has voted',  data); });
bot.on('registered',   function (data) { console.log('Someone registered', data); });

Dynamic bot

REPL allows you to dynamically call the bot functions and modify his variables during his execution.

var Bot  = require('ttapi')
  , repl = require('repl');

var bot = new Bot(AUTH, USERID, ROOMID);
repl.start('> ').context.bot = bot;

// ...

Debugging

bot.debug = true;

That will print on the terminal all the data that you get and all the data that you send.

Hosting

  • https://c9.io/ : Free (up to 128MB memory/storage) hosting for nodejs-based projects with full SSH access, FTP, and unlimited collaborators.
  • https://openshift.redhat.com/ : Free (up to 1.5GB memory/3GB storage) Git-based PaaS service that supports nodejs with limited SSH access.
  • http://www.heroku.com/ : Free (up to 1 dyno/512MB memory/200MB storage) Git-based PaaS service that supports nodejs with a easy-to-use frontend.
  • http://nodester.com/ : Free (unlimited applications/50GB transfer/up to 2GB memory) PaaS service that supports nodejs and comes with easy deployment options.
  • https://modulus.io/ : Cheap (scaleable memory not to be abused) nodejs hosting with $25 credit for a limited time.
  • http://www.nodejitsu.com/ : Cheap (scaleable memory/storage not to be abused) hosting for nodejs-based projects.

Documentation

Events

Here are some examples of the data that you'll receive from those events.

on('ready', function ( ) { })

Triggered when the bot is connected. Do not attempt to use any actions until you receive this event.

on('error', function (error:Error) { })

Triggered when attempting to connect using an invalid roomid.

Warning

If you do not handle this event, your bot will stop running when this error occurs.

on('disconnected', function (error:Error) { })

Triggered on recoverable connection errors.

Note

If you do not handle this event, an error event will be triggered when the connection to Turntable is lost.

on('tcpConnect', function (socket) { })

Triggered when a socket opens a connection.

on('tcpMessage', function (socket, msg) { })

Triggered when the bot receives a TCP message.

on('tcpEnd', function (socket) { })

Triggered when a socket closes its connection.

on('httpRequest', function (request, response) { })

Triggered when the bot receives an HTTP request.

on('roomChanged', function (data) { })

Triggered when the bot enters a room.

on('registered', function (data) { })

Triggered when a user enters the room.

on('deregistered', function (data) { })

Triggered when a user leaves the room.

on('speak', function (data) { })

Triggered when a new message is sent via the chat.

on('endsong', function (data) { })

Triggered at the end of the song. (Just before the newsong/nosong event)

The data returned by this event contains information about the song that has just ended.

on('newsong', function (data) { })

Triggered when a new song starts.

on('nosong', function (data) { })

Triggered when there is no song.

on('update_votes', function (data) { })

Triggered when a user votes.

Note

The userid is provided only if the user votes up, or later changes their mind and votes down.

on('booted_user', function (data) { })

Triggered when a user gets booted.

on('update_user', function (data) { })

Triggered when a user updates their name/profile.

on('add_dj', function (data) { })

Triggered when a user takes a dj spot.

on('rem_dj', function (data) { })

Triggered when a user leaves a dj spot.

on('escort', function (data) { })

Triggered when a user is escorted off the stage.

on('new_moderator', function (data) { })

Triggered when a user is promoted to a moderator.

on('rem_moderator', function (data) { })

Triggered when a user loses their moderator title.

on('snagged', function (data) { })

Triggered when a user queues the currently playing song.

on('pmmed', function (data) { })

Triggered when the bot receives a private message.

Actions

tcpListen ( port, address )

Start a TCP server.

listen ( port, address )

Start an HTTP server.

roomNow ( [callback:fn] )

Get the Turntable server time.

listRooms ( skip=0:int [, callback:fn] )

Get 20 rooms.

searchRooms( [options:obj, ]callback:fn )

Search the directory for rooms.

options
  • limit - The number of rooms to return
  • query - Filter based on this search term

directoryGraph ( callback:fn )

Get the location of your friends/idols.

directoryRooms( options:obj, callback:fn )

Get a directory of rooms.

options
  • limit - The number of rooms to return
  • section_aware
  • sort - What to sort by,
  • skip - The number of rooms to skip

stalk ( userId:string [, allInformation=false:bool ], callback:fn )

Get the location of a user. If allInformation is true, you'll also receive the information about the room and the user.

Warning

This function will make you become a fan of the user.

getFavorites ( callback:fn )

Get your favorite rooms.

addFavorite ( roomId:string [, callback:fn ] )

Add a room to your favorite rooms.

remFavorite ( roomId:string [, callback:fn ] )

Remove a room from your favorite rooms.

roomRegister ( roomId:string [, callback:fn] )

Register in a room.

roomDeregister ( [callback:fn] )

Deregister from the current room.

roomInfo ( [[extended=true:bool, ]callback:fn] )

Get the current room information. Do not include song log if 'extended' is false.

speak ( msg:string [, callback:fn] )

Broadcast a message in the chat.

bootUser ( userId:string, reason:string [, callback:fn] )

Boot a user.

boot ( userId:string, reason:string [, callback:fn] )

Alias of bootUser().

addModerator ( userId:string [, callback:fn] )

Add a moderator.

remModerator ( userId:string [, callback:fn] )

Remove a moderator. (Note the person does NOT have to be in the room to remove their moderator status.)

addDj ( [callback:fn] )

Add yourself as a DJ.

remDj ( [[userId:string, ]callback:fn] )

Remove the specified DJ, or yourself if not specified.

stopSong ( [callback:fn] )

Stop the currently playing song. You must be a moderator to stop playing someone else's song.

skip ( [callback:fn] )

Alias of stopSong().

vote ( val:enum('up', 'down') [, callback:fn] )

Vote for the current song.

bop ( )

Alias of vote('up').

userAuthenticate ( [callback:fn] )

Authenticate the user.

userInfo ( [callback:fn] )

Get the current user's information.

userAvailableAvatars ( callback:fn )

Get all available avatars.

getAvatarIds ( callback:fn )

Get the avatar ids that you can currently use.

getFanOf ( [[userId:string, ]callback:fn )

Get the list of everyone the specified userid is a fan of, or the list of everyone you are a fan of if a userid is not specified.

getFans ( [[userId:string, ]callback:fn )

Get the list of everyone who is a fan of the specified userid, or the list of everyone who is your fan if a userid is not specified.

example
bot.getFans(function (data) { console.log(data); });
// { msgid: 7, fans: [ '4e69c14e4fe7d00e7303cd6d', ... ], success: true }

getUserId ( name:string, callback:fn )

Get a user's id by their name.

Example
bot.getUserId('@alain_gilbert', function (data) { console.log(data); });
// { msgid: 12, userid: '4deadb0f4fe7d013dc0555f1', success: true }

getPresence ( [[userId:string, ]callback:fn] )

Get presence for the specified user, or your presence if a userid is not specified.

getProfile ( [[userId:string, ]callback:fn] )

Get the profile for the specified user, or your profile if a userid is not specified.

modifyProfile ( profile:obj [, callback:fn] )

Modify your profile. Any missing properties from the 'profile' object will be replaced with the current values.

Arguments
  • profile:obj (required)
    • name:string (optional)
    • twitter:string (optional)
    • soundcloud:string (optional)
    • facebook:string (optional)
    • website:string (optional)
    • about:string (optional)
    • topartists:string (optional)
    • hangout:string (optional)
  • callback:fn (optional)
Examples
bot.modifyProfile({ website:'http://ttdashboard.com/', about:'My bot.' }, callback);

modifyLaptop ( laptop:enum('linux', 'mac', 'pc', 'chrome' , 'iphone', 'android') [, callback:fn] )

Modify your laptop.

modifyName ( name:string [, callback:fn] )

Modify your name.

setAvatar ( avatarId:int [, callback:fn] )

Set your avatar.

becomeFan ( userId:string [, callback:fn] )

Fan someone.

removeFan ( userId:string [, callback:fn] )

Unfan someone.

snag ( [ callback:fn ] )

Trigger the heart animation used to show that you've snagged the currently playing song.

Warning

This function will not add the song into the queue. Use .playlistAdd to queue the song, and if successful, then use .snag to trigger the animation.

pm (msg:string, receiverId:string [, callback:fn] )

Send a private message.

pmHistory ( receiverId:string, callback:fn )

Get the private conversation history.

setStatus ( status:enum('available', 'unavailable', 'away') [, callback:fn ] )

Set your current status.

setAsBot ( callback:fn )

Set the user to be considered a bot. This puts the user under the "Bots" group in the room list. A good place to run this command is in the callback to .roomRegister.

bot.roomRegister(roomid, function() {
  bot.setAsBot();
});

playlistListAll ( callback:fn )

List all your playlists.

playlistCreate ( playlistName:string [ , callback:fn ] )

Create a new playlist.

Arguments
  • playlistName (required)
  • callback (optional)
Examples
bot.playlistCreate(newPlaylistName)
bot.playlistCreate(newPlaylistName, callback)

playlistDelete ( playlistName:string [ , callback:fn ] )

Delete a playlist.

Arguments
  • playlistName (required)
  • callback (optional)
Examples
bot.playlistDelete(playlistName)
bot.playlistDelete(paylistName, callback)

playlistRename ( oldPlaylistName:string, newPlaylistName:string [ , callback:fn ] )

Rename a playlist.

Arguments
  • oldPlaylistName (required)
  • newPlaylistName (required)
  • callback (optional)
Examples
bot.playlistRename(oldPlaylistName, newPlaylistName)
bot.playlistRename(oldPlaylistName, newPlaylistName, callback)

playlistSwitch ( playlistName:string [ , callabck:fn ] )

Switch to another playlist.

Arguments
  • playlistName (required)
  • callback (optional)
Examples
bot.playlistSwitch(playlistName)
bot.playlistSwitch(playlistName, callback)

playlistAll ( [ playlistName:string, ] callback:fn )

Get all information about a playlist.

Arguments
  • playlistName (optional) default: default
  • callback (required)
Examples
bot.playlistAll(callback);
bot.playlistAll(playlistName, callback);

playlistAdd ( [ playlistName:string, ] songId:string [, index:int [, callback:fn]] )

Add a song to a playlist.

Arguments

  • playlistName (optional) default: default
  • songId (required)
  • index (optional) default: 0
  • callback (optional)
Examples
bot.playlistAdd(songId);
bot.playlistAdd(songId, idx);
bot.playlistAdd(songId, callback);
bot.playlistAdd(songId, idx, callback);
bot.playlistAdd(playlistName, songId, idx);
bot.playlistAdd(playlistName, songId, callback);
bot.playlistAdd(playlistName, songId, idx, callback);
bot.playlistAdd(false, songId, callback); // Backward compatibility
bot.playlistAdd(false, songId);           // Backward compatibility

playlistRemove ( [ playlistName:string, ] index:int [, callback:fn ] )

Remove a song on a playlist.

Arguments
  • playlistName (optional) default: default
  • index (optional) default: 0
  • callback (optional)
Examples
bot.playlistRemove();
bot.playlistRemove(index);
bot.playlistRemove(index, callback);
bot.playlistRemove(playlistName, index);
bot.playlistRemove(playlistName, index, callback);

playlistReorder ( [ playlistName:string, ] indexFrom:int, indexTo:int [, callback:fn ] )

Reorder a playlist. Take the song at index indexFrom and move it to index indexTo.

Arguments
  • playlistName (optional) default: default
  • indexFrom (required) default: 0
  • indexTo (required) default: 0
  • callback (optional)
Examples
bot.playlistReorder(indexFrom, indexTo);
bot.playlistReorder(indexFrom, indexTo, callback);
bot.playlistReorder(playlistName, indexFrom, indexTo);
bot.playlistReorder(playlistName, indexFrom, indexTo, callback);

searchSong ( query:string, callback:fn )

Search for songs.

Arguments
  • query
  • callback
Examples
bot.searchSong(query, callback);

getStickers ( callback:fn )

Get all stickers information.

Example
bot.getStickers(function (data) { console.log(data); });
// https://github.com/alaingilbert/Turntable-API/blob/master/turntable_data/getstickers.js

getStickerPlacements ( userid:string, callback:fn )

Get the information about a user's stickers.

Example
bot.getStickerPlacements('4e0889d4a3f7517d1100af78', function (data) { console.log(data); });
// https://github.com/alaingilbert/Turntable-API/blob/master/turntable_data/getstickerplacements.js

placeStickers ( placements:array.<object> [, callback:fn] )

Sets your sticker placements. The placements object is formatted the same as the placements object retrieved in the getStickerPlacements callback.

Example
var placements = [{
  top: 126,
  angle: -23.325931577,
  sticker_id: '4f86fe84e77989117e000008',
  left: 78
}];
bot.placeStickers(placements);

turntable-api's People

Contributors

alaingilbert avatar benthehokie avatar chrisinajar avatar drhinehart avatar frick avatar gizmotronic avatar goto-bus-stop avatar izzmo avatar jeffstieler avatar krunkosaurus avatar leosperry avatar mcmoyer avatar mikewills avatar mnafricano avatar morgon avatar oldramen avatar omgyeti avatar paradox460 avatar sharedferret avatar technobly avatar therabidbanana avatar vin avatar

Stargazers

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

Watchers

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

turntable-api's Issues

When switching chat servers, bot should send disconnect

I had an issue when porting the bot to C# (this may only happen with newer websocket protocol drafts). If you have a bot that can switch between rooms without shutting down and starting up, it is important to send turntable the disconnect command so that they know to disconnect the current connection and not a new one on a different chat server.

Before after deregistering from the room, send: m10mdisconnect

This will cause the server to close its connection with the client so you can connect to a different chat server for a different room.

End song event

Can we get a "end song" event added to the API ? I want to have the ability to total awesomes, lames before the new song message gets displayed on the TT room

Blacklist user

I know how to get my own userid, but how do you get a troll's userid? Right now I'm blacklisting the username, which can be changed. Thanks.

last.fm scrobble

looking to add some scrobble function, any experience with that alain?

Cannot call method 'send'

downloaded new code for tt fix thats going to happen and when I ran my bot script it faild with this

node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot call method 'send' of undefined
at [object Object]._send (exmaple.com/uberbot/bot/node_modules/ttapi/bot.js:299:12)
at [object Object].bootUser (exmaple.com/uberbot/bot/node_modules/ttapi/bot.js:468:9)
at [object Object].startAPI (exmaple.com/uberbot/bot/node_modules/uberbot/uberbot.js:941:14)
at Object. (exmaple.com/uberbot/bot/marvin-mixxx.js:220:6)
at Module._compile (module.js:407:26)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array. (module.js:426:10)
at EventEmitter._tickCallback (node.js:126:26)

how to use auth

Hi,
This is not an issue, I just coudlnt' find a place to post it.

When creating the Bot, it takes in Auth, i see on the bottom of the examples it has
var AUTH = 'auth+live+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

so what is auth exactly? what do I assign to it?

thanks!
mina

playlistRemove not functioning correctly?

I am trying to run the following code to clear a bot's entire playlist.

This doesn't clear all the songs out though. It will only clear a couple every time it is run.

bot.playlistAll(function (data) {
for(var i = 0; i < data.list.length; i++)
bot.playlistRemove();
});

Automatically reconnect after connection lost?

Is there a way to make the bot automatically reconnect to turntable if its internet connection goes down temporarily? I run a bot off my home connection, and occasionally it'll go down, maybe for just a few minutes, but when this happens of course the bot leaves turntable, and the only way I can see to have it reconnect is to restart the bot.

My bot is running on my ubuntu box, and I have it set up with an init script so it does automatically restart if it crashes, but this doesn't apply when just losing its internet connection.

Trouble connecting?

Anyone else having trouble getting their bot to connect this morning? In debug mode mine can get as far as seeing his own fan userids, and getting presence updates but he does not appear in the room. my js hasn't changed since last night when it was working. I hope TT didn't change anything that would break Alains API!

Playlist Name

Does a bot need a particular playlist name to be able to DJ? Might be nice to update the readme/wiki with that detail if somebody knows it. I'm creating a Hubot (http://github.com/github/hubot) adapter using your library and it'd be awesome to be able to make the bot play music.

No data for endsong event

I'm not getting any data for endsong. When I print the value of data, i.e.:

bot.on('endsong', function (data) {
console.log(data);
});

I just get "undefined".

Do we know what is causing this? AFAIK, I'm using the latest version.

Add track to queue from external site?

Not really an "issue", more of a question - I've got a stats site that records plays, and was wondering if anyone has figured out how to replicate the "add to queue" functionality to a website, assuming you have the songId. Can it be done via JavaScript?

Pipe results of get request to bot.speak?

I apologize in advance if this too elementary a questino, but as a student of js, I was pulling my hair out about this all weekend. I want to take the JSON returned by a get request and pipe one of the returned lines to bot.speak, but I'm having a really hard time wiring it up. I installed the request module, and I think it's returning data, but the best I can do is to get the bot to speak "[object Object]".

Can a kind soul help me out?

Python Bots Sporadically Going Offline

I may or may not be the only person who has this problem, but I have 2 bots set up and each goes offline PM-wise so that PM commands cannot be carried out. It usually happens during periods of higher activity in the room however, the computer that they are running off of is decent and relatively new. Any help is appreciated.

Thanks,

~ LSK

Count DJ song played or time afk

I was looking at the example for afk user list, but Im not sure how to use it to keep track of the ammount of time a DJ has been afk or how many songs he has played. Can someone help me with this?

I see the example tracks the time for everyone, but not sure how to get it to.. remove dj after 20minutes afk or 5 songs. something like that.

Any help would be GREATLY APPRECIATED , thank you much for all this information too.

Bot not working after TT update this morning

My bot seems to have stopped working after TT did their update this morning. I've updated with your latest changes to the API (as of yesterday). Should this be working at the moment, or are there more changes needed after the update this morning?

bot.roomRegister callback doesn't fire

Looks like the code is wrong in Bot.prototype.roomRegister. Why is the callback being sent from within an anonymous function?

this.callback = function () {
var rq = { api: 'room.register', roomid: roomId };
self._send(rq, callback);
};

I tried just having it execute the code inside (by commenting out the first and last line from the above), but I end up getting an uncaught exception (TypeError: Cannot read property 'metadata' of undefined). Also, adding code inside that anonymous function DOES get fired, but for some reason the callback itself doesn't seem to.

I'm using
bot.roomRegister(ROOMID, function(result) {
console.log("Registered: ", result);
});

But the "Registered: " ( + result) never gets logged.

Adding songs to Q no longer working

For some reason the method I have been using to add songs to my bot's queue is no longer working. I haven't changed anything on it so I am not sure why it suddenly stopped. I can return the songID and index in the console but it just won't let me add. Below is my code...

if (data.text.match(/^*add$/)) {
bot.roomInfo(true, function(data) {
var newSong = data.room.metadata.current_song._id;
var newSongName = songName = data.room.metadata.current_song.metadata.song;
var newArtist = artist = data.room.metadata.current_song.metadata.artist;
bot.playlistAdd(newSong, plLength);
console.log(newSong, plLength);
plLength++;
bot.vote('up');
bot.speak('I can now play "'+newSongName+'" by '+newArtist+' for you.');
});
}

playlistAll returns api error (1)

I want to reorder the playlist after adding a song, but need to know the length of the playlist.
playlistAdd() doesn't return any helpful info about the playlist.
playlistAll() just returns an api error:

bot.playlistAll(function(data) {console.log(data); } );
{ msgid: 3, err: 'api error (1)', success: false }

Am I missing something?
Thanks!

removing profile data

I have change the profile data of my bot just like the example

bot.modifyProfile({ website:'http://ttdashboard.com/', about:'My bot.' }, callback);

and then realized that we didn't want any data in the block about. then realized if I leave it blank then it will use the previous value so I am wondering how to remove it ?

thanks
mcgrailm

Bot sporadically dissapears, but doesn't appear to crash

I'm having an issue where my bot is dissapearing from the room but not showing any signs of crashing.
I'm suspecting this has to do with the bot timing out or something along those lines but the bot doesn't seem to crash.

I've tried the bot on Nodejitsu and on my personal computer and when the bot dissapears, both my computer and Nodejitsu tells me the bot is running and no errors appear.

Here's what I'm using to initialize the bot.

//Main Initilization
var TTAPI   = require('ttapi');
var AUTH   = 'authhere';
var USERID = 'useridhere';
var ROOMID = 'roomidhere';

var bot = new TTAPI(AUTH, USERID, ROOMID);

//Required for Nodejitsu
bot.listen(8080, '127.0.0.1');

stalk user callback data does not work with mobile users

bot.stalk([userid], function(data){console.log('data.roomId: '+data.roomId);})

When calling this code while the [userid] is a mobile user, data.roomId is undefined. it appears that the data object either doesn't get returned or is different in structure.

anyone else come across this, or at least confirm this is true?

Bot dropping from room

I am using the chat-bot example and for some reason after about 1 song the bot is being dropped from the room. On the site, in the room, I can see the bot's icon there, but when I refresh they are not there (I am guessing the icon was only where because of some false open connection or something). Any reason why or how to keep the connection alive? There are no chat's in the room so maybe it is because there is too long of a period without receiving data? I don't know, just speculating.

Thanks!

AFK Police finished too quick?

Here, I have 3 questions. For the AFK Police.

First question: How do I make the '+dj+' things to show their real DJ names not their IDs.

afkCheck = function () {
   var afkLimit = 7; //An Afk Limit of 7+1 minutes.
   for (i = 0; i < djs.length; i++) {
      dj = djs[i]; //Pick a DJ
      if (isAfk(dj, afkLimit)) { 
         bot.speak('@'+dj+', don\'t fall alseep on the decks! Wake up!');
         bot.pm('Hey! Don\'t fall alseep on the decks! Wake up! You have 1 minute to respond before you get remove from the decks!', dj);
         setTimeout(function() {
         bot.remDj(dj);
         bot.speak('@'+dj+', you were remove because you were AFK on the decks for 8 minutes.');
      }, 60000);

      };
   };
};

Second Question: So, this repeats every 5 seconds, and when the Dude AFK Limit DOES hit, won't the bot give the Dude the speech every 5 seconds? Is there some way you can stop that? With variables and stuff?

setInterval(afkCheck, 5000) //This repeats the check every five seconds.

Third Question: Soooo, is there a way so that the TimeStamp updates? By, Speaking, PMing, Laming, Awesoming? Cause, I don't think this works. I just see speak, but I don't know what to put there.

bot.on('roomChanged', function (data) { djs = data.room.metadata.djs; });

bot.on('add_dj', function (data) { djs.push(data.user[0].userid); });

bot.on('rem_dj', function (data) { djs.splice(djs.indexOf(data.user[0].userid), 1); });


    justSaw = function (uid) {
    return lastSeen[uid] = Date.now();
    };

    bot.on('speak', function (data) {
    //your other code
    justSaw(data.userid);
    });

    isAfk = function (userId, num) {
   var last = lastSeen[userId];
   var age_ms = Date.now() - last;
   var age_m = Math.floor(age_ms / 1000 / 60);
   if (age_m >= num) {
      return true;
   };
   return false;
};

Socket is not writable

at about 1 AM EST I got this error on more than 1 bot

net.js:391
    throw new Error('Socket is not writable');
          ^
Error: Socket is not writable
    at Client._writeOut (net.js:391:11)
    at Client.write (net.js:377:17)
    at [object Object].<anonymous> (/node_modules/ttapi/websocket.js:449:16)
    at [object Object]._send (/node_modules/ttapi/bot.js:299:12)
    at [object Object].updatePresence (/node_modules/ttapi/bot.js:333:9)
    at Timer.callback (/node_modules/ttapi/bot.js:148:47)

not sure if this is due to an interruption by tt or by my server ?

I would appreciate any advice you could give here
Mike

setInterval Not Needed?

On line 149 of bot.js, the updatePresence() interval, is this needed anymore? I know it causes memory leak issues and I seem to stay on chat fine without it.

Comments/Thoughts?

python style default parameters

remDj, roomInfo, getProfile, playlistAll, playlistAdd, playlistRemove, playlistReorder

these functions should use python style named/keyword parameters, rather than relying so strictly on parameter order.

NPM package installs older version now

NPM installs 1.2.4, won't update beyond that version. Checked a dev bot I set up this weekend and it's on 1.4.3, so something reverted yesterday or today.

Using getProfile when replying to PMs (Python)

I may be asking not exactly in the right place, but suppose I wanted to be able to return the username of any user by using getProfile and then reply in a PM e.g.:

user:    username of 4f66952ba3f751581d025a4d
bot:     The username of the user is John Doe.

How would I go about doing this?

Thanks and pardon my lack of experience
~ LSK

difference between playlistAdd and snag?

The documentation says "snag" will not add a song to queue, but I thought that's what it was doing...how does this compare to playlistAdd?

Also, the playlist functions make it seems as if multiple playlists are supported?

Unexpected Crash

is this ttapi related?

SyntaxError: Unexpected token U
at Object.parse (native)
at [object Object].onMessage (/node_modules/ttapi/bot.js:151:20)
at [object Object].onmessage (/node_modules/ttapi/bot.js:412:46)
at Array.0 (/node_modules/ttapi/websocket.js:308:30)
at EventEmitter._tickCallback (node.js:192:40)

Getting bot to enter room and do things... it's a mystery!

We chatted earlier - I created a folder with a file, main.js:
var Bot = require('../index');
var AUTH = 'auth+live+...';
var USERID = '...';
var ROOMID = '...';

var bot = new Bot(AUTH, USERID, ROOMID);

bot.on('speak', function (data) {
   // Get the data
   var name = data.name;
   var text = data.text;

   // Respond to "/hello" command
   if (text.match(/^/hello$/)) {
      bot.speak('Hey! How are you '+name+' ?');
   }
});

Just trying to get the bot in the room. I created the file in text edit. The main.js file is in /bot folder, so I open mongoDB, connect to mongo shell, and in a seperate terminal window i cd to the bot folder and say $ node main.js
This is what happens.
$ node main.js

/bot/main.js:1
{\rtf1\ansi\ansi
^

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:429:25)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)

I hate that I don't know what all that means. I have node installed, node_modules is located in my root, and I have ttapi, mongoose, and mysql. MongoDB is running and I have the shell open. I don't know what is wrong. Anyone? Grrrr.
Thanks so much.
Vega

Bot crashes on timeout

Alain,

Thanks so much for this API, it's really spectacular. I've noticed that my bot will periodically crash, here are two of the the stack trace, which seem to be some kind of time out (perhaps on an http.get?):

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: ETIMEDOUT, Connection timed out
    at Socket._onConnect (net.js:595:18)
    at IOWatcher.onWritable [as callback] (net.js:186:12)

And this looks a little different, but also seems to deal with some kind of network issue

net.js:391
    throw new Error('Socket is not writable');
          ^
Error: Socket is not writable
    at Client._writeOut (net.js:391:11)
    at Client.write (net.js:377:17)
    at [object Object].<anonymous> (/home/dkyjenxqvps/tt bots/websocket.js:449:16)
    at [object Object]._send (/home/dkyjenxqvps/tt bots/bot.js:288:12)
    at [object Object].updatePresence (/home/dkyjenxqvps/tt bots/bot.js:317:9)
    at Timer.callback (/home/dkyjenxqvps/tt bots/bot.js:137:47)

I'm not exactly a seasoned javascript coder, but I suspect it's that I'm not handling some case with a try/catch. If it's possible and not too difficult for you to explain how I might code to prevent this, I'd appreciate any help you can offer.

Chat Port

I saw at the bottom of websocket.py (and possibly a few other places) that you were hard coding the port.
ws = create_connection("ws://localhost:5000/chat")

I'm trying to use a node.js hosting platform to develop on, but they require a custom port. They also support environment variables: port, host, PORT, HOST, app_host, app_port.

Any chance you could change the port to use a variable?

Thanks!
-Mike

snag() always fails now

For the last week or two I've noticed that when my bot (cmbot) snags a song, it doesn't produce the hearts anymore. After looking into it, it looks like the snag() call is failing. I add a callback and checked the result it receives, and get the following

result: { msgid: 85, err: '', success: false }

Anyone know why? I know this is happening with at least one other bot running my code.

missing user id on down vote

console.log(data.room.metadata.votelog);

does not return a user id on down vote but does on up vote

thanks for any help
Mike

Help with replying to PMs (Python)

Could someone whip up a quick example for replying to PMs in Python (something like the chat bot example except for PMming)? I'm having trouble trying to understand how to use it.

Thanks in advance.

Get the bot to snag a song?

I know it is possible, I am just not familiar with how to make the bot produce the 'heart' from it's cute little head when i tell her to swipe a song. How do I modify the snag ( [ callback:fn ] ) to make my bot heart-burp on the /snag command?
Thanks so much... I am learning!
Vega

Better use of _isConnected flag

Is there any reason we don't make better use of this flag?

I understand most people have a single bot and it's not really necessary, but for those who run quite a few, this flag is invaluable and I noticed it's never actually being set to false. In my fork I made it so this condition is set if some conditions are met.

setInterval Causing Garbage Collection Issues

I think it may be possible that the setTimeout on the update presence method may be causing garbage collection issues when operating multiple bots. So far I have updated my copy to cancel the setTimeout if the web socket is no longer connected and seems to be working nicely. I will give more updates in the next day or two as I test it out.

Bot stops being able to interact with the room after some time

My bot works perfectly for about one minute, and then stops being able to interact with the room (vote, speak, etc...) all at once.

It hasn't frozen, because I still get console log messages that look perfect.

Here's my code:

var Bot = require('ttapi');
var bot = new Bot(AUTH, USERID, ROOMID);

bot.on('speak', function (data) {
    // Get the data
    var name = data.name;
    var text = data.text;

    // Say stuff when someone says myname
    if ( text.indexOf("myname") != -1 && !name.match(/^\myname$/)) {
        console.log('\nI heard my name\n\n', data); 
        bot.speak('/me myname');
    }
});

bot.on('newsong', function (data) { 
    bot.vote('up'); 
    console.log('\New song, voted up\n\n', data); 
});

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.