Creating bots with nodejs

  1. Twitter
  2. Discord
  3. Twitch
  4. Other Bots

Twitter bot with 'twit'

An easy module I found for this is the "twit" module. It allows for easy image upload, which I needed for my bot.
As always, install it with npm install twit.
Then create a file with '.js' ending and paste the following into it:


console.log("Starting Twitterbot v1.0");

var fs = require('fs');
var path = require('path');
var Twit = require('twit');

var config = {
  consumer_key:         'Key Here',
  consumer_secret:      'Key Here',
  access_token:         'Key Here',
  access_token_secret:  'Key Here'
}

function randomArray(images){
  return images[Math.floor(Math.random() * images.length)];
}

function uploadImage(images){
  console.log("Opening image...");
  var ranimg = randomArray(images);
  var image_path = path.join(__dirname, '/pics/' + ranimg),
      b64content = fs.readFileSync(image_path, { encoding: 'base64' });

  console.log("Uploading image...");
  console.log("Image: "+ranimg);

  T.post('media/upload', { media_data: b64content }, function (err, data, response) {
    if (err){
      console.log('ERROR While uploading Image:');
      console.log(err);
    }
    else{
      console.log('Image uploaded!');
      console.log('Sending tweet...');

      T.post('statuses/update', {
        media_ids: new Array(data.media_id_string),
        status: "Text of Tweet here"
      },
        function(err, data, response) {
          if (err){
            console.log('ERROR While posting Tweet:');
            console.log(err);
          }
          else{
            console.log('Tweet was posted!');
            console.log("");
          }
        }
      );
    }
  });
}

var T = new Twit(config);

fs.readdir(__dirname + '/pics', function(err, files) {
  if (err){
    console.log(err);
  }
  else{
    var images = [];
    files.forEach(function(f) {
      images.push(f);
    });

    setInterval(function(){
        var temp = new Date();
        console.log(temp);
        uploadImage(images);
    }, 10000);
  }
});
Create a folder in the same directory and name it "pics".
Upload your images there and the bot will pick a random one and upload it to twitter every 10 seconds.
You can change the interval in the 3rd last row. The script should be self-explanatory.
Documentation of twit: npmjs.com/package/twit


Discord bot with 'discord.js'

Creating a discord bot is really easy with 'discord.js'. First create your bot using discordapp.com/developers.
Then simply install the module using npm install discord.js.
This is an example-script that shows off the main features that a basic bot will be using.


const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
 });

client.on('message', msg => {
 if (msg.content.toLowerCase() === "ping") {
  msg.reply('pong');
 }
 if (msg.content.toLowerCase() === "t") {
  msg.channel.send("Sending without Tag!");
 }
 if (msg.content.toLowerCase() === "e"){
  const embed = new Discord.RichEmbed().setTitle("EmbedTitle").setColor(0xFF0000).setDescription("Hi, Embed Text!");
  msg.channel.send(embed);
 }
 if (msg.content.toLowerCase() === "a"){
  const attachment = new Discord.Attachment("./pic.jpg");
  msg.channel.send(msg.author,attachment);
 }
 });

client.login('Client_Token_Of_Your_Bot_Here');
More info: msg.reply Tags the user that sent the message that triggered the bot, while msg.channel.send only sends a message without @-ing anyone.
You can send images either from your server (like in this example with "./pic.jpg") or you can also send an image via a link aswell.
Documentation of discord.js: discord.js.org


Twitch bot with 'tmi.js'

I mostly use my twitch bot to log messages, so this example using "tmi.js" is pretty short and self-explanatory.


const tmi = require('tmi.js');
const fs = require('fs');

console.log("Starting AutomatedChatLog...")
console.log(new Date().toISOString());
var stream = fs.createWriteStream(new Date().toISOString().slice(0,10), {flags:'a'});
const opts = {
  identity: {
    username: "UserNameOfBotHere",
    password: "KeyHere"
  },
  channels: [
    "StreamerNameHere"
  ]
};

const client = new tmi.client(opts);
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
client.connect();
let cdate = new Date();

function onMessageHandler (channel, context, msg, self) {
  cdate = new Date();
  console.log(cdate.getHours()+":"+cdate.getMinutes()+" - "+context["display-name"]+" - "+msg);
  stream.write(cdate.getHours()+":"+cdate.getMinutes()+" - "+context["display-name"]+" - "+msg+"\n")
}

function onConnectedHandler (addr, port) {
  console.log(`Connected to ${addr}:${port}`);
}
This script logs all the chat messages (not notifications or subscriptions) to a file named "2019-MM-DD".
This is great for analysis of toxic behavior or simply big-data stuff.
To quickly search for chat messages a user sent: grep "UserName" FileName
Documentation of tmi.js: github.com/tmijs/tmi.js


Creating other bots

Simple bots for web-scraping can be created with simple python code.
Similar nodejs bots like the ones above can be created with similar modules that you can find via google.
Most 'bots' use a pre-defined module that helps a lot, so google should help with that.
For creating automated tasks (what a bot does) have a look at python-based automatetheboringstuff.com aswell.