How to build a Twitter bot with NodeJs - CodeSource.io

How to build a Twitter bot with NodeJs - CodeSource.io

Building a Twitter bot using their API is one of the fundamental applications of the Twitter API. To build a Twitter bot with Nodejs, you’ll...

How to: Build a Twitter Bot with Node.js only Takes a Few Minutes!

How to: Build a Twitter Bot with Node.js only Takes a Few Minutes!

Building a Twitter bot with Node.js is easy these days (if you have at least some web development & JavaScript knowledge). Get ready with me and set up your own one in just a few minutes.

Building a Twitter bot with Node.js is easy these days (if you have at least some web development & JavaScript knowledge). Get ready with me and set up your own one in just a few minutes.

At first you will need to register a (new) Twitter account specifiying the screen name, through which you’d like to tweet into the world. After that you are ready to apply for a developer’s account and add a new Twitter developer’s app here. This is necessary for generating keys and tokens for accessing the official Twitter API. Twitter asks for several information about what you want to do with your app. Writing down what the bot is all about went just fine for me. Finally it’s time for coding. Make sure node and npm are installed on your computer with the following commands.

node -v
npm -v

After that, we are ready to setup a working folder and init a npm project with:

npm init

The only library that is mandatory for our project is the npm package twitter-lite, a tiny, full-featured, modern client / server library for the Twitter API, whose documentation you will find here. It was built because existing ones have not been recently maintained, or depend on outdated libraries. Within our working folder we create a Node.js script, which could be named “bot.js”.

const Twitter = require("twitter-lite");
const client = new Twitter({
  consumer_key: 'xyz',
  consumer_secret: 'xyz',
  access_token_key: 'xyz',
  access_token_secret: 'xyz'
});

This creates a new authorized Twitter API client. All keys and secrets are available in your Twitter developer’s account.

What should the bot do exactly? Well, for example, we could filter all incoming new tweets around the world with the help of keywords or hashtags by opening up the Twitter Stream and providing some parameters, like so:

const parameters = {
  language: "en",
  track:
    "#girlswhocode,#girlsintech,#womenintech,#womenwhocode,#momsintech,#momswhocode"
};
client
  .stream("statuses/filter", parameters)
  .on("start", response => console.log("start"))
  .on("data", async data => {
    console.log("got data", data.id_str);
  })
  .on("error", error => console.log("error", error))
  .on("end", response => console.log("end"));

Instead of just logging filtered tweets we could now automatically retweet those tweets by adding:

const url = `statuses/retweet/${data.id_str}`;
await client.post(url);

That’s it! Just start your script with

node bot.js

and your bot starts firing. There are many more possibilities on how the Twitter API can be used. You would like to deploy this app? Sure, you could deploy on Heroku or use a hoster like DigitalOcean that could run your app in the background with pm2. Beware: Your secrets and keys should be stored in environment variables! A great library to do so is dot-env.

Thank for read!

How to Build a Discord Bot with Node.js

How to Build a Discord Bot with Node.js

This article will solely focus on creating your first bot with the exposed Discord API using Node.js. Maybe the most well-known Discord bot is the Music Bot.

Nowadays, bots are being used for automating various tasks. Since the release of Amazon’s Alexa devices, the hype surrounding automation bots has only started to grow. Besides Alexa, other communication tools like Discord and Telegram offer APIs to develop custom bots.

This article will solely focus on creating your first bot with the exposed Discord API. Maybe the most well-known Discord bot is the Music Bot. The music bot lets you type a song name and the bot will attach a new user to your channel who plays the requested song. It’s a commonly used bot among younger people on gaming or streaming servers.

Let’s get started with creating a custom Discord bot.

Prerequisites
  • Node.js v10 or higher installed (basic knowledge)
  • a Discord account and Discord client
  • basic knowledge of using a terminal
Step 1: Setup Test Server

First of all, we need a test server on which we can later test our Discord bot. We can create a new server by clicking the plus icon in the left bottom corner.

A pop-up will be displayed that asks you if you want to join a server or create a new one. Of course, we want to create a new server.

Next, we need to input the name for our server. To keep things simple, I’ve named the server discord_playground. If you want, you can change the server location depending on where you’re located to get a better ping.

If everything went well, you should see your newly created server.

Step 2: Generating Auth Token

When we want to control our bot via code, we need to register the bot first under our Discord account.

To register the bot, go to the Discord Developers Portal and log in with your account.

After logging in, you should be able to see the dashboard. Let’s create a new application by clicking the New Application button.

Next, you’ll see a pop-up that asks you to input a name for your application. Let’s call our bot my-greeter-bot. By clicking the Create button, Discord will create an API application.

When the application has been created, you’ll see the overview of the newly created my-greeter-bot application. You’ll see information like a client ID and client secret. This secret will be used later as the authorization token.

Now, click on the Bot menu option in the Settings menu. Discord will build our my-greeter-bot application and add a bot user to it.

When the bot has been built, you get an overview of your custom bot. Take a look at the Token section. Copy this authorization token and write it down somewhere, as we’ll need it later to connect to our bot user.

Step 3: Define Permissions and Add Bot to Server

Thirdly, we want to define the permissions for the bot and add it to our Discord server.

Navigate to the OAuth2 section under the Settings menu. Here we can define the scope for our bot. As we just want to enable a simple bot, we pick the bot option.

You might notice that the authorization URL below has changed now. However, the permissions=0 section indicates that we haven’t set permissions yet.

If we scroll further down, you’ll find the bot permissions section. We want the bot to be able to Send Messages and read message history. We need the permission Read Message History so we can detect users’ requests.

When you select both options, notice the number has changed for the permissions parameter in the authorization URL.

Lastly, copy this URL and paste it in your favorite web browser. You’ll find an overview that asks you which server you want to add the bot to. Let’s select our newly created discord_playground.

Click the Authorize button to add the bot to our server.

If you’re able to successfully add the bot to your server, you should see the following success screen.

If you want to double-check that your bot got added, go to the general channel. You should see a similar message that indicates that the bot has joined the channel.

Success!

Step 4: Project Setup

Finally, let’s set up the project. You can find the base project on GitHub. Please clone the repository locally on your machine using git clone https://github.com/michielmulders/discord-bot-sitepoint.git.

The project depends on two dependencies, dotenv and discord.js. The first dependency allows us to use a .env file that holds the bot token we have written down. It’s obvious we need the second dependency, discord.js, for developing the Discord bot.

In order to install both dependencies, please execute npm install inside the project folder.

Lastly, to complete the installation, create a .env file in the root of the project. Add one environment variable called TOKEN to the file like this:

TOKEN=my-unique-bot-token

Step 5: Exploring Discord.js

Let’s take a look at the index.js file located in the root of the project:

require('dotenv').config();
const Discord = require('discord.js');
const bot = new Discord.Client();

const TOKEN = process.env.TOKEN;

bot.login(TOKEN);

We first load the environment variables we’ve defined through requiring the config from the environment .env file. This allows us to use the TOKEN variable we’ve defined through process.env.ToKEN. The last line of the above snippet shows how we pass the token to the login function in order to get access to the bot we’ve created.

The bot variable is actually our Discord client through which we’ll interact.

Listen for “ready” Event

Next, we can listen for events. First of all, we’re listening to a ready event. The ready event is fired once we’re connected to the bot:

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

If you’ve used the right TOKEN to log in to the bot, your terminal should print the name of your bot bot.user.tag.

You can start the bot by simply executing node index.js in you terminal. Make sure you’re executing this command in the root of your project.

If the bot is connected successfully, you should see the name of your bot being printed in the terminal.

Listen for “message” Event

Besides the ready event, the Discord client allows you to listen for a message event. This means the bot can read any message that is sent to a channel. To tie back to the permissions section, this is the exact reason why we need to give the bot permission to read the message history.

bot.on('message', msg => {
    if (msg.content === 'ping') {
        msg.reply('pong');
        msg.channel.send('pong');
    }
});

If we explore the code a bit further, you see we’re looking for a message with contents ping. If we receive a message that just contains ping, the bot replies with pong. After that, we use msg.channel.send to send again pong to the channel.

Notice the difference between both commands:

  • msg.reply: tags the initial user who has sent the message
  • msg.channel.send: sends a message to the channel without tagging anyone.

Try to run the bot with node index.js and send a message ping to the general channel. Verify if you see the same result.

Look for Tagged Users

In order to add a new command, we have to extend the if clause we have with an else … if:

if (msg.content === 'ping') {
        msg.reply('pong');
        msg.channel.send('pong');

} else if (msg.content.startsWith('!kick')) {
    if (msg.mentions.users.size) {
        const taggedUser = msg.mentions.users.first();
        msg.channel.send(`You wanted to kick: ${taggedUser.username}`);
    } else {
        msg.reply('Please tag a valid user!');
    }
}

Let’s say we want to kick someone by sending a message like !kick @username. So, first we look for !kick in the message’s content. If we find a message that starts with !kick, we can check if users were tagged in the message with the msg.mentions.users property.

If there are users tagged, we can select the first mentioned user with msg.mentions.users.first(). Next, we reply to the channel with the user’s username in the message.

Step 6: The Problem with the else … if Chain

Next, let’s discuss the problem with all these else … if statements. If you have only a few commands defined to listen for in the message event, the code is quite readable.

However, when we decide to build an extensive project this way, we end up with a chain of else … if statements. Here’s a small list of reasons why you shouldn’t use else … if chains for anything that’s not a small project:

  • it’s easier to fall victim to spaghetti code
  • the code is hard to read
  • it’s not easy to debug
  • it’s difficult to organize code
  • it’s not easy to maintain as the code grows.

Therefore, let’s take a look at the command pattern we can use.

Implementing a Command Handler

A command handler is an approach that’s supported by the discord.js package. Before we continue, check out the advanced branch with git checkout advanced. This branch holds the command handler implementation.

Command Folder

First, let’s explore the command folder. This folder holds an index.js file that exports all commands we’ll define. To keep things simple, we’ll only define one command, ping:

module.exports = {
    Ping: require('./ping'),
};

Next, let’s look at the implementation of the ping command, which basically exports an object which contains the following:

  • name: a command name.
  • description: it’s best practice to add a description for each command.
  • execute: a function that accepts msg and args inputs. This function holds the same logic as we had in our else … if chain.
module.exports = {
    name: 'ping',
    description: 'Ping!',
    execute(msg, args) {
        msg.reply('pong');
        msg.channel.send('pong');
    },
};

Importing Commands

Continuing, let’s import the commands into the index.js file. Notice we define a commands collection on the Discord bot. We loop over all the commands and add them one by one to the commands collection.

The bot.commands.set function accepts the name of the command and the whole command object:

const Discord = require('discord.js');
const bot = new Discord.Client();
bot.commands = new Discord.Collection();
const botCommands = require('./commands');

Object.keys(botCommands).map(key => {
    bot.commands.set(botCommands[key].name, botCommands[key]);
});

After that, we have to remove our else … if chain and replace it with some dynamic code to find the right command we want to call:

bot.on('message', msg => {
    const args = msg.content.split(/ +/);
    const command = args.shift().toLowerCase();
    console.info(`Called command: ${command}`);

    if (!bot.commands.has(command)) return;

    try {
        bot.commands.get(command).execute(msg, args);
    } catch (error) {
        console.error(error);
        msg.reply('there was an error trying to execute that command!');
    }
});

We first try to split the content of the message by whitespaces using .split(/ +/). We assume the first item in this args array is our command. To check if the command exists in our collection, the collection exposes a has() function, which simply returns true or false. If the command doesn’t exist, we return an empty response.

However, if the command exists, we use the get() function to retrieve the correct command and execute it with the input parameters msg and args.

It’s an easy-to-read, dynamic way of calling commands without writing spaghetti code. This allows you to scale your project to many hundreds of commands if needed.

Again, if you want to test the new version of our code, make sure you check out the advanced branch with git checkout advanced. Next, install all dependencies with npm install and start the bot with node index.js.

Wrapping Up

Installing and setting up a new Discord bot might feel overwhelming at first. However, the API offered by the discord.js package is straightforward, and the Discord website provides great examples.

As this tutorial only covered two permissions, there’s much more to be found. You can learn more about permissions on the Discordjs.guide website.

Good luck with building your first Discord bot!

Top Collection NodeJS Frameworks for Developers in 2020

Top Collection NodeJS Frameworks for Developers in 2020

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

As a developer, one gets to smoothly use the same language for both client–side and server–side scripting and this unique facility has increased the quick adoption of NodeJS frameworks by many developers across the globe in building web applications of any size.

Since it’s been launched in 2009 as a tool for building scalable, server-side web applications it has brought about exponential growth in its usage.

In addition, Node facilitates quick prototyping in building unique projects.

Let’s check out this list of 10 Top NodeJS Frameworks:

1. Hapi.JS

Hapi is a powerful and robust framework that is used for developing APIs. The well-developed plugin system and various key features such as input validation, configuration-based functionality, implement caching, error handling, logging, etc. make the Hapi one of the most preferred frameworks. It is used for building useful applications and providing technology solutions by several large-scale websites such as PayPal, Disney.

Hapi builds secure, powerful, and scalable applications with minimal overhead and out-of-the-box functionality

Hapi is a configuration-driven model built to control web server operations. It has the unique function of being able to create a server on a specific IP , and has functions such as " onPreHandler ", we can process the request by intercepting the request and preprocessing the request before it is completed.

2. Express.JS

Express.js was built by TJ Holowaychuk, one of the members of the core Node project team. A large community backs this framework, so it has the advantages of continuous updates and reforms of all the core features. This is a minimalist framework that is used to build a number of mobile applications and APIs.

Express is a minimal and flexible Node.JS web application framework providing a robust set of features

It’s robust API allows users to configure routes to send/receive requests between the front-end and the database (acting as a HTTP server framework).

A good advantage with express is how it supports a lot of other packages and other template engines such as Pug, Mustache, EJS and a lot more.

3. Socket.io

It is used for building real-time web applications. It’s a Javascript library that allows the bidirectional data flow between the web client and server. Asynchronous data I/O, binary streaming, instant messaging are some of the most important features of this framework.


Socket the fastest and reliable real-time engine

4. Total.JS

Total.js is a modern and modular NodeJS supporting the MVC architecture. Angular.js, Polymer, Backbone.js, Bootstrap and other client–side frameworks are fully compatible with this framework. This framework is totally extensible and asynchronous. The fact that it does not require any tools such as Grunt to compress makes it easy to use. It also has NoSql embedded in it and supports array and other prototypes.

Total.js has some really beautiful versions like the Total.js Eshop, which contains a user interface optimized for mobile devices, and it is downloadable by all premium members. Eshop is one of the best Node.js e-commerce system. This is because of its many versions of unique content management system(CMS).

5. Sail.JS

This MVC framework has become very popular with NodeJS developers and this framework has gained traction through the development of chat applications, dashboards and multiplayer games. It is most famous for building data-driven APIs. It uses waterline for object-related mapping and db solutions. This framework uses Express.js for handling HTTP requests and is built upon Node.js.

Its compatibility with Grunt modules, including LESS, SASS, Stylus, CoffeeScript, Jade, Dust makes it an ideal candidate for browser-based applications.

Sail is highly compatible with several front-end platforms. Developers have enough freedom to their development while implementing this framework.

6. Derby

This is an MVC framework that is used for creating real-time mobile and web applications. Derby’s Racer, a real-time data synchronization engine for Node.js allows multi-site, real-time concurrency and data synchronization across clients and servers. The racer optimizes conflict resolution and allows real-time editing of the application by leveraging the ShareJS.

Derby is a full-stack framework for writing modern web applications

Derby is an open-source framework based on MVC structure and it is a full-stack NodeJS web framework. Derby is considered ideal for developing real-time collective applications. Using DerbyJS , developers can easily add customized codes and build real-time and effective custom made websites.

7. Meteor.JS

One of the fundamentally most used NodeJS frameworks is Meteor.JS. And this list would remain incomplete if we didn’t mention the MeteorJS framework. This is a full-stack framework of NodeJS which allows users to build real-time applications.

It is used to create both mobile and web-based javascript applications.

Backed by a huge community of developers, tutorials, custom packages and documentation, this framework is used to create some great web and mobile applications for only Javascript only.

8. Loopback

Loopback is a highly-extensible API framework that allows the user to create such APIs that can work with any kind of web client and can be easily bridged to backend sources. This new age modern application comes with complex integration. With Loopback being an open-source framework, the user can create dynamic REST APIs with a minimum or no knowledge of coding.

Highly extensible NodeJS framework for building APIs and microservices

Loopback permits developers to create SDKs and API documentation. This is possible due to widget-API explorer that comes in default with loopback.

Also, it comes with model-relation-support, third party login and storage service, API swagger, better user management policy

9. Koa

Koa was created by the same team that created Express.js and it is often referred to as the next-generation NodeJS framework. Koa is unique in the fact that it uses some really cool ECMAScript(ES6) methods that have not even landed in some browsers yet. It allows you to work without callbacks while providing you with an immense increase in error handling.

It requires a NodeJS version of at least 0.11 or higher.

KoaJS supports syn/await keywords and helps to manage the codes neatly.

Also, it doesn’t pack any bundle of middleware in the core. That makes server writing with Koa faster and enjoyable. KoaJS comes with more options for customization. It allows you to work with applications from scratch where developers can add those features only which they need.

10. NestJS

NestJs is a framework built with Node.js, It is used for building efficient, scalable Node.js server-side applications. Nest uses progressive JavaScript and is written with TypeScript. Being built with TypeScript means that Nest comes with strong typing and combines elements of OOP(Object Oriented Programming), FP(Functional Programming) and FRP(Functional Reactive Programming).

Advantages of the NodeJS framework

NodeJS Framework is now emerging as the most commonly used development framework for building frontend and backend for web applications. And it is the most preferred environment for custom web development. Let’s check some of the major advantages of NodeJS Framework:

  • Real-time working environment
  • Simple coding experience
  • Seamless data streaming
  • Same code pattern throughout development
  • User-friendly
Final analysis

After reading this article, we can of course understand that which framework to use depends entirely on the type of website and web application we want to build. The list of frames is endless and is everywhere in the JavaScript community.