I am making a discord bot and trying to make it say the error in the channel.
Instead of saying the error in the channel, it says "function () { [native code] }"
My code:
module.exports = {
name:"ping",
description: "yes ping",
execute(message, args) {
if(message.member.roles.cache.has('681210322090197005')){
message.channel.send('wow, now thats cool! you have permissions!')
} else {
message.channel.send("**[Permission ERROR]** It looks like you don't have access to this command!")
message.member.roles.add('681210323981828147').catch(message.channel.send(console.error)); // doesnt return the error in the channel!!
}
}
}
message.member.roles.add("681210323981828147").catch(err => {
if(err) return message.channel.send("Error: " + err);
});
This will send the error into the channel. You wanted to send console.error, thats not possible, because console.error is a function to log errors to the console.
Related
Hello and thank you in advance!
const comprarCapsula = () => {
const compraCapsula = async () => {
console.log("Iniciando transacción...");
// ------------------------
const pago = web3.utils.toWei(precioFinal.toString(), 'ether');
// Mensaje de información
infoAlert();
// Petición al SC
const transaction = await contract.myFunction(cantidad, {
from: props.currentAccount,
value: pago.toString()}
).then((result) => {
console.log("RESULT:", result);
successAlert(result.tx);
}).catch((error) => {
console.error("TESTING: ", error.message);
errorAlert(error.message);
});
console.log("TRANS: ", transaction);
// ------------------------
}
contract && compraCapsula()
}
My application detects when I cancel the operation with MetaMask (error) but if the Smart Contract throws an error it is not picked up by the catch.
MetaMask - RPC Error: Internal JSON-RPC error.
Object { code: -32603, message: "Internal JSON-RPC error.", data: {…} }
Data: Object { code: 3, message: "execution reverted: Exception: must have minter role to mint"
Error "must have minter role to mint" its in my Smart Contract.
Why? I'm trying several ways to collect the RPC errors that Metamask throws but I can't find the way.
Could you check calling your contract function as such:
contract.myFunction.call
rather than
contract.myFunction
I had a similar problem when developing a contract. call can be used to see whether the function will throw an error - especially structural, modifier checking wise - but only using call will not invoke the full behaviour of the function. After checking for errors with call, you can call the function again.
Function calls with call enabled us to catch those kind of errors. I used such a structure then:
await contract.myFunction.call(`parameters...`)
.then(
contract.myFunction(`parameters...`)
)
Purpose: To ban unauthorised users who kick members out of my server.
Code:
client.on("guildMemberRemove", async member => {
const FetchingLogs = await member.guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_KICK",
});
const kickLog = FetchingLogs.entries.first();
if (!kickLog) {
return console.log(red(`${member.user.tag} was kicked in ${member.guild.name} but nothing was registered in the audit log...`));
}
const { executor, target, createdAt } = kickLog
if (target.id === member.id) {
console.log(greenBright(`${member.user.tag} got kicked in ${member.guild.name}, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
member.guild.member(executor).ban({
reason: `Unauthorised Kick`
}).then(member.guild.owner.send(`**Unauthorised Kick By:** ${executor.tag} \n**Victim:** ${target.tag} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
})
Result: It bans the executor but it still throws this error:
(node:10272) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ban' of null
Could you please tell me why this is happening and what I could to remove this error. All help appreciated ;)
This is the offending line:
member.guild.member(executor).ban(....
You supply member.guild.member an executor object and it returns null, then it tries to call the function ban on a null object and you get the error.
Maybe try sending it the executor.id instead, like so:
member.guild.member(executor.id).ban
If you want to ban somebody from a guild you can do this by writing:
member.guild.members.ban(executor.id, { reason: "/* Your reason */" })...
Sources:
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=ban
and my experience with discord.js
I develop a bot with discord.js that uses things like msg.member.hasPermission("ADMINISTRATOR") or msg.member.roles.cache.has(teacherRoleID). Everything worked fine until I tried webhooks. By adding these two lines :
client.on('ready', () => {
client.user.setStatus("online")
client.user.setActivity("!help", {
type: "PLAYING",
});
superConsole(`Logged in as ${client.user.tag} in ${client.guilds.size} guilds!`);
const hook = new Discord.WebhookClient("ID", "secret token"); // THESE
hook.send("I am now alive!"); // LINES
});
(btw superConsole is a function)
Since then, the program did not work any more and always returned the same errors: (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of null & (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
When I delete these 2 lines for the webhook, it works again. Why? I don't understand.
The permission and role things are in a message listener:
client.on('message', async msg => {
if (msg.member.hasPermission('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
});
The issue is that when you send a message from hook, it triggers the client's message event. Because a webhook isn't a guild member, msg.member will get undefined for messages sent from a webhook.
You would have to use something like this:
if (msg.member) {
if (msg.member.permissions.has('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
}
How Can I handle error in React-Native
So this is my error enums
export const frontendErrors = {
INVALID_PHONE_NUMBER_ENTERED: 'Sorry you have entered invalid phone number'
}
From my phoneAuth.js file, I am throwing error in catch statement like this
catch (err) {
const errorSearch = 'auth/invalid-phone-number'
if (err.message.includes(errorSearch)) {
throw new Error(frontendErrors.INVALID_PHONE_NUMBER_ENTERED)
}
And When I catching the error in the parent component
catch (error) {
console.log(error)
this.dropDownAlertRef.alertWithType('error', 'Error', error)
}
in the log I am getting my error as an object and like this
Error: Sorry you have entered invalid phone number
The dropdownAlertRef takes in string so it is logging an empty object i.e.
this.dropDownAlertRef.alertWithType('error', 'Error', 'Invalid phone number')
this will log error.
What have I tried?
Doing, console.log(error.Error) gives undefined. How can I access my error?
You can do something like this.
console.log(error.message)
For more refrence you can refer here
So I am trying to code a Discord bot via discord.js-commando in Visual Studio Code. I am trying to code the music player, and I am able to get the bot to join the voice channel. When inputting the URL I want it to play, though, the terminal gives me this error:
(node:17316) DeprecationWarning: Collection#filterArray: use
Collection#filter instead
(node:17316) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property '524399562249601026' of undefined
at Play
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:6:24)
at message.member.voiceChannel.join.then.connection
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:48:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:17316) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without
a catch block, or by rejecting a promise which was not handled with
.catch(). (rejection id: 1)
(node:17316) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
This is the code:
const commando = require('discord.js-commando');
const YTDL = require('ytdl-core');
function Play(connection, message)
{
var server = server[message.guild.id]
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0])
{
Play(connection, message);
}
else
{
connection.disconnect();
}
});
}
class JoinChannelCommand extends commando.Command
{
constructor(client)
{
super(client,{
name: 'play',
group: 'music',
memberName: 'play',
description: 'Plays whatever you link from YouTube.'
});
}
async run(message, args)
{
if(message.member.voiceChannel)
{
if(!message.guild.voiceConnection)
{
if(!servers[message.guild.id])
{
servers[message.guild.id] = {queue: []}
}
message.member.voiceChannel.join()
.then(connection =>{
var server = servers[message.guild.id];
message.reply("Successfully joined!")
server.queue.push(args);
Play(connection, message);
})
}
else
{
message.reply("You must first join a voice channel before inputting the command.")
}
}
}
}
module.exports = JoinChannelCommand;
I'm a little new to this so any help would be appreciated, thank you.
The issue occurs at var server = server[message.guild.id] saying it can't read property 524399562249601026 of undefined. So in this context server is undefined.
Looking at more snippets of your code, I think you made a typo in that it should be servers[...] instead of server[...].