I have a problem with version 12 of discord JavaScript.
I get this error but I changed the find function.
What else can he have?
upBot.send is not a function
let upBot = bot.channels.cache.find(ch => ch.id = "");
let upBotEmbed = new Discord.MessageEmbed()
.setColor(colours.red_light)
.addField(`${bot.user.username} online`, datetime)
.setFooter(`Test`, bot.user.displayAvatarURL);
upBot.send(upBotEmbed).then(m => m.delete(900000))
The reason you are getting this error is because you are not using the delete timeout correctly.
Change
.delete(900000)
to
.delete({ timeout: 900000 })
The delete property takes an object in version v12.
find function should returns a list of object. Try this:
...
for(const upBot of upBots) {
upBot.send(upBotEmbed).then(m => m.delete(900000))
}
Related
I am merging a bot under discord.js v12 to a newer bot with discord.js v14.
However it's my first experience on the node and I don't understand everything, I'm doing well in lua but I don't understand...
The events return me errors either it does not find the guild or it is impossible to rename a player, or a player is not found...
Here is how it is, I comment you the events according to the return of log that I have
on("DiscordBot:RenameMember", (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
if (targetguild) {
let target = targetguild.members.fetch(discordid); // I got on log : [object Promise]
if (target) {
target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
}
}
});
I made a multitude of tests with cache, without cache but nothing makes it all I find is similar and does not work here...
Here you will find the launch of the bot :
https://hastebin.com/ovipelopam.js
And here is the file I made separately to find my way around :
https://hastebin.com/azaraqituh.js
Do you have an idea ?
In your case targetguild.members.fetch(discordid) seems to return a Promise, which is an async operation. Therefore target has no value right away, but instead, has to either be awaited, or the rest of the code has to be put in the then function, that can be set to the promise.
Here is an example where you await the promise to resolve. In order to achieve this you have to define your function as async, so that it itself returns a Promise:
on("DiscordBot:RenameMember", async (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
if (targetguild) {
let target = await targetguild.members.fetch(discordid); // I got on log : [object Promise]
if (target) {
target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
}
}
});
Thank you for answering and explaining,
I still don't understand how it works, but it will come...
I had some problems with the setNickname and it started to work without understanding why either :)
Here is what I get in the end :
on("DiscordBot:RenameMember", async (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first();
if (targetguild) {
let target = await targetguild.members.fetch(discordid);
if (target) {
// target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
// target.members.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
let targetRename = await target.setNickname(fullname, 'Modification correspondant au profile InGame'); // That work
}
}
});
Thanks again :)
I ve been trying to do a report 'bug command'.
This is my code so far:
bot.on('message', async (client, message, args) => {
let parts = message.content.split(" ");
if(parts[0].toLocaleLowerCase() == '!bugreport') {
const owner = client.users.cache.get('567717280759283883');
const query = args.join(" ");
if(!query) return message.channel.send('Bitte schildere den Bug').then(m => m.delete({timeout: 5000}))
const reportEmbed = new Discord.MessageEmbed()
.setTitle('Fehlermeldung')
.setThumbnail(message.guild.iconURL())
.addField('Fehler:', query)
.addField('Server:', message.guild.name, true)
.setFooter(`Gesendet von ${message.author.tag}`, message.author.displayAvatarURL({dynamic: true}))
.setTimestamp();
owner.send(reportEmbed);
}
});
The error code always says that 'content' is undefined, but I do not understand that
Assuming your bot is a Client, it seems you're expecting the message event to pass more arguments than it actually does. Although that would indicate you're trying to read content from undefined, not that content itself is undefined.
The Client#message event allows 1 parameter which is an instance of Message. Change your code to this
bot.on('message', async (message) => {
//code here
})
You probably got confused with message handlers, where you can customize the function to your liking.
The message event only passes the received message according to the discord.js docs. Your event handler should look more like this at the start:
bot.on('message', async (message) => {
Note this won't completely fix your command, as you'll still be missing the args and client parameters. Here's my best guess as to where to get those from based on how you're using them:
const args = parts.splice(0,1); // gives array of everything after "!bugreport"
const client = bot; // alternatively, replace client with bot in your code
I'm trying to use multiple user mentions and message.mention.members.first() cannot do this. So I did some digging and found this function from Parsing Mention Arguments:
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
When I try to use this function I get the "Discord JS - TypeError: Cannot read property 'setChannel' of undefined" here is the code causing the error
let channel = client.channels.cache.find(channel => channel.name === args[0]);
const user1 = getUserFromMention(args[1]);
const user2 = getUserFromMention(args[2]);
message.member.voice.setChannel(channel.id);
user1.voice.setChannel(channel.id);
user2.voice.setChannel(channel.id);
This code Is meant to move Myself and mentioned users to selected Voice Channel it works perfectly fine when using message.mention.members.first() but can only handle one out of two of the mentioned users.
I was wondering if there was a fix for my current error or if there is another way I should be working this out?
Remember that,
message.mentions.members- Returns a GuildMember whereas
client.users.cache.get - Returns a User
You can only move/disconnect GuildMembers across VCs.
Therefore you can use message.mentions.members, which returns a Collection of all mentioned Users.
let channel = client.channels.cache.find(channel => channel.name === args[0]);
message.member.voice.setChannel(channel.id);
message.mentions.members.each(u => {
u.voice.setChannel(channel.id);
})
The problem can be, that the user is not in cache, so you must use GuildMemberManager#fetch(id). Problem is, that this function is async. The easiest solution is to make getUserFromMention and the functions where you use it async and use await.
I have a gcloud pub/sub-function that performs a simple query on a collection. It was working fine before Oct 08. Now I am seeing "The requested snapshot version is too old" error messages.
I have created an HTTP function with the same code and run it manually, it works perfectly fine.
Here is the function:
// 0 3 * * * - at 03:00 AM every day
exports.GenerateRankings = functions.pubsub.schedule('0 3 * * *')
.onRun((context) => {
console.log("GenerateRankings Task started")
const playersCollection = admin.firestore().collection('players')
playersCollection.orderBy("Coin", "desc").get()
.then((qs) => {
console.log("Fetching Players by Coin")
// some staff
return true
})
.catch((error) => {
console.error("Error fetching players", error)
return false
})
})
And here is the error stack:
9 FAILED_PRECONDITION: The requested snapshot version is too old.
at Object.callErrorFromStatus (/workspace/node_modules/#grpc/grpc-js/build/src/call.js:31:26)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client.js:327:49)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:305:181)
at /workspace/node_modules/#grpc/grpc-js/build/src/call-stream.js:124:78
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Caused by: Error
at Query._get (/workspace/node_modules/#google-cloud/firestore/build/src/reference.js:1466:23)
at Query.get (/workspace/node_modules/#google-cloud/firestore/build/src/reference.js:1455:21)
at /workspace/index.js:22:47
at cloudFunction (/workspace/node_modules/firebase-functions/lib/cloud-functions.js:130:23)
at /layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:198:28
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 9,
details: 'The requested snapshot version is too old.',
metadata: Metadata { internalRepr: Map {}, options: {} }
}
I know there is another unanswered question
"The requested snapshot version is too old." error in Firestore
similar to this. I am facing this problem with pub/sub-functions.
Thanks for your help.
In case someone faces this problem, I answer my own question.
After a lot of reading, testing, I've noticed there is a warning in my logs like "Function returned undefined, expected Promise or value". Because I return a promise in my function, I was not paying attention to this.
Adding a return on top of my function fixed my warning, and my function has been running successfully for 5 days.
return exports.GenerateRankings = functions.pubsub.schedule('0 3 * * *') ...
I encountered the same problem, in my case, the code was as follows and the error mentioned in this issue was returned.
const userSnapshots = await this.firestore.collection('Users').where('archive', '==', false).get();
const users = userSnapshots.docs
users.map(async (user) => {
//code to update user documents
});
Then I changed the code to the following and it worked without returning the error mentioned in this issue.
const userSnapshots = await this.firestore.collection('Users').where('archive', '==', false).get();
const users = userSnapshots.docs
const markPromises = users.map(async (user) => {
//code to update user documents
});
await Promise.all(markPromises);
I don’t know this is the correct answer to this question but this worked for me.
For my case, I guess the problem was because of the size of data, and time it took to do the data management. I have split data into parts of 5000 elements :
const store = getFirestore(initializeApp(myConfig));
const collectionRef = store.collection("users");
const limit = 5000;
let docs: Array<QueryDocumentSnapshot<DocumentData>>;
let querySnapshot: QuerySnapshot<DocumentData>;
let query = collectionRef.limit(limit);
do {
querySnapshot = await query.get();
docs = querySnapshot.docs; // thanks to #prahack answer
for (const doc of docs) {
await manageMyData(doc.id, doc.data());
}
if (docs.length > 0) {
// Get the last visible document
query = collectionRef.startAfter(docs[docs.length - 1]).limit(limit);
}
} while (docs.length > 0);
Without my data managing, i can use part of 10.000 elements (limit = 10000), but with management, i should down to 5000.
I spent hours trying to run a list of actions inside a "pubsub" and then I decided to try the following code and it worked.
this.firestore.collection('Users').where('archive', '==', false).get().then(snap=>{
// Code Here
});
I feel ridiculous asking for help on this so in advance I apologize, but I got this error in my code when trying to create a channel. Here is my code:
if (message.author.bot) return;
msg = message.content.toLowerCase();
if (msg.startsWith("create channel")) {
const args = message.content.split(' ').slice(2).join(' ')
message.guild.createChannel(`${args}`).then(channel => {
channel.setTopic('Test')
})
}
It appears that you are trying to use the wrong function in v12. Guild#channels is a GuildChannelManager in v12 instead of a Collection.
Replace message.guild.createChannel (v11) with message.guild.channels.create (v12). Note that you can also set the topic in the same API call by passing options to GuildChannelManager#create() like so...
message.guild.channels.create(args.join(" "), { topic: "Test" })
See this guide on updating your code from v11 to v12.