Find a string inside quotes in Javascript - 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...
}
}

Related

How do I export this named function through module.exports?

I have a command file for a discord bot that contains the command and a piece of parsing logic contained within a function that I want to reuse within my index.js
// file: ./commands/scrumPrompt.js
// The function
const extractDeets = function (f, scrum) {
let items = [];
let re = new RegExp("(\n[ -]*" + f + ".*)", "g");
let replace = new RegExp("[ -]*" + f + "[ ]+");
for (const item of scrum.matchAll(re)) {
items.push(item[1].trim().replace(replace, ""));
}
return items;
};
// The actual command itself within the same file
module.exports = {
name: "scrum",
usage: `!scrum < followed by your message > as per Standup format - refer !show for showing the format`,
description: "Reply to standup prompt",
async execute(message, args) {
if (message.channel.type === "text") {
if (!args.length)
return message.reply(
"Please Provide your scrum as per the format in help menu !scrum < your message >"
);
else {
if (message.author.id !== -1) {
const client = new MongoClient(MONGO_URI);
try {
const database = client.db(DB_NAME);
const members = database.collection("members");
const query = { user_id: message.author.id };
const membersdetail = await members.findOne(query);
if (membersdetail !== null) {
// since this method returns the matched document, not a cursor, print it directly
//console.log("Adding Scrum for ", membersdetail.email);
let userscrum = args.splice(0).join(" ");
// Check if multiple !scrum commands are present in developer scrum message
if (userscrum.includes("!scrum") == false) {
// Expects notations of "-" to exist
let [f, e, b, o, bl] = ["f", "e", "b", "o", "x"];
let features = extractDeets(f, userscrum);
let enhancements = extractDeets(e, userscrum);
let bugs = extractDeets(b, userscrum);
let others = extractDeets(o, userscrum);
let blockers = extractDeets(bl, userscrum);
.
.
.
};
I want to keep the name of the function as extractDeets() itself so that it doesn't mess with the usage within the command as well. I'm not completely sure how to export it into the index.js because it's already kind of being imported here:
// Imports the command file + adds the command to the bot commands collection
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
I'm unsure of how to add the function as another import, maybe I should export it into another file and then import it from there? I'm not sure if that's possible or doable here. I've tried directly importing from here but then the command doesn't work, which is troublesome.
You can do it like this:
module.exports = { extractDeets };
Later, you can import it like this:
const { extractDeets } = require('../your_file');

Issue with Java Discord.js Modmail System

I have been trying to make a discord ModMail system on my bot and there is an error that I can't understand my code is below:
client.on('message', message => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/+ /)
if (!message.channel.name.includes('modmail')) {
return;
} else {
if (isNaN(args[0])) {
return message.channel.send('Sorry but that is not a valid user')
}
let storage = message.guild.members.cache;
let memberId = storage.find(member => member.id.toLowerCase() === args[0]);
if (memberId) {
const msg = message.content.slice(args[0].length + prefix.length).split(" ").join(" ");
let embed = new Discord.MessageEmbed()
.setThumnail(message.author.displayAvatarURL())
.setDescription(`<#${message.author.id}>\n------------\n${msg}`)
.setColor('#599cff')
.setFooter('ModMail System')
.setTimestamp();
client.users.fetch(args[0]).then(user => user.send(embed).catch(err => console.log(err)));
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.')
} else {
return message.channel.send('Could not find the user sorry.');
}
}
});
client.on('message', message => {
var msg = message.content;
var n = message.author.username;
if (message.channel.type === 'dm') {
if (message.author.bot) return;
let blacklisted = ['word1', 'word2']
let foundInText = false;
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
return message.channel.send('Please do not use foul language in the message. (if you must please cover it with symbols *not letters*)');
}
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.');
const mailMessage = `${message.author.id} ${msg}`
client.channels.fetch('795031406442315816').then(user => user.send(mailMessage).catch(err => console.log(err)));
}
});
The error that is shown is:
SyntaxError: Invalid regular expression: /+ /: Nothing to repeat
This has been confusing me for a while (I am new to code) please if you know how to fix this it would help a lot thank you.
I think the error is because there is a problem here:
const args = message.content.slice(prefix.length).split(/+ /)
If you change .split(/+ /) to .split(' ') or .split(/ /) it would work.

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 can I separate Username and ID from command?

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.

Discord.js how to make suggest command?

What can I do in Discord.js to make suggest command? My actual code doesn't work, i have 2 types of suggestions: support server and bot.
Here's my code:
if (command === "suggest"){
const type = args.join(" ")
const thing = args.join(" ").slice(6)
const thing2 = args.join(" ").slice(3)
const suggestion = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing}`)
const suggestion2 = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing2}`)
if (!typ){
message.reply("enter suggestion type, which you want to suggest!");
return;
}
if (type === "server"){
if (!thing){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("channel_id").send(suggestion);
return;
}
if (type === "bot"){
if (!suggestion2){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("another_channel_id").send(suggestion2);
return;
}
else if (type !== "bot" || type !== "server"){
message.reply("invalid suggestion type!");
return;
}
}
and it outputs "invalid suggestion type!" when I type !suggestion
I'm not an expert with discord.js but this should work! (It does on my server!)
client.on('message', msg => { //This runs when a message is sent.
const args = msg.content.slice(prefix.length).split(' '); //Get the arguments
const command = args.shift().toLowerCase(); //Making the command non case-sensitive
if (command === 'suggest'){ //if command is suggest
const channel = msg.guild.channels.find(ch => ch.name === 'suggestions'); //finds the channel named suggestions
channel.send('Suggestion:\n ' + args.join(' ')) //Sends the arguments
} //Closes the if (command === 'suggest'){
}); //Closes the client.on('message',msg => {
Great if i can help!
Also you used !== so if user is not a bot it doesn't send message. Try using === instead!
I dont know if you use a command handler or not but if you do, this should work:
if (command === 'suggest'){
const Discord = require('discord.js'); // this should be on top of ur js file, NOT HERE
const { Client, MessageEmbed } = require('discord.js'); // this should be on top of ur js file, NOT HERE
if(!args[0]) return message.reply('You need to type a suggestion..') // bot reply if user only typed !suggest n didnt include any text..
const user_avatar = message.author.avatarURL({ format: 'png', dynamic: true, size: 2048 }); // gets discord user avatar
const user_suggestion = args.slice(0).join(" ") // gets discord user args
let suggestion_channel = message.guild.channels.cache.find(
(cache) => cache.name === "suggestions" // the channel name u want the embed to be sent to..
);
if (!suggestion_channel) return;
const suggestion_emb = new MessageEmbed() // The suggestion embed that will be sent to the "suggestions" channel
.setAuthor(`Suggestion:`, `${user_avatar + "?size=2048"}`)
.setDescription(`${user_suggestion}`)
.setColor("RANDOM") // randomizes the color of the embed, can also be hex n rgb so ".setColor("#3d71e7")" for example.
.setFooter(`Suggested by: ${message.author.tag}`);
const suggestion_reply_emb = new MessageEmbed() // the reply embed so when someone does !suggest suggestion here, it will reply with the embed below
.setAuthor(`${message.author.tag}`, `${user_avatar + "?size=2048"}`)
.setDescription(`:white_check_mark: Your suggestion has been sent to <#CHANNEL_ID_HERE>.`)
.setColor("RANDOM");
message.reply(suggestion_reply_emb) && suggestion_channel.send(suggestion_emb)
};
if u use a command handler just remove the first & last line

Categories

Resources