I'm making mineflayer bot he follow me and try to kill me so when I go far from him he stop from
following me, And he has other problems like while he bridge he fall as stupid so how I can make him sprint while he follow me
My code :
const { versions } = require('minecraft-data')
const MinecraftData = require('minecraft-data')
const mineflayer = require('mineflayer')
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
const GoalFollow = goals.GoalFollow
const pvp = require('mineflayer-pvp').plugin
const armorM = require('mineflayer-armor-manager')
const bot = mineflayer.createBot({
host: 'EventWG.aternos.me',
username: 'bot'
})
//Follow the player
function followPlayer() {
bot.on('chat', (namee, msgg)=>{
const player = bot.players[namee]
if (msgg == "attack") {
bot.chat("ok " + namee)
bot.chat("/effect give #p minecraft:resistance 111111 255")
if (!player || !player.entity){
bot.chat("I can't see you " + namee)
return
}
const data = require('minecraft-data')(bot.version)
const movements = new Movements(bot, data)
bot.pathfinder.setMovements(movements)
const goal = new GoalFollow(player.entity, 2)
bot.pathfinder.setGoal(goal, true)
setInterval(() => {
const playerFilter = p => p.type === "player"
const playerr = bot.nearestEntity(playerFilter)
bot.pvp.attack(player.entity)
const sword = bot.inventory.items().find(item => item.name.includes('sword'))
if(sword) bot.equip(sword, "hand")
}, 2000);
}
})
}
bot.on('spawn', lookAtPlayer)
bot.on('spawn', followPlayer)
You can simple just use bot.setControlState just like
bot.setControlState('sprint', true);
Related
Loop over a list of ids and foreach id get data from api but, i can make only 40 requests per 10 seconds, i'm getting data from tbdb but i'm getting kicked by the api here is my code
Popular.findAll({ limit: 25 }).then((filmes) => {
for (let index = 0; index < filmes.length; index++) {
const element = filmes[index];
const id_filme = element.id_filme;
i get each movie id so i can make requests to the api with this function..
function fetchdata(id_filme) {
setTimeout(function () {
axios
.all([
axios.get(
`https://api.themoviedb.org/3/movie/${id_filme}?api_key=${process.env.API_KEY}&language=pt-BR`
),
axios.get(
`https://api.themoviedb.org/3/movie/${id_filme}/videos?api_key=${process.env.API_KEY}&language=pt-BR`
),
])
.then(
axios.spread(function (detalhes, linksyt) {
var filme = detalhes.data;
var youtube = linksyt.data;
// console.log(filme, youtube);
var filmesLista = new Array();
const title = filme.title;
const filmeid = filme.id;
if (Object.keys(filme.genres).length === 0) {
var genre = filme.genres;
} else {
var genre = filme.genres[0].name;
}
const overview = filme.overview;
const poster_path =
"https://image.tmdb.org/t/p/w500" + filme.poster_path;
const release_date = filme.release_date;
const vote_average = parseFloat(filme.vote_average);
const backdrop_path =
"https://image.tmdb.org/t/p/original" + filme.backdrop_path;
const imdb_id = filme.imdb_id;
const runtime = filme.runtime;
if (Object.keys(youtube.results).length === 0) {
var trailer = "";
} else {
var trailer =
"http://www.youtube.com/watch?v=" + youtube.results[0].key;
}
filmesLista.push([
filmeid,
title,
genre,
overview,
poster_path,
release_date,
vote_average,
backdrop_path,
imdb_id,
runtime,
trailer,
]);
console.log(filmesLista);
filmesLista.forEach((i) => {
const filmeid = i[0];
const title = i[1];
const genre = i[2];
const overview = i[3];
const poster_path = i[4];
const release_date = i[5];
const vote_average = i[6];
const backdrop_path = i[7];
const imdb_id = i[8];
const runtime = i[9];
const trailer = i[10];
Detalhes.create({
id_filme: `${filmeid}`,
title: `${title}`,
genre: `${genre}`,
release_date: `${release_date}`,
vote_average: `${vote_average}`,
imdb_id: `${imdb_id}`,
runtime: `${runtime}`,
overview: `${overview}`,
poster_path: `${poster_path}`,
backdrop_path: `${backdrop_path}`,
trailer: `${trailer}`,
});
});
})
);
o++;
if (o < 25) {
fetchdata(id_filme);
}
}, 10000);
console.log("INSERIDO NO BANCO");
}
fetchdata(id_filme);
the code works but, works so fast and i get kicked every time i run with more than 40 ids.. i'm strugling on just make 40 request every 10 secconds. anyone can help me please?
I am very new to Javascript so please bear with me! When I try to execute my script it doesnt respond! It just keeps dropping on to the next line waiting for me to write node index.js AGAIN. I have posted 2 images in the Imgur album, the first one is me writing node index.js and the second is me pressing enter and the response. Literally blank.
I would like some help as I feel like this is the last step to get my bot up and running! :D.
https://imgur.com/a/bRFFKKf
Here is my index.js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
var args = message.content.split(" ")
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
var args = message.content.split(" ")
if (message.author.bot == false) {
if (message.content.startsWith("$")) {
if (message.channel.id != CMDS && message.author.id != DISCORD_ID) {
message.reply("stop using cmds here idiot. <#" + CMDS + ">")
return;
}
}
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
switch (args[0]) {
case prefix + "pois":
var id = parseInt(args[1])
if (id) {
fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
//// clog(res)
if (res != 'Uaid not found, try again later') {
var search = res,
first = 'uaid_details'
var second = `owner_list`;
var itemdat = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
// clog(itemdat)
var search = res,
first = 'item_details'
var second = `uaid_details`;
var itemname = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
var search = res,
first = 'owner_list'
var second = `lucky_cat_uaid`;
var owners = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
message.reply(`Checking be patient bozo...`)
var em = new discord.messageEmbed()
.setFooter("Archs")
.setURL("https://www.rolimons.com/item/" + args[1])
.setColor("#ffc0cb")
.setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=" + itemdat["asset_id"])
.setTitle(`UAID ` + args[1])
.setURL(`https://www.rolimons.com/uaid/` + args[1])
.setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=` + itemdat["asset_id"])
if (itemdat.serial) {
em.addField('SERIAL', itemdat.serial)
}
em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
em.addField(`Last Traded`, itemdat["updated_relative_string"])
message.reply(em)
if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)
} else {
comped_detected = false
Object.keys(owners).forEach(x => {
var item = owners[x][0]
if (item && parseInt(x) + 2628000 >= Date.now() / 1000) {
fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
avatar.assets.forEach(a => {
if (badassets[a.id] != undefined) {
comped_detected = true
}
})
fetch("https://inventory.roblox.com/v1/users/" + item + "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
// clog(p)
var amt = 0
if (p.data) {
p.data.forEach(l => {
amt = amt + itemdata[l.assetId][4]
})
if (amt < 5000) {
comped_detected = true
}
}
})
})
}
})
}
}
}
)}
}
}
client
.login(token)
.catch(consola.error)
});
Again sorry if this sounds very dumb, I just started Javascript (node). Oh and one more thing! I am trying for it to work on discord with a discord command. Thanks for any help.
First off, if you're using intents, I assume you're using discord.js v13. The client.on("message" in that case would be client.on("messageCreate".
You don't need to input node index.js in repl.it. Instead, go to the 3 dots on your file like below and click on "Show Hidden Files". Once you see the .replit file, go into it and write on the first line: run = "npm start". Then, go into package.json (not package-lock.json) and write the code on the other screenshot (I highlighted the code so it's easier for you to read). That should fix all your problems! If you need additional reference, I have pasted some very helpful YouTube tutorials that I definitely recommend to watch.
Tutorial - Command handler and help command
Tutorial - How to use Discord.js v13 in repl.it
Your code seems to be in the form:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
// stuff
})
so basically it seems to attach some kind of listener, and then reaches the end. So it does nothing...
Here is my code (not the entire code, but I think this is the only really relevant part):
const timer = ms => new Promise(resolve => setTimeout(resolve, ms));
const createThrottler = (limitHeader) => {
let requestTimestamp = 0;
let rateLimit = 0;
return (requestHandler) => {
return async (...params) => {
const currentTimestamp = Number(Date.now());
if (currentTimestamp < requestTimestamp + rateLimit) {
const timeOut = rateLimit - (currentTimestamp - requestTimestamp);
requestTimestamp = Number(Date.now()) + timeOut;
await timer(timeOut)
}
requestTimestamp = Number(Date.now());
const response = await requestHandler(...params);
if (!rateLimit > 0) {
rateLimit = Math.floor((60 / response.headers.get(limitHeader)) * 1000);
}
console.log(limitHeader);
console.log(rateLimit);
return response;
}
}
}
const throttle = createThrottler("X-***-Ratelimit");
const throttleFetch = throttle(fetch);
function getRelease(idFiltered) {
return throttleFetch(`https://api.***.com/releases/${idFiltered}`, {
headers: {
'User-Agent': '***/0.1',
},
}).then(response => response.json())
.then(data => {
if (data.message === 'Release not found.') {
return { error: `Release with ID ${idFiltered} does not exist` };
} else {
const id = data.id;
const delimiter = document.getElementById("delimiter").value || "|";
const artists = data.artists ? data.artists.map(artist => artist.name) : [];
const barcode = data.identifiers.filter(id => id.type === 'Barcode')
.map(barcode => barcode.value);
var formattedBarcode = barcode.join(delimiter);
const country = data.country || 'Unknown';
const genres = data.genres || [];
const formattedGenres = genres.join(delimiter);
const labels = data.labels ? data.labels.map(label => label.name) : [];
const formattedLabels = labels.join(delimiter);
const catno = data.labels ? data.labels.map(catno => catno.catno) : [];
const formattedCatNo = catno.join(delimiter);
const styles = data.styles || [];
const formattedStyles = styles.join(delimiter);
const tracklist = data.tracklist ? data.tracklist
.map(track => track.title) : [];
const formattedTracklist = tracklist.join(delimiter);
const year = data.year || 'Unknown';
const format = data.formats ? data.formats.map(format => format.name) : [];
const qty = data.formats ? data.formats.map(format => format.qty) : [];
const descriptions = data.formats ? data.formats
.map(descriptions => descriptions.descriptions) : [];
const preformattedDescriptions = descriptions.toString()
.replace('"', '""').replace(/,/g, ', ');
const formattedDescriptions = '"' + preformattedDescriptions + '"';
console.log(idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
)
return [idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
];
}
});
}
But the "X-***-Ratelimit" header is clearly not being read correctly, as when I do
console.log(limitHeader);
console.log(rateLimit);
I initially get back
object
and thereafter
X-***-Ratelimit
Infinity
From the host's documentation:
We attach the following headers to responses to help you track your rate limit use:
X-***-Ratelimit: The total number of requests you can make in a one minute window.
X-***-Ratelimit-Used : The number of requests you’ve made in your existing rate limit window.
X-***-Ratelimit-Remaining: The number of remaining requests you are able to make in the existing rate limit window.
Any help please? TIA.
Edit: amazingly, I managed to greatly increase the rate-limit by getting my app authenticated thusly:
headers: {
'User-Agent': '***/0.1',
'Authorization': '*** key=***, secret=***',
},
However, I just took the key and secret from the site documentation, and I now get back this JSON response:
message - "Invalid consumer key/secret. Please register an app before making requests."
Edit2: OK, I worked out how to register my app now. I'm proceeding to further tests.
Edit3: the rate-limit in effect from the host is much better now, but my app is still not reading the header from the response correctly, so limitHeader is still coming back as "Infinity", instead of some meaningful/appropriate value.
When I require code and load it into my main code for my Discord bot, it's unable to find variables or sub parts of them even if they're defined in the main code.
Required code:
module.exports.stupid = () => {
bot.on('messageCreate', (msg) => {
if (msg.content === 'yes'){
bot.createMessage(msg.channel.id,'yes!!')
}
});
}
-- Code in main script
const Eris = require('eris');
const axios = require('axios');
const firebase = require('firebase/app');
const FieldValue = require('firebase-admin').firestore.FieldValue
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccount.json');
// Commands
const cm1 = require('./staff.js')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
let db = admin.firestore()
const bot = new Eris('token_removed');
let prefix = ';'
const sprefix = ">"
const botname = "bee"
const version = '0.6.6'
const emoji = '<:bee_logo:730125457638425039>'
const semoji = '<:bshield:729463155587022860>'
const remoji = 'buzz:683498511341191245'
const bee_check = '<:bee_check:729878268811018300>'
const bee_dash = '<:bee_dash:729878268790177862>'
const bee_x = '<:bee_x:729878268848898159>'
const hex = 0xF3DC3E
const gethex = 'F3DC3E'
const server = "Amazon (Linux/UNIX)"
const today = new Date();
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
cm1.stupid()
You'll have to edit a few lines in order to make everything work as intended :
Replace your module.exports.stupid = () => { with module.exports.stupid = (client) => {
When calling the function (cm1.stupid()), you need to pass the bot variable as an argument like so: cm1.stupid(client)
Hope this helps !
I tried to make and embed and add reactions to it.
but the embeds find is returning undefined when console.log
I am trying to make reaction role the following code is to create one.
I can successfully create embed but I can't add desired reactions because it is not able to find embed
const Discord = require('discord.js')
module.exports.run = async (client,message,args,con)=>{
message.channel.send("How many reaction role you want to create");
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
const n = (answer.map(answers => answers.content).join())
if(isNaN(n)) return message.channel.send("Enter a Number")
message.channel.send("Enter the title");
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
const embtitle = (answer.map(answers => answers.content).join())
var a = []
var b = []
for(var i =0; i<n;i++){
message.channel.send("Enter the emoji")
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
a[i] = (answer.map(answers => answers.content).join())
message.channel.send("Enter the role name")
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
b[i] = (answer.map(answers => answers.content).join())
}
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += a[i]+ ' '+b[i] +'\n';
}
return finalString;
}
const embed = new Discord.MessageEmbed()
.setTitle(embtitle)
.setColor("BLUE")
.setDescription(embstr());
message.channel.send(embed);
const embedMsg = message.embeds.find(msg => msg.title === 'some');
console.log(embedMsg)
for(var i = 0;i<n;i++){
var emoid = a[i].slice(1,-1)
emoid = emoid.split(':')
emoid = emoid[2];
console.log(emoid);
const embedMsg = message.embeds.find(msg => msg.title === embtitle);
console.log(embedMsg)
if(embedMsg){
message.react(emoid)
}
}
}
module.exports.config = {
command: 'create'
}
Instead of constantly trying to find the message you sent like this :
const embedMsg = message.embeds.find(msg => msg.title === 'some');
You could simply assign the message you sent to a variable, like this :
const embedMsg = await message.channel.send(embed); // I used await since I saw your function is asynchronous
Then react to the message this way :
await embedMsg.react('emote Name/ID/Whatever');
Hope this will help :)