Skip to content

Instantly share code, notes, and snippets.

@dnordstrom
Forked from AlcaDesign/index.js
Created August 11, 2018 13:39
Show Gist options
  • Save dnordstrom/920b39a5d4ff822c812dac23e4c304e6 to your computer and use it in GitHub Desktop.
Save dnordstrom/920b39a5d4ff822c812dac23e4c304e6 to your computer and use it in GitHub Desktop.
A command bot example
const tmi = require('tmi.js'),
request = require('request'),
countdown = require('countdown'),
kraken = request.defaults({
baseUrl: 'https://api.twitch.tv/kraken/',
json: true,
headers: {
'Client-ID': '',
Accept: 'application/vnd.twitchtv.v3+json'
}
});
let client = new tmi.client({
options: {
debug: true
},
connection: {
reconnect: true,
secure: true
},
channels: [
'alca'
],
identity: {
username: '',
password: ''
}
});
client.on('message', (channel, userstate, message, fromSelf) => {
if(fromSelf || message[0] !== '!') {
return;
}
userstate.name = userstate['display-name'] || userstate.username;
let chan = channel.slice(1),
params = message.split(' '),
commandName = params.shift().slice(1).toLowerCase(),
hasParams = params.length > 0,
perms = {
mod: userstate.mod,
broadcaster: userstate['user-id'] === userstate['room-id']
//broadcaster: 'broadcaster' in userstate.badges
},
reply = msg => client.say(channel, msg);
perms.modUp = perms.mod || perms.broadcaster;
if(commandName === 'time') {
let d = new Date();
reply(d.toLocaleString());
}
else if(commandName === 'created') {
let target = userstate.username;
if(hasParams && perms.modUp) {
target = params[0];
}
kraken({
url: `users/${target}`,
qs: {
_: Math.random() * 1000000
}
}, (err, res, body) => {
if(err) {
console.log('ERROR', err);
reply('Errror');
return;
}
else if(res.statusCode !== 200) {
reply('User not found');
return;
}
let timestamp = new Date(body.created_at).getTime(),
created = countdown(timestamp, Date.now(), 158),
name = body.display_name || body.name,
message = `${userstate.name}, ${name} was created ` +
`${created.toString()} ago.`;
reply(message);
});
}
else if(commandName === 'uptime') {
let target = chan;
if(hasParams && perms.modUp) {
target = params[0];
}
kraken({
url: `streams/${target}`,
qs: {
_: Math.random() * 1000000
}
}, (err, res, body) => {
if(err) {
console.log('ERROR', err);
reply('Errror');
return;
}
else if(res.statusCode !== 200) {
reply('User not found');
return;
}
if(body.stream === null) {
reply(`${target} is offline. :(`);
return;
}
let timestamp = new Date(body.stream.created_at).getTime(),
uptime = countdown(timestamp, Date.now(), 158),
name = body.stream.channel.display_name,
message = `${name} has been live for ${uptime}!`;
reply(message);
});
}
});
client.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment