Creating a Bot/Node.js (JavaScript)

Node.js (JavaScript) is loosely typed and very easy to learn. If you are a beginner, don't sweat it. Your code doesn't have to be perfect.

**This guide is for Windows users.** Linux users, you're smart. Figure it out.

## How to Install Node.js

If you already have Node.js installed, go to the next step, silly.

But, if you haven't, follow these steps:

1. Go to nodejs.org and download the one recommended for most users.
2. Run the installer and spam next.
3. Once installed, restart your computer (or log out and log back in again). This is to add Node.js to your Windows path. It will make everything easier later.

## How to Make Your First Bot

This guide is going to be very simplified. There is more to bot creation than displayed here. I am also going to be avoiding difficult topics, such as, *shudder*, promises*...* That's something I can not teach you.

Well, first, you're gonna need a dope coding environment if you don't have one already. Yes, you can use Notepad, but why? Personally I use Visual Studio Code, and if you aren't fluent in any other environment, I'd suggest you get it as well. It's what I will be using and explaining how to use in this guide.

If you aren't gonna use it, I suggest reading through this next part anyways to make sure you have similar configs. Or don't.

### Installing and setting up Visual Studio Code

1. Download Visual Studio Code.
2. Run the installer and spam next (except maybe add "Open with Code" options in Select Additional Tasks).
3. You've installed Visual Studio Code! Now, run it.
4. When it opens, press Ctrl + , and search "windows exec". Make sure it is set to C:\Windows\system32\cmd.exe (or equivalent). If it isn't (for example, if it's PowerShell), change it.

Now you're done setting it up! Next, it's time to create the files for your bot. Go to somewhere on your Desktop or where ever and make a folder called "My Bot" or something, and then open it in Visual Studio Code. If you added "Open with Code" options in Select Additional Tasks during installation, you can just right click on the folder and select that option. Otherwise, you need to go into Visual Studio Code and press Ctrl + K and then Ctrl + O. Then find your folder and click "Select Folder".

Your Visual Studio Code should hopefully look like this:

   You can close that Welcome tab if you like.

### Starting your project

Go right click in the gray empty area underneath My Bot on the left and select "New File". Then, type in "bot.js" and hit enter. Now you should have your JavaScript file in your bot workspace.

Now, you need to install a package for your project. Packages are libraries you can download via the command line using NPM. We need to install a package to request to the Facebook API when we are ready.

To do this, press Ctrl + `. This will bring up the terminal in Visual Studio Code. In that terminal, type:

```
npm i fb

```

And then hit enter. If the command line says something like:

```
'npm' is not recognized as an internal or external command,
operable program or batch file.

```

You need to restart your computer and try again. **Have you installed Node.js?** Any other errors I can't help you with... ask in the #bot-help channel in the Discord!

Otherwise, you should have something like this:

The warns should be fine. Now you're ready to code!

### Coding Time!

We are going to make something extremely simple to test that everything works. We are going to post Hello World to your page. Amazing.

**If you don't have a token already, get one now. You're gonna need it.**

First, you need to add this on to your bot.js file:

```
 const FB = require('fb');

```

This line makes the code recognize the library we just installed as one it can use (or something).

In the code examples, I am going to be using my own token. **Make sure you are using your own token.** You aren't that dumb, are you? Of course not.

After the part where you require fb, you are going to enter in your token that you got earlier here for your script to use. Do it like this:

```
 FB.setAccessToken('YOURTOKENHERE');

```

In the future, I would learn how to make a JSON config file so you don't have your token sitting there in your code for everyone to see. But you're still learning, I don't want to annoy you with that kind of stuff yet.

Next, you're going to create your first Hello World post using the fb library! Don't worry too much about how scary it looks. You're a beginner, so you're a paster.

Insert this after your first two lines of code:

```
 let postContents = 'Hello World!';
 FB.api('me/feed', 'post', { message: postContents }, res => {
 if (!res || res.error) {
 return console.error(!res ? 'error occurred' : res.error);
 }
 console.log(`Post ID: ${res.id}`);
 });

```

Now what the hell is all this code? Well, let's go through it. If you don't give a shit, filthy paster, skip ahead.

```
 let postContents = 'Hello World!';

```

**let** is used to define variables. In this case, the variable **postContents** is being set to the string **'Hello World!'**.

```
 FB.api('me/feed', 'post', { message: postContents }, res => {
 ...
 });

```

**FB.api** is creating a new API request using the fb library to post to feed of the access token owner you defined earlier, using the contents of **postContents**. **res => {...}** is a callback function, that means what is going to happen after the API request has completed. In this example, arrow function notation is used. It's basically a fancier way of writing **function (res) {...}**. Hopefully this helps understanding it if you have used other languages in which arrow function notation isn't a thing.

```
 if (!res || res.error) {
 return console.error(!res ? 'error occurred' : res.error);
 }

```

This is error handling. If, for example, you entered your access token wrong or forgot to enter a message variable, the callback function would return an error. This if statement displays the error, to help with debugging.

```
 console.log(`Post ID: ${res.id}`);

```

Simple: This simply outputs the post ID that was generated from the API request. You can use it to go look at the post you generated.

Speaking of, why don't we do that right now? Let's get this code churning! Just to double check, your code should look like this before we run it:

```
 const FB = require('fb');
 FB.setAccessToken('YOURTOKENHERE');

 let postContents = 'Hello World!';
 FB.api('me/feed', 'post', { message: postContents }, res => {
 if (!res || res.error) {
 return console.error(!res ? 'error occurred' : res.error);
 }
 console.log(`Post ID: ${res.id}`);
 });

```

Now, in the terminal (If you closed it, press Ctrl + `), simply enter:

```
node bot.js

```

...and then...

*Note: If you encounter an error, check your code with mine. If you're still stuck, check out the #bot-help channel in the Discord!*

Obviously, your post ID will be different. Refresh your page, and there you go!

You're a fuckin' genius!

### Improvements

Now, hang on a second. This bot is hella boring! Who wants to like a bot that just posts "Hello World!" every 30 minutes? I don't. Well, not to worry, because we can fix that!

All you need is an idea, and my idea... hmm... how about a lottery prediction bot? It will predict lottery numbers. Yes, it's a simple idea, but you're simple minded, so that's what we're doing!

In the future, you will figure out how to create your own bot ideas. If you haven't already, learn the basics of JavaScript, otherwise you're gonna struggle. This guide is intended to help out people who have grasped the basics learn how to post to Facebook or whatever. And if you haven't learnt JavaScript yet, don't sweat it! Think of this as a mildly advanced introduction, then get learning afterwards!

So, what do we need for our bot? We need 6 random numbers, between 1 and 99. Pretend this lottery has numbers between 1 and 99 if your jurisdiction doesn't have a lottery with numbers between 1 and 99. Well, to generate random numbers, we have a built in JavaScript function for that:

```
 let lottoNumber1 = Math.random();

```

Nice! The problem is, this function only generates a number between 0 and 1, for example, 0.602607520266923.

So how about we multiply that number by 100?

```
 let lottoNumber1 = Math.random() \* 100;

```

Hmm... but now we have 26.38795248309207. That's still not what we want. And also, it is between 0 and 100. We want it between 1 and 99. So how do we fix that first?

Let's change the multiplier to 99, and add 1 afterwards.

```
 let lottoNumber1 = (Math.random() \* 99) + 1;

```

This algorithm ensures we only generate numbers between 1 and 99. But we still have a problem, and that's the decimals on the end. Well, we have a function for that, and it's called Math.floor(). This rounds down the number it's given to a round number. So, let's use it here:

```
 let lottoNumber1 = Math.floor(Math.random() \* 99) + 1;

```

Now we are getting crisp round numbers like 77, 89 and 14. Nice!

So, how would we put this into a bot? Well, we need 6 random numbers, so we could just repeat this variable 5 more times with incrementing names! Let's put this code after the FB.setAccessToken line you put earlier:

```
 let lottoNumber1 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber2 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber3 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber4 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber5 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber6 = Math.floor(Math.random() \* 99) + 1;

```

Truly astonishing, professional code.

If you're a statistics guy, you may notice that I don't account for the fact that the lottery balls aren't put back in the mix. Here's an explanation why I didn't account for that: I don't care.

And now, we want our bot to display those. How do we do that? Let's edit the postContents variable in our code already. So, instead of being set to Hello World, it should be:

```
 let postContents = `Lottery Prediction:\n${lottoNumber1} ${lottoNumber2} ${lottoNumber3} ${lottoNumber4} ${lottoNumber5} ${lottoNumber6}`;

```

What a long and ugly line. Get used to it.

You may notice that I changed the quotation mark (') to a tilde (`). Why? Well, using tildes as the quote marks means the JavaScript will let us add variables to our string in a very clean way, using **${variableName}**. It's a lot more clean and readable than when you use quotation marks, which is done by **' + variableName + '**. But, in the end, it all comes down to preference.

So, after all that, your code should look like this:

```
 const FB = require('fb');
 FB.setAccessToken('YOURTOKENHERE');

 let lottoNumber1 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber2 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber3 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber4 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber5 = Math.floor(Math.random() \* 99) + 1;
 let lottoNumber6 = Math.floor(Math.random() \* 99) + 1;

 let postContents = `Lottery Prediction:\n${lottoNumber1} ${lottoNumber2} ${lottoNumber3} ${lottoNumber4} ${lottoNumber5} ${lottoNumber6}`;

 FB.api('me/feed', 'post', { message: postContents }, res => {
 if (!res || res.error) {
 return console.error(!res ? 'error occurred' : res.error);
 }
 console.log(`Post ID: ${res.id}`);
 });

```

Your bot is now random and kind of interesting! Let's run it using this terminal (Ctrl + `) command again:

```
node bot.js

```

And let's see our post...

Congratulations. You fuckin' did it.

### Posting Images

I'm not going to be teaching you how to generate images, but I will teach you how to post them.

Soon.

This part is coming soon. I still need to figure it out in a non-retarded way.

### Now what?

It's time for you to implement your idea. But here's the catch: If you haven't already, **learn JavaScript.** Trust me. You don't want other people just coding your bot for you. Actually code it yourself, and understand how it works.

Once you've done that... how do you automate posting? Find out here.