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.
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:
- 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.
- 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”
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