I'm trying to make my Discord Bot[v13] go thru all the members in the server and remove ! and extra spaces from theirs username. For example the bot would change someone nickname from ! net-tech- to just net-tech- by removing the ! and extra spaces. So far I have
message.guild.members.fetch().then(fetchedMembers => {
const target_users = fetchedMembers.filter(member => member.user.username.startsWith("!"));
but I don't know how I would rename them to their name without ! at the start.
You could try using string replace. e.g.
var name = "! net-tech-"
// replace ! with "" and replace the space with ""
var newName = name.replace("!","").replace(" ","")
newName should give you "net-tech-"
Alternatively, you could use an if statement to check if the name starts with "!", e.g.
if (name[0] === "!") {
// get the string from 2nd character onwards
var newName = name.slice(1)
}
Fetch The first step would be to fetch all the members, which you've done so far.
Filter
Next filter all members with usernames that have ! or any extra spaces.
If you want to replace only the ! if they are at the start you would use String#startsWith(), for any ! in the username use String#includes().
To remove all extra spaces you can use the Regular Expression / +/g
Traverse Loop through the resulting members and change their nicknames
const targetChar = '!';
const extraSpaces = / +/g;
message.guild.members.fetch().then(fetchedMembers => {
// Use startsWith() for only starting "!", Use includes for any "!"
const membersToRename = Array.from(fetchedMembers.filter(m => m.user.username.includes(targetChar) || m.user.username.match(extraSpaces).length));
if (!membersToRename.length) return;
// Use replace() for only the first, replaceAll() for all
membersToRename.forEach(m => {
const newNickname = m.user.username
.replaceAll(targetChar, '')
.replaceAll(extraSpaces, '');
m.setNickname(newNickname)
.catch(console.error);
});
});
Warning This could be considered API spam since you're changing information in masses, especially if used in large servers.