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 :)
Related
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);
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.
I want to print the content of author.name an description of an embed, but I have no idea how.
Error:
Uncaught ReferenceError: author is not defined
const user = author.name;
message.channel.send(`${user} !!!`);
console.log(`${user} !!!`);
Example
I want to return the name "Juan" of .setAuthor and "text" of .setDescription from the embed , It is not the name of the author of the message
const embed = new MessageEmbed()
.setAuthor('Juan')
.setColor('RANDOM')
.setDescription("text")
message.channel.send(embed);
Sounds like you need to use message.author.username
client.on((message) => {
const username = message.author.username;
message.channel.send(`${username} !!!`);
console.log(`${username} !!!`);
})
problem solved
if(message.embeds.length >= 0)
{
let embed = message.embeds
for(let i = 0; i < embed.length; i++)
{
if (!embed[i] || !embed[i].author || embed[i].author.name === null) return;
{
const string4 = (embed[i].author.name);
message.channel.send(string4)
}
}
}
This code worked until I put it in a ForEach loop. The issue appears to be with the 'await fetch(integromat_webhook_url + aj);' line as it throws this error 'await is only valid in async function'.
I'm trying to send multiple webhooks to integromat.
Is there a way to do without the AWAIT part or make it an ASYNC Function please?
I'm a noob and just learning javascript :-).
Thanks
Jonathan
console.log('Filtered PIDs:', filteredPids);
let worksheetsCreated = filteredPids.length;
let integromat_webhook_url = "";
if(worksheetsCreated > 0){
output.markdown(worksheetsCreated + " worksheets created and being sent to indiviudal groups.");
//ADD FILTERED PRODUCTION WORKSHEETS TO TABLE
let recordsCreated = await batchAnd('Create', groupworksheetsBase, filteredPids);
//GET ARRAY OF GROUPS IN FILTERED PRODUCTION WORKSHEET
let unique = [...new Set(filteredPids.map(item => item.fields.Group))];
console.log('unique groups in filtered PIDs',unique);
//LOOP THROUGH UNIQUE GROUPS
unique.forEach(function(uGroup) {
integromatArray = filteredPids.filter(pid => pid.fields.Group == uGroup)
console.log(uGroup, integromatArray);
switch(uGroup) {
case 'Birkenhead':
integromat_webhook_url = "https://hook.integromat.com/mksobdvdxxxxxxxxxxx?pidsArray=";
break;
case 'Taupo':
integromat_webhook_url = "https://hook.integromat.com/9c6y4279kxxxxxxxxxx?pidsArray=";
break;
}
const aj = JSON.stringify(integromatArray);
console.log('stringify array',aj);
await fetch(integromat_webhook_url + aj);
});
} else {
output.markdown("No new worksheets to add.");
}
Thanks so much
Jonathan
just add async before the function keyword
unique.forEach(async function(uGroup) {
integromatArray = filteredPids.filter(pid => pid.fields.Group == uGroup)
console.log(uGroup, integromatArray);
switch(uGroup) {
case 'Birkenhead':
integromat_webhook_url = "https://hook.integromat.com/mksobdvdxxxxxxxxxxx?pidsArray=";
break;
case 'Taupo':
integromat_webhook_url = "https://hook.integromat.com/9c6y4279kxxxxxxxxxx?pidsArray=";
break;
}
const aj = JSON.stringify(integromatArray);
console.log('stringify array',aj);
await fetch(integromat_webhook_url + aj);
});
I used this approach to get it working as suggested by a friend of mine...
console.log('Filtered PIDs:', filteredPids);
let worksheetsCreated = filteredPids.length;
let integromat_webhook_url = "";
if(worksheetsCreated > 0){
output.markdown(worksheetsCreated + " worksheets created and being sent to indiviudal groups.");
//ADD FILTERED PRODUCTION WORKSHEETS TO TABLE
let recordsCreated = await batchAnd('Create', groupworksheetsBase, filteredPids);
//GET ARRAY OF GROUPS IN FILTERED PRODUCTION WORKSHEET
const unique = [...new Set(filteredPids.map(item => item.fields.Group))];
console.log('unique groups in filtered PIDs', unique);
//LOOP THROUGH UNIQUE GROUPS
await Promise.all(
unique.map(async uGroup => {
integromatArray = recordsArray.filter(pid => pid.fields.Group == uGroup);
console.log(uGroup, integromatArray);
switch (uGroup) {
case 'Birkenhead':
integromat_webhook_url = 'https://hook.integromat.com/mksobdvdu8uydiq9x22mxptgaye6ueji?pidsArray=';
break;
case 'Taupo':
integromat_webhook_url = 'https://hook.integromat.com/9c6y4279kydmqm7hswjutwhp7fu814aa?pidsArray=';
break;
}
const aj = JSON.stringify(integromatArray);
console.log('stringify array', aj);
console.log('url',integromat_webhook_url + aj);
const result = await fetch(integromat_webhook_url + aj);
return result;
})
);
} else {
output.markdown("No new worksheets to add.");
}
Change your forEach loop to a for loop and do not forget to put the async keyword before the function keyword like :
async function test() {
}