How can I separate Username and ID from command? - javascript

I made a code using the DankMemer Youtube Imgen API. When I type:
,youtube hello
, it displays:
But when I tag someone, it displays the text along with the ID:
Is there a way I can separate the username from the text?
let target = message.mentions.users.first() || message.author;
let profilepic = target.avatarURL;
let sentence = args.join(" ");
let url = ` https://dankmemer.services/api/youtube?avatar1=${profilepic}&username1=${target.username}&text=${sentence}`;
message.channel.startTyping();
snekfetch.get(url, {
headers: {
"Authorization": token
}
}).then(async res => {
await message.channel.send({
files: [{
attachment: res.body,
name: `${target.tag}-youtube.jpg`
}]
}).then(() => message.channel.stopTyping());
}).catch(err => console.error(err));

let sentence = args.join(" ");
you joined the args there which I think also includes the user mentioned. The only thing you need to do is remove the mention. If you want to remove only the first mention then do this-
if (!target === message.author) {
let toremove = `{#${target.id}}`;
sentence = sentence.replace(toremove, "");
}
Add this code after this line-
let sentence = args.join(" ");

You can replace all mentions in the message's content with blanks using regex, like so:
let messageContentWithoutMentions = message.content.replace(new RegExp("<#\d+>","gm"),"")
If you wanted to remove something else, just make use of the string.replace function.

Related

How to take name and last name with match function?

You can add comment in my project and you can reply my comment. I want to take the name and surname after "#". How can I do that?
My find username function
const findUsername = message => {
var attachments = message.match(/#[^\s]+/g);
console.log(attachments);
return attachments !== null
? attachments.map(item => item).join('')
: null; };
This function just take the name, example: "#John Dao", function take the John. Anybody help me ?
Comment Example:
Comment
Reply Example:
Reply Example
Message argument example : "#Berkay Ergün skajjkdalskjdadsa"
You can try this:
const splitName = (name = '') => {
const res = name.substring(1)
const [firstName, ...lastName] = res.split(' ').filter(Boolean);
return {
name: firstName,
surname: lastName.join(' ')
}
}
console.log(splitName('#Jon Doe'));

Find a string inside quotes in Javascript

The title explains my problem. I am trying to get a string that has quotation marks around it so I can use Node.js to pass into a weather module. Here's my code so far (I have not set the var CityToSearch yet in this code which is what I need help with)
And also yes I'm using Discord.js to send messages.
const Discord = require('discord.js')
const bot = new Discord.Client()
const PREFIX = '/';
const embed = new Discord.MessageEmbed()
const ping = require('minecraft-server-util')
const weather = require('weather-js')
bot.on('message', message => {
if (message.channel.type === 'dm') {return}
let args = message.content.substring(PREFIX.length).split(' ')
if(message.content.startsWith(PREFIX))
switch (args[0]) {
case 'weather':
if (args.includes('"')){
var CityToSearch =
}
weather.find({search: `city, ${CityToSearch}`, degreeType: 'F'}, function(err, result) {
if(err) console.log(err);
var currentw = new Discord.MessageEmbed()
.setColor(0x00ffff)
.setTitle(`Current Weather in ${args[1]} in state ${args[2]}`)
.addField('Temperature', result[0].current.temperature)
.addField('Sky Text', result[0].current.skytext)
.addField('Humidity', result[0].current.humidity)
.addField('Wind Speed & Direction', result[0].current.winddisplay)
.addField('Feels Like', result[0].current.feelslike)
.addField('Location', result[0].current.observationpoint)
.addField('Time', result[0].current.observationtime)
.addField('Date', result[0].current.date)
message.channel.send(currentw)
});
You can split the actual string with ". So that the string will be split and the string at index 1 will be the city you are looking for.
const str = '/weather "San Fransico" California';
console.log(str.split('"'));
console.log(str.split('"')[1]);
I would NOT split the arguments on spaces initially. You can use the Regular Expression below with your arguments to yank out the command, and then parse the inputs as needed:
const args = message.content.substring(PREFIX.length).match(/\/([^\s]+) (.+)/)
if (args) { // valid input?
const command = args[1]
const input = args[2]
switch (command) {
case 'weather':
const cityMatch = input.match(/"([^"]+)"/)
const CityToSearch = (cityMatch) ? cityMatch[1] : input.split(/\s/)[0]
weather.find({search: `city, ${CityToSearch}` ...)
// other commands...
}
}

Trying to show off emoji when it's added using Discord.js

Currently I'm trying to add something to my bot to display text and a preview when an emoji is added.
I was pretty close, but it appears the emoji doesn't exist on the server during the emojiCreate event.
my code (which is a mess) looks like this currently:
var latestEmojiName = "";
let announcementChannel = "";
client.on("emojiCreate", emoji => {
announcementChannel = emoji.guild.channels.find(x => x.id === "625678148440162314");
announcementChannel.send("new emoji has been added:");
latestEmojiName = emoji.name;
newEmojiFollowup1();
});
function newEmojiFollowup1() {
setTimeout(newEmojiFollowup2, 2000);
}
function newEmojiFollowup2() {
announcementChannel.send(client.guilds.find(x => x.id === "607642928872947724").emojis.find(x => x.name === latestEmojiName));
}
Ok, I added the following listener to one of my bots and it worked. Also, there is no need to look-up the guild because you do not need a timeout. The emoji object has all you need already.
You need to send: <:${emoji.name}:${emoji.id}>
Also, use let instead of var to resolve scoping issues and there is no need for all the "follow-on functions.
// Verified with discord.js#11.5.1
const channelId = "625678148440162314" // e.g. Channel: #general
client.on("emojiCreate", emoji => {
const channel = emoji.guild.channels.find(x => x.id === channelId)
channel.send("A new emoji has been added:")
channel.send(`<:${emoji.name}:${emoji.id}>`)
})
You can also send a rich-embed message:
// Verified with discord.js#11.5.1
const channelId = "625678148440162314" // e.g. Channel: #general
client.on("emojiCreate", emoji => {
const channel = emoji.guild.channels.find(x => x.id === channelId)
const embed = new RichEmbed()
.setTitle("A new emoji has been added!")
.setColor(0x222222)
.setDescription("Preview:")
embed.addField(`:${emoji.name}:`, `<:${emoji.name}:${emoji.id}>`, true)
channel.send(embed)
})

Discord help command - args.join isn't a function

with my discord bot I am working on a help command.
My command list file which the help command accesses is:
{
"Help": {
"name":"Help",
"group":"User",
"desc":"Displays a list of commands",
"usage":"help [group OR command]"
},
"Purge": {
"name":"Purge",
"group":"Admin",
"desc":"Deletes a specified number of messages",
"usage":"Purge <amount>"
}
}
These just define group, name, and usage of the commands. The code for the help command so far is:
const Discord = require('discord.js');
const bot = new Discord.Client();
const client = new Discord.Client();
const weather = require('weather-js');
const fs = require('fs');
const commands = JSON.parse(fs.readFileSync('Storage/commands.json', 'utf8'))
const token = "<my token>"
const prefix = 'cb!';
bot.on('message', message => {
// Variables
let msg = message.content.toUpperCase();
let sender = message.author;
let cont = message.content.slice(prefix.length).split(" ");
let args = cont.shift().toLowerCase();
if (message.content.startsWith(prefix+'help')) {
console.log('ok i hate this')
const embed = new Discord.RichEmbed()
.setColor(0x1D82B6)
let commandsFound = 0;
for (var cmd in commands) {
if (commands[cmd].group.toUpperCase() === 'USER') {
commandsFound++
embed.addField(`${commands[cmd].name}`, `**Description:** ${commands[cmd].desc}\n**Usage:** ${prefix + commands[cmd].usage}`);
}
}
embed.setFooter(`Currently showing user commands. To view another group do ${prefix}help [group / command]`)
embed.setDescription(`**${commandsFound} commands found** - <> means required, [] means optional`)
message.author.send({embed})
message.channel.send({embed: {
color: 0x1D82B6,
description: `**Check your DMs ${message.author}!**`
}})
} else {
// Variables
let groupFound = '';
for (var cmd in commands) {
if (args.join(" ").trim().toUpperCase() === commands[cmd].group.toUpperCase()) {
groupFound = commands[cmd].group.toUpperCase();
break;
}
}
if (groupFound != '') {
for (var cmd in commands) {
const embed = new Discord.RichEmbed()
.setColor(0x1D82B6)
let commandsFound = 0;
if (commands[cmd].group.toUpperCase() === groupFound) {
commandsFound++
embed.addField(`${commands[cmd].name}`, `**Description:** ${commands[cmd].desc}\n**Usage:** ${prefix + commands[cmd].usage}`);
}
}
embed.setFooter(`Currently showing ${groupFound} commands. To view another group do ${prefix}help [group / command]`)
embed.setDescription(`**${commandsFound} commands found** - <> means required, [] means optional`)
message.author.send({embed})
message.channel.send({embed: {
color: 0x1D82B6,
description: `**Check your DMs ${message.author}!**`
}})
}
}
});
If I were to type "cb!help admin" I would get this error in the console
if (args.join(" ").trim().toUpperCase() === commands[cmd].group.toUpperCase()) {
^
TypeError: args.join is not a function
What might I do to fix this? I've also tried if (args[0].join... but that doesn't work.
As always, thanks for taking the time to read this. I'm basing this off of out dated code so there are maybe some other errors. I'm trying too fix them all.
args has one definition in your code sample:
let args = cont.shift().toLowerCase();
This makes args a string - string do not have the method join() as join() is part of the Array prototype chain, which strings do not inherit from. shift() will return the first element of the cont array, so you may just want to call args.toUpperCase(), although I would recommend renaming your variables to make the meaning of what args is clearer.
You should try to swap your two variables at the top so that
let args = message.content.slice(prefix.length).split(' ');
let cont = args.shift().toLowerCase();
Then just put args in your if statement
if (args[0].toUpperCase === commands[cmd].group.toUpperCase) { /* Your code... */ }
Your args are already stored in an array so there is no need to trim them and the join function is also therefore not needed.
Hope this helps!
your missing client, insert client, message, args

How does one parent a channel to a category with a discord bot?

Basically there is no errors in the output but at the same time it's not doing what I'm trying to achieve.
Ive been tinkering with the script for 5 hours straight mixing up line positioning and now I got it to where it gives me the promise (my initial issue) but I cant parent the channel.
I've tried discord.js server and site, youtube, 2 other sites i forgot the name of but i cant crack it.
function setup(arguments, message){
var server = message.guild;
var name = message.author.username;
let searchquery = arguments.join("")
let cat = server.createChannel("Important", "category");
async function Channelmaker(Sent, obj){
try {
let chan = await server.createChannel(Sent, "Text");
//console.log(obj);
return chan
} catch(prom){
var chan2 = await server.createChannel(Sent, "Text");
return new Promise(resolve => {
var chan2 = server.createChannel(Sent, "Text", parent = obj);
resolve(chan2)
});
}
}
var holding
var chan = Channelmaker("⚖️ rules ⚖️", cat).then(value => {
console.log(value)
holding = value
value.parentID = cat
chan.setParent(cat.Id)
}).catch(error => {
// s
});
console.log("holding")
console.log(holding)
}
The category is not the parent of the "⚖️ rules ⚖️" channel that is created which is the opposite of what I'm trying to achieve
In Guild.createChannel(), use the options parameter including ChannelData, like so:
await server.createChannel(Sent, {
// You can omit the 'type' property; it's 'text' by default.
parent: obj
});

Categories

Resources