I'm trying to make a mute command.I am using v12 version. While coding this command I got stuck in the Permissions part.
can you help me please
Commands ;
if (!muterole) {
try {
muterole = await message.guild.roles.create({ data: {
name: 'Muted',
color: '#000000',
permission: []
}});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
'SEND_MESSAGES': false,
'ADD_REACTION': false,
'CONNECT': false
});
});
} catch(e) {
console.log(e.message);
}
};
if (user.roles.cache.has(muterole)) return message.channel.send(`**${user.user.username}** Başarıyla tamamlandı.`)
user.roles.add(muterole)
message.channel.send(`**${user.user.username}, Başarıyla mutelendi!**`);
Error:
<node:4788> UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied overwrites is not an Array or Collection of Permission Overwrites.
overwritePermissions requires an array in the permission field like this.
channel.overwritePermissions([
{
id: muterole.id,
deny: ['SEND_MESSAGES', 'the rest of your permissions'],
},
], 'Needed to change permissions');
The way you have it here is used in updateOverwrite, which is the better option anyway because it doesn't remove all permissions you had on channels before.
So to fix this, simply replace overwritePermissions with updateOverwrite.
Related
So I have a command that outputs user information. Though most fields have no problems, the Status field is rather buggy for me.
This is the code for the command:
import { Command } from '#sapphire/framework';
import { MessageEmbed } from 'discord.js';
export class UserInfoCommand extends Command {
constructor(context, options) {
super(context, {
...options,
name: 'userinfo',
description: 'Retrives user information.',
aliases: ['user'],
});
}
async messageRun(message, args) {
const userInfo = await args.pick('member').catch(() => message.member);
const roleMap = userInfo.roles.cache.mapValues(roles => roles.name);
const roleArray = Array.from(roleMap.values());
const userEmbed = new MessageEmbed()
.setTitle(`Information about ${userInfo.displayName}#${userInfo.user.discriminator}`)
.setColor(0xC63D85)
.setThumbnail(userInfo.displayAvatarURL())
.addField('ID', `${userInfo.id}`, true)
.addField('Status', `${userInfo.presence.status}`, true)
.addField('Account Created:', `${userInfo.user.createdAt}`)
.addField('Joined on:', `${userInfo.joinedAt}`)
.addField('Server Nickname:', `${userInfo.displayName}`)
.addField('Server Roles:', `${roleArray.join(', ')}`);
return message.channel.send({ embeds: [userEmbed] });
}
}
When executing the command with me (or a user offline since the bot was started), it throws TypeError: Cannot read properties of null (reading 'status'). When I go online and then offline once again, the command works and outputs offline as my status.
I do have the proper intents enabled.
const client = new SapphireClient({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'],
disableMentionPrefix: true,
typing: true,
presence: {
activities: [
{
name: 'Captain\'s commands!',
type: 'LISTENING',
},
],
},
});
I've tried to use an if statement where if userInfo.presence.status is null then it should throw offline instead but that didn't work out. How can I make this work out properly?
Make sure you have the PRESENCE INTENT option enabled in the applications bot settings
This setting is required to get presence updates
Replaced the line with:
.addField('Status', `${userInfo.presence? userInfo.presence.status : "offline"}`, true) // if presence is truthy, output the string, else, the user is offline
A simple null check that worked. Probably my previous method was wrong.
I am building a reactjs app that among others will include Braintree Dropin UI integration. So far, I have managed to make the UI show up and send a payload to the back end. However, I cannot get the gateway.transaction.sale() part to work. Here is my code's relevant parts:
When the user clicks the pay button, this is fired:
instance.requestPaymentMethod().then(function (payload) {
console.log(payload);
completePayment(amount, payload.nonce, userId, sessionId).then((result) => {
console.log( result );
});
}).catch(function (err) {
alert(err.message);
});
And this is the code that should handle the transaction:
return gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonce,
customFields: {
session_id: sessionId,
user_id: userId
},
options: {
submitForSettlement: true
}
}).then(function (result) {
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
}).catch(( error ) => {
alert(error);
});
Every time this function is fired, I get this error from catch:
TypeError: can't assign to property "success" on :not an object
Can anyone point me in the right direction?
Please note that I am not very familiar with react, node etc so my code may not be the best thing around...
Check these points:
make sure you assigned your environment to the sandbox (braintree.Environment.Sandbox);
double check (merchantId, publicKey, and privateKey).
So im very new to fullstack and been working on a little vanilla js project to make a website that calls a server I run that calls chess.com api, for example retrieving all elo ratings is:
https://api.chess.com/pub/player/${username}/stats
So I made a backend call in node-js:
const fetch = require('node-fetch');
exports.getChessManStats = () => {
return (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
const username = req.param('username');
console.log(req.param('username'));
fetch(`https://api.chess.com/pub/player/${username}/stats`)
.then(res2 => res2.json() )
.then(chessManData => {
res.json({
daily: chessManData.chess_daily.last.rating,
rapid: chessManData.chess_rapid.last.rating,
blitz: chessManData.chess_blitz.last.rating,
bullet: chessManData.chess_bullet.last.rating,
})
})
.catch(err => console.log(err));
}
};
the code then runs with express on the main.js with:
const app = express();
app.get('/getRating',chessManController.getChessManStats());
obviously later down the line I called app.listen(3000) .
So then at the frontend I made a button that calls this function :
const makeUserStats = () => {
const username = document.getElementById('username').value;//id=username is type input
document.getElementById('rating').innerHTML = `Searching`; //making the rating div into 'searching'
console.log(`http://localhost:3000/getRating?username=${username}`)//just seeing the sting I send
fetch(`http://localhost:3000/getRating?username=${username}`)
.then(rating => {
document.getElementsByClassName('statButton').disabled = true;//disabling buttons until the data arrives
console.log('got json');
return rating.json();
})
.catch(err => console.log(err))//looking for errors
.then((userRating => {
window.userRating = userRating;//saving the stats globaly to use in other buttons
window.user = username;
}))
.then(() => {
document.getElementsByClassName('statButton').disabled = false;//enabling the buttons again
document.getElementById('rating').innerHTML = `${window.user} rating is:`;
})
}
and now when I press the button it works with some usernames and with some dont.
YoniRamot (mine) works, hikaru (pro player) works, atomicstew (friend) doesnt work, idobl (friend) doesnt work. and the wierd part is it does'nt catch any errors, just waiting for answer that it never gets.
but if you go the the api they all exist:
https://api.chess.com/pub/player/yoniramot/stats -- mine
https://api.chess.com/pub/player/hikaru/stats --proplayer
https://api.chess.com/pub/player/atomicstew/stats --friend
https://api.chess.com/pub/player/idobl/stats --friend
the console of the backend shows:
atomicstew
TypeError: Cannot read property 'last' of undefined
at C:\Users\Yonatan\Desktop\coding\training\intermediateChess\backend\controllers\chessStats.js:12:45
at processTicksAndRejections (internal/process/task_queues.js:93:5)
meaning that the backend gets the username but does'nt find it in the api for some reason.
please help my mind is blowing at this point.
-edit 1-
So I added a console log before sending the res with the data, and it printed:
atomicstew
{
chess_rapid: {
last: { rating: 1228, date: 1612114999, rd: 28 },
best: {
rating: 1265,
date: 1611786478,
game: 'https://www.chess.com/live/game/6380128206'
},
record: { win: 233, loss: 202, draw: 19 }
},
chess_blitz: {
last: { rating: 902, date: 1611928398, rd: 50 },
best: {
rating: 1010,
date: 1609882454,
game: 'https://www.chess.com/live/game/6297568401'
},
record: { win: 26, loss: 24, draw: 4 }
},
fide: 0,
tactics: {
highest: { rating: 1659, date: 1609635730 },
lowest: { rating: 387, date: 1608148134 }
},
lessons: {},
puzzle_rush: {}
}
TypeError: Cannot read property 'last' of undefined
at C:\Users\Yonatan\Desktop\coding\training\intermediateChess\backend\controllers\chessStats.js:13:45
at processTicksAndRejections (internal/process/task_queues.js:93:5)
and the references I am calling are right there, so I am still stuck.
-edit 2-
I noe realized that if a player didnt play a certain game mode than the api doesnt hold that values. any ideas how to save the data as 0 or null if there is no data neatly?
Issue is in following block of code where you are trying to access last field on different properties in response:
res.json({
daily: chessManData.chess_daily.last.rating,
rapid: chessManData.chess_rapid.last.rating,
blitz: chessManData.chess_blitz.last.rating,
bullet: chessManData.chess_bullet.last.rating,
})
I had quick look at response for following API and it does not have chess_daily and chess_bullet properties.
https://api.chess.com/pub/player/atomicstew/stats
Since you are trying to access chessManData.chess_daily.last.rating and chess_daily is not present in chessManData, you are getting exception for .last.
In order to fix it, you can replace above block by following:
res.json({
daily: chessManData.chess_daily && chessManData.chess_daily.last ? chessManData.chess_daily.last.rating : null, // replace null with appropriate default value for rating
rapid: chessManData.chess_rapid && chessManData.chess_rapid.last ? chessManData.chess_rapid.last.rating : null,
blitz: chessManData.chess_blitz && chessManData.chess_blitz.last ? chessManData.chess_blitz.last.rating : null,
bullet: chessManData.chess_bullet && chessManData.chess_bullet.last ? chessManData.chess_bullet.last.rating : null,
})
So I have this command that sets the bot's "Playing" status:
const commando = require('discord.js-commando');
const { RichEmbed } = require('discord.js');
class sets extends commando.Command {
constructor(client) {
super(client, {
name: 'setgame',
group: 'owner',
memberName: 'setgame',
description: 'Sets the Bots\' activity',
examples: ['Playing __on many servers!__'],
args: [
{
key: "game",
prompt: "What do you want to set my game as?",
type: "string"
}
]
});
}
async run(message, { game } ) {
if (message.author.id !== "442918106378010635"){
message.channel.send("That's for TheRSC only!");
}
else {
this.client.bot.setActivity(game)
const embed = new RichEmbed()
.setColor(0x00AE86)
.setDescription("Game set!");
message.channel.send({embed});;
}
}
}
module.exports = sets;;
I ran into a few bugs before and managed to fix them, but this one stumps me. No matter how I code it, I keep getting: TypeError: Cannot read property 'setActivity' of undefined
I've tried a few things, having text be defined in run, putting args.game into .setActivity() and it keeps spitting out that error. I tried the splitting the args method but that didn't work either. Any ideas? (As a side note, I'd also like to turn this into a .setPresence command if possible.)
Note: I am a beginner at coding, so I may be doing something that the average coder wouldn't.
Try changing
client.bot.setActivity(game)
to
client.user.setActivity(game)
You can take a look at this example provided by the official documentation on setActivity() if you need more help, or if my solution doesn't work.
client.user.setActivity('YouTube', { type: 'WATCHING' })
.then(presence => console.log(`Activity set to ${presence.game ? presence.game.name : 'none'}`))
.catch(console.error);
EDIT: I still think it has something to do with the .bot part because the only reference on the documentation of .bot was a boolean of whether or not a user was a bot.
I might just be missing something simple, but I've never had this error before and I don't think I edited it enough to cause this problem since it was last functional. The code block below keeps giving me this error at the top of the file:
(node:17592) UnhandledPromiseRejectionWarning: TypeError: client.catch is not a function
I have specified client = new Discord.Client();
The other issue I am having is that I am trying to get the role that is being made by the bot to be the name of the two players/users (challenger vs target format) after the target has accepted the challenge posed by the challenger. It just makes a role named "new role" instead. Any help with either of these problems?
if (message.channel.id === '541736552582086656') return challenged.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
.then((newmsg) => {
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 150000,
errors: ['time'],
}).then((collected) => {
// Grabs the first (and only) message from the collection.
const reply = collected.first();
if (reply.content === 'accept'){
reply.channel.send(`You have ***accepted *** the challenge from ${challenger}. Please wait while your battlefield is made...`);
message.author.send(`${target} has accepted your challenge! Please wait while the channel is made for your brawl...`)
var server = message.guild;
var permsName = `${target} vs ${challenger}`;
var name = `${target} vs ${challenger}`;
message.guild.createRole({
data: {
name: permsName,
hoist: true,
color: "#00fffa",
permissions: [] }
}).then(role => {
target.addRole(data, permsName)
challenger.addRole(role, permsName)
// client.catch error occurring below
.catch(error => client.catch(error))
}).catch(error => client.catch(error)).then(
server.createChannel(name, "text")).then(
(channel) => {
channel.setParent("542070913177485323")
})
} else if (reply.content === 'deny') {
reply.channel.send("You have ***denied *** the challenge.")
} else {
reply.channel.send("Your response wasn't valid.");
}
})
})
}
module.exports.help = {
name: "challenge"
}
I have tried looking up the problem and I don't see anything that has helped so far with either issue. They might be related since the catch is after the add role part? Thanks in advance for the help!
Curious if there's a template you copied for this bot? The Discord.Client object does not have any catch method, so calling client.catch() is not going to work.
To clarify, this is fine:
challenger.addRole(role, permsName)
.catch(error => /* do something with this error */);
What can you do with the error? You could print it to console, I suppose:
challenger.addRole(role, permsName)
.catch(error => console.error(error));
But you can't call client.catch(error), because that's not a real method - you can check out the docs for the Client object here.
Regarding the role name, you just have a small error: you don't want to wrap your options object in { data: }, your options object is the data. Just pass them in directly, like so:
message.guild.createRole({
name: permsName,
hoist: true,
color: "#00fffa",
permissions: []
}).then(role => {
Hope that helps!