How to make a Roblox Bot using Roblox API!

How to make a Roblox Bot using Roblox API!

Introduction

Been a while hasn’t it?

Today, I will be showing YOU how to make a roblox bot which will update it’s about page to the time left until new years! Without further ado, lets get right into it!

Installing needed software

NOTE: if you already have Visual Studio code and Node.js installed, you can skip this part.

We will need 2 stuff in order to make our bot. Visual Studio Code(Vs code) and node.js.

Install VS code: Download Visual Studio Code - Mac, Linux, Windows
Install node.js: Node.js

do whatever the installers says.

Setting up project

Creating project folder

In order to set up project, we need to first create a folder. To do so, right click in the file explorer and click “new” and then “folder.” This folder can be anywhere in your computer, but I recommend putting your folder inside of documents as that is a good place to put these kinds of stuff.

Next, name the folder whatever you want, but personally i’ll be naming mine “New years bot roblox.”

After you name your folder, make sure to memorize the folder’s path as you will need it for the next part.

Opening project folder in VS Code.

First, open up VS code. You should see a window like this:

Next, click File → Open Folder and select your project folder.

Once you selected your folder, open the terminal terminal → new terminal.
image

now type the following commands in the terminal:

initialize project:

npm init -y

install dotenv, this is to hide credentials:

npm i dotenv

install node-fetch in order to send requests to roblox api.

npm i node-fetch@2.6.1

install typescript:

npm i typescript -g

install node types for node.js

npm i @types/node --save

and once you do all of that, your project explorer should look something like this(your icons may be different than mine)

if it does, we can (almost) start scripting. But before we do that, we need to create a bot account.

creating a bot account

In this section, we will create a bot account.
DO NOT use your main account for this or any accounts you value. You should ALWAYS use alt accounts for stuff like this.

First, open an incognito tab. DO NOT OPEN A NORMAL TAB. And create a new account. For reference, my account will be named TheNewYearsBot. Make sure to make the account over 13 so that filters are less harsh.

After you create your bot, grab the .ROBLOSECURITY cookie, this is different depending on your browser. But for this example, i’ll show you how to get it on Chrome. If you dont know how to on your browser search: How to get .ROBLOSECURITY [BROWSER_NAME] or How to get cookie [BROWSER_NAME].

Right click anywhere and press “Inspect Element.” You should see something like this:

Next, click on Application and grab the .ROBLOSECURITY from there. Make sure to copy it to your clipboard. You may close the incognito tab. DO NOT LOG OUT this will reset your .ROBLOSECURITY cookie. If you are outside of the US make sure to use a vpn and connect to the US and get your cookie from there. Otherwise your cookie will reset.

creating .env and storing .ROBLOSECURITY for later use in code.

Now that we have the .ROBLOSECURITY go back to vs code and create a new file called .env. Rightclick in project explorer and click “new file.”

We will store our .ROBLOSECURITY there for security. So that our .ROBLOSECURITY wont be in plain text in our code.

Inisde the .env file, type the following.

TOKEN=[.ROBLOSECURITY]

make sure to keep the TOKEN part as that is how we will reference this variable inside our code.

adding needed folders

we will need to add some folders to our project. Create 2 folders “src” and “out”. We will type our code inside of src, and our out folder is where our typescript code will be compiled to.

adding tsconfig.json

since we will be using Typescript, lets create a tsconfig.json file. Simply make a tsconfig.json file and paste the following settings. Configure as you like, I will not explain this code as i dont see it as important.

{
    "compilerOptions": {
        "rootDir": "src",
        "outDir": "out",
        "skipDefaultLibCheck": true
    }
}

Now we can start scripting, finally!

Scripting our bot

finally, we can start scripting!! Woo hoo!

Inside our src folder, create a new file called “index.ts.” And inside the terminal type tsc -w

After creating the file, lets insert all our dependencies!

import * as fetch from "node-fetch"
import { config } from "dotenv"

config() // initialize environment variables(.env) to access .ROBLOSECURITY

Next lets add our variables and functions.

import fetch from "node-fetch";
import { config } from "dotenv"

config() // initialize environment variables(.env) to access .ROBLOSECURITY

const token = process.env.TOKEN // .ROBLOSECURITY\

async function getNextYear() {
    // TODO: make function get the next year value
}

async function getTimeUntilNewYears() {
    // TODO: make function return the time until new years
}

async function getCsrfToken() {
    // TODO: get csrf token in order to set bot's about page
}

async function setAboutPage() {
    // TODO: Make function set about page
}

lets first start off by adding our getNextYear function. This function will return the next year value. For example, if the year is 2022, the function will return 2023.

import fetch from "node-fetch";
import { config } from "dotenv";

config(); // initialize environment variables(.env) to access .ROBLOSECURITY

const token = process.env.TOKEN; // .ROBLOSECURITY\

async function getNextYear() {
    const date = new Date(); // make new date object
    const currentYear = date.getUTCFullYear(); // get the current UTC year.
    const nextYear = currentYear + 1; // add 1 to the current UTC year, as this will be our next year

    return nextYear;
}

async function getTimeUntilNewYears() {
    // TODO: make function return the time until new years
}

async function getCsrfToken() {
    // TODO: get csrf token in order to set bot's about page
}

async function setAboutPage() {
    // TODO: Make function set about page
}

// next getNextYear function

getNextYear().then((year) => {
    console.log(year);
});


now we need to run our code in order to test the getNextYear function. To do so, we can use node out/index.js but this will require use to run this command anytime we edit our code. To fix this, we can use something called nodemon which will run node out/index.js anytime you save.

To install nodemon do the following in the terminal:

npm i nodemon

after that, create a new terminal and type nodemon out/index.js

After running this command, you should see 2023 in your terminal. If you’re watching this in the future, this date will be different for you.

After we do that function, lets make the getTimeUntilNewYears function!

async function getTimeUntilNewYears() {
    const nextYear = await getNextYear(); // get the nextyear value
    const nextYearTimestamp = `${nextYear}-01-01T12:00:00.00Z`; // this will be the timestamp for when next year comes.

    const nextYearDate = new Date(nextYearTimestamp);
    const currentDate = new Date();

    const timeleft = nextYearDate.getTime() - currentDate.getTime();

    const days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
        (timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

    return {
        days,
        hours,
        minutes,
        seconds,
    };
}

Now to test, we can add this to the bottom of our code.

getTimeUntilNewYears().then((timeLeft) => {
    console.log(timeLeft);
});

As you can see, you will be prompted with a dictionary saying the time left. Now we can do the getCsrfToken function, this function will be used to get the x-csrf-token which is needed for setting the about page. This token is a security measure to prevent 3rd party apps from randomly setting your about page.

async function getCsrfToken() {
    // here's the process:
    // send in a friend request to a random user, of which will fail. Grab x-csrf-token
    // from the response, and return.

    try {
        const response = await fetch(
            "https://friends.roblox.com/v1/users/321/request-friendship",
            {
                method: "POST",
                headers: {
                    Cookie: `.ROBLOSECURITY=${token}`,
                },
            }
        );

        if (response.status === 403) {
            return response.headers.get("x-csrf-token"); // get x-csrf-token from headers
        }
    } catch (e) {
        console.log(`Failed to get x-csrf-token because: ${e.message}`);
    }
}

to test, add this code at the bottom:

getCsrfToken().then((csrf) => {
    console.log(csrf);
});

as you can see, you’ll get a random string. This string is a token which is required for certain roblox apis such as the set about page api.

Now we can start the fun part, the setting about page part!! Woo hoo!

so now let’s right the setAboutPage() function!

async function setAboutPage() {
    try {
        const csrfToken = await getCsrfToken(); // get x-csrf-token
        const timeLeft = await getTimeUntilNewYears(); // get time until new years

        // send request
        const response = await fetch(
            "https://accountinformation.roblox.com/v1/description",
            {
                method: "POST",
                headers: {
                    Cookie: `.ROBLOSECURITY=${token}`,
                    "Content-Type": "application/json",
                    "x-csrf-token": csrfToken,
                },
                body: JSON.stringify({
                    description: `I'm the NewYearsBot!

Times left until new years:
Days: ${timeLeft.days}, Hours: ${timeLeft.hours}, Minutes: ${timeLeft.minutes}, Seconds: ${timeLeft.seconds}`,
                }),
            }
        );

        if (!response.ok) {
            throw new Error(`${response.status} ${response.statusText}`);
        }

        console.log("set about page");

        const data = await response.json();
        return data;
    } catch (e) {
        console.log(`failed to set about page because: ${e.message}`);
    }
}

now to test, we can do at the bottom:

setAboutPage();

now if you go to your bot’s about page, you will see the following result:

now lets make it so that the setAboutPage function will be called every 60 seconds(any time lower than this could result in errors.)

To do this, we can use setInterval

do the following at the bottom of your code

setAboutPage();

const intervalTime = 5 * 60 1000; // 5m to ms.
setInterval(async () => {
    await setAboutPage();
}, intervalTime);

and now, you’ve completed your FIRST ROBLOX BOT! Congratulations! BUT WAIT we need to host this bot, as the bot will stop running when we close our computer. So we can use a service like replit.com with pinging.

Hosting our bot

Now that we’ve made our bot, we can use replit to host our bot with pinging. We must use pinging as replit will stop hosting your bot after u close your browser.

There are 2 ways we can do pinging:

  1. use uptimerobot, but this will ping replit every 5 minutes(you can pay them to make it less than this), which can cause for some downtime.
  2. create our own custom pinging, which will ping our server every 30 seconds, causing for no downtime whatsoever. We can do this directly from our server with 3 lines of code. We will be using this method.

So before we go to replit, create a new file called server.ts

type: npm i express inside your terminal and paste the following code(not explaining as I simply cant be bothered)


import * as express from "express";

const app = express();

app.get("/", (_req, res) => {
    res.send("server is running");
});

export default function () {
    app.listen(3000, () => {
        console.log("Server started");
    });
}



change our index.ts file to this:

import fetch from "node-fetch";
import { config } from "dotenv";
import startServer from "./server";

config(); // initialize environment variables(.env) to access .ROBLOSECURITY

const token = process.env.TOKEN; // .ROBLOSECURITY

async function getNextYear() {
    const date = new Date(); // make new date object
    const currentYear = date.getUTCFullYear(); // get the current UTC year.
    const nextYear = currentYear + 1; // add 1 to the current UTC year, as this will be our next year

    return nextYear;
}

async function getTimeUntilNewYears() {
    const nextYear = await getNextYear(); // get the nextyear value
    const nextYearTimestamp = `${nextYear}-01-01T12:00:00.00Z`; // this will be the timestamp for when next year comes.

    const nextYearDate = new Date(nextYearTimestamp);
    const currentDate = new Date();

    const timeleft = nextYearDate.getTime() - currentDate.getTime();

    const days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
        (timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

    return {
        days,
        hours,
        minutes,
        seconds,
    };
}

async function getCsrfToken() {
    // here's the process:
    // send in a friend request to a random user, of which will fail. Grab x-csrf-token
    // from the response, and return.

    try {
        const response = await fetch(
            "https://friends.roblox.com/v1/users/321/request-friendship",
            {
                method: "POST",
                headers: {
                    Cookie: `.ROBLOSECURITY=${token}`,
                },
            }
        );

        if (response.status === 403) {
            return response.headers.get("x-csrf-token"); // get x-csrf-token from headers
        }
    } catch (e) {
        console.log(`Failed to get x-csrf-token because: ${e.message}`);
    }
}

async function setAboutPage() {
    try {
        const csrfToken = await getCsrfToken(); // get x-csrf-token
        const timeLeft = await getTimeUntilNewYears(); // get time until new years

        // send request
        const response = await fetch(
            "https://accountinformation.roblox.com/v1/description",
            {
                method: "POST",
                headers: {
                    Cookie: `.ROBLOSECURITY=${token}`,
                    "Content-Type": "application/json",
                    "x-csrf-token": csrfToken,
                },
                body: JSON.stringify({
                    description: `I'm the NewYearsBot!

Times left until new years:
Days: ${timeLeft.days}, Hours: ${timeLeft.hours}, Minutes: ${timeLeft.minutes}, Seconds: ${timeLeft.seconds}`,
                }),
            }
        );

        if (!response.ok) {
            throw new Error(`${response.status} ${response.statusText}`);
        }

        console.log("set about page");

        const data = await response.json();
        return data;
    } catch (e) {
        console.log(`failed to set about page because: ${e.message}`);
    }
}

// set about page
setAboutPage();

const intervalTime = 60 * 1000; // 60s to ms.
setInterval(async () => {
    await setAboutPage();
}, intervalTime);

// start server
startServer();

now, sign up for replit and click “create” which is located at the side bar

choose “node.js” as your project type and change the name to whatever you want.

Now, go back to vs code and copy the code of out/index.js(the out folder which has an index.js file) and paste it to the index.js code on replit.

now create a new file called “server.js” and copy the code from out/server.js

now click the Run button at the top

if you get an error like this:


Error [ERR_REQUIRE_ESM]: require() of ES Module 

go to the shell and type npm i node-fetch@2.6.1

now run the code and it’ll run like normal! Except you may be getting errors such as failed to set about page because: 401 Unauthorized This is because replit doesn’t have our environment variables.

To add one, go to the secrets tab at the side

and set the key to “TOKEN” and set the value to your .ROBLOSECURITY and click “Add new secret”
image

now your bot is hosted!! woohoo! BUT WAIT hosting will stop whenever you close your browser! Fix? pinging. The reason why we made the server file is to start a webserver on repl.

First, get the server url, which should be at the side and copy the url at the top

now add the following code at the bottom of the script(index.ts in vs code):

fetch("REPL URL").then(() => {
    console.log("pinged server");
});

setInterval(async () => {
    await fetch("REPL URL");
    console.log("pinged server");
}, 30 * 1000);

and copy the compiled code from out/index.js via tsc -w in the terminal.

and now, you’re finally finished! congratulations!

**It is also recommended that you make an Uptime Robot pinging incase the server goes down for whatever reason. **

PS: if you get any errors such as a 429 too much requests, try increasing the intervalTime variable to 5 minutes rather than 1 minute. I discovered this while writing this part and im too lazy to fix all the code and stuff SO DO IT YOUR SELF.

Extra ways to learn

if you want to learn more here are some stuff I recommend checking out:

My friends TheMessageMan bot: https://github.com/Biack1st/MessageMan-messaging-program
Roblox: Roblox api docs

if you have any suggestions on what I should add here, feel free to say!

Outro

that took long didn’t it? Oh well, hope u learned something new! Anyways I’m out, this took around over 2 hours to write. So feel free to heart this post or whatever.

also if you want to see this bot in action, you can see my bot man here

24 Likes

Man. It took me a whole 2 mins to scroll down

What functions can this bot have?

Thanks for making this tutorial, even though Im probably not gonna make one, im lazy

4 Likes

your bot can basically do anything you can do on the roblox site. I just made a simple example of using the about page.

3 Likes

Here’s my thoughts:

  • You should use a Roblox library instead of managing the cookie yourself. There’s no point in reinventing the wheel - libraries like noblox.js and rblx simplify this process for the developer.
  • TypeScript is unnecessary for this tutorial, as you don’t seem to utilize types anywhere
  • Going along with the last one, if TypeScript isn’t required, you don’t need to install VSC and can dive straight into Replit from the beginning.
2 Likes

although this is the case most of the time, for this example we were setting the about page. Which can’t be done with noblox. And dont get started with rblx, why would I want to use a module with 6 weekly downloads?

You dont only need to use typescript for types. I prefer to use typescript as that will show errors inside the code. Rather than testing it and then realizing there’s an error

You could, but replit doesn’t have a very good ide experience. I prefer to write code in VSC and move to replit.

it seems like you didn’t even read the guide and simply went through it with all this nonsense criticism

2 Likes

Both noblox and rblx are just examples (although rblx does allow you to set a description). You’re able to use any library you want; the point is that for a beginner’s tutorial on how to use NodeJS to make a Roblox bot, it should be simple & beginner-friendly. A simple method like user.setDescription() is much friendlier than sending an HTTP request with node-fetch.

That’s true, but this is a beginner’s tutorial. Simplification is key if you want to really have the end-user understand exactly what you’re doing. Plus, they shouldn’t need to worry about errors if they’re using code from a tutorial.

Again, simplification. The copying from the out dir, discarding the old .env file, and installing local packages when you don’t need them are extra steps that can confuse the reader. It’s better to have a few well-explained steps than many steps that can leave the reader with questions.

Criticism is normal, and my points aren’t necessarily wrong. I don’t benefit from giving my criticism - you do. I’m giving you my thoughts on how you can improve this tutorial so future viewers will understand how to reach the end result without potentially leaving with questions, like why TypeScript was necessary, or why there’s a code editor and a decently sized node_modules folder on their hard drive that’s not being used. By diving straight into Replit, the VSC & NodeJS/npm installations can be skipped.


If you’d like to continue this, my DMs are open :slight_smile: I don’t want to further clog this thread.

3 Likes

yeah, many people like me dont have enough money to buy a VPS. But a VPS is indeed a good solution for hosting

2 Likes

There’s a section at the end of the tutorial where it pings the hosting URL, but even that isn’t effective as repls will completely refresh every once in a while and therefore stops the setInterval loop.

@TheH0meLands
I would look into UptimeRobot. The free tier is enough and has kept my Discord bots alive for well over a year.

3 Likes

hmm seems like a good idea. I used this method of pinging for a lot of my bots and didn’t encounter any down time. While with uptimerobot, my bot would go down every once in a while. I’ll try looking into it and update the guide as needed.

2 Likes

Replit doesn’t allow Roblox cookies. If you use a Roblox cookie on replit then the cookie will be reset.

it’s never happened to me? I believe cookies only reset when someone logs into your account from a different IP. Not when you use the roblox api(i think)

so it’s not possible to use cookies on replit then.

?? I just said that cookies dont reset when u use the roblox api. Only when you log into the account from a different ip? Am I misunderstanding?

I use the replit to host all my bots and I have no issues with cookies resetting.

yeah your misunderstanding bro, replit resets the cookie since replit has its own built in ip and you cant fix that

theres not even an issue in the first place. The cookie doesn’t reset on replit. It only resets when another ip logs into your account.

Bots use the roblox api to do actions. Cookies only reset when someone logs into your account from a different ip. Using the roblox api on behalf of another account doesnt(i believe.)

I use replit for all my bot hosting and I was able to host my bot for around 2 months straight and no cookie resetting whatsoever.

bro learn to read I didn’t say it resets because of apis it resets because replit resets it due to replit having a ip built in.

theres no need for you to be rude. Im simply saying the cookie wont reset whatsoever due to replit. Would you please provide some sources?

I assume you’re talking about the ip changes resetting cookies. But that only affects you when someone logs into your account, not when you use the roblox api.

1 Like
const noblox=require('noblox.js')

const token=process.env.TOKEN; // .ROBLOSECURITY

async function startApp () {
    const currentUser=await noblox.setCookie(token) // This will cause to reset cookie on replit
    console.log(`Logged in as ${currentUser.UserName} [${currentUser.UserID}]`)
}
startApp()

bro what’s wrong with you, show me when I said it does? bet u can’t

there is no reason Roblox would reset cookies for using the API
unless you use replit because it resets the cookie due to replit IP.