Discord Bot doesn't send randomly chosen message - discord.js

I have the following code:
bot.on('message', msg =>{
if(msg.content === "Hello"){
const hello1 = 'Hello mah boi! or girl... eh'
const hello2 = 'Sup.'
const hello3 = 'Wassup?'
const hello4 = 'HEEEEEELLLLOOOOO BOOOOOIII'
const hello5 = 'Are you sure you wanna say hi??'
const hello6 = '.'
const hello7 = 'Heeeeeyyyyyyyyy ey eyyyyyyyy'
const items = [
hello1,
hello2,
hello3,
hello4,
hello5,
hello6,
hello7
];
const rndString = items[Math.floor(Math.random() * items.length)];
msg.channel.send(rndString);
}
})
I'm trying to make a random message command, but it isn't working. No message is ever sent. It doesn't throw any errors either.

I do the same thing, except with memes. You could try this, this is my code:
const memes = [
'https://tenor.com/LxdC.gif',
'https://tenor.com/Fm1D.gif',
'https://tenor.com/bqltH.gif',
'https://tenor.com/4nHj.gif',
'https://tenor.com/zFEB.gif',
'https://tenor.com/xa3U.gif',
'https://tenor.com/wMSx.gif',
'https://tenor.com/HxIT.gif',
'https://tenor.com/XGES.gif',
'https://tenor.com/bdnvi.gif',
'https://tenor.com/yf4L.gif',
'https://tenor.com/bnU5s.gif',
'https://tenor.com/xjhw.gif',
'https://tenor.com/2Rbt.gif',
'https://tenor.com/bE4YO.gif',
'https://tenor.com/bEOYD.gif'
]
client.on('message', (message) => {
if (message.content.startsWith('!memes')) {
const response = memes[Math.floor(Math.random() * memes.length)];
message.channel.send(response);
}
});
client.on('message', (message) => {
if (message.content.startsWith('!memesdm')) {
const response = memes[Math.floor(Math.random() * memes.length)];
message.author.send(response);
}
});

You can do it like this:
bot.on('message', msg =>{
if(msg.content === "Hello"){
function random() {
const hello1 = 'Hello mah boi! or girl... eh'
const hello2 = 'Sup.'
const hello3 = 'Wassup?'
const hello4 = 'HEEEEEELLLLOOOOO BOOOOOIII'
const hello5 = 'Are you sure you wanna say hi??'
const hello6 = '.'
const hello7 = 'Heeeeeyyyyyyyyy ey eyyyyyyyy'
var rand = [hello1, hello2, hello3, hello4, hello5, hello6, hello7];
return rand[Math.floor(Math.random()*rand.length)];
}
message.channel.send(random())
}
})

Related

Discord.js push slash commands

I recently started writing Discordbots and just can't seem to get anywhere pushing the slash commands. I already have a handler file (pushSlash.js) but for some reason the commands are never loaded or I get an error in the console (mostly simply this: chalk.blue is not a function). My bot also doesn't get the badge that it supports slash commands.
Can anyone help me further?
Here is my code (pushSlash.js):
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
import( 'chalk').then(chalk => {
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
});
};
I've already tried everything possible, but since I'm relatively new to discord.js, I don't know that much yet either.
Actually everything should work and exactly 2 different commands should be loaded, but I only get error messages or the handler was loaded on console but nothing is displayed on Discord.
first download chalk#4.1.2 with
npm install chalk#4.1.2
and import chalk normally.
const chalk = require('chalk')
There your code modified version:
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
// Imported chalk normally
const chalk = require('chalk')
// removed `import( 'chalk').then(chalk => {})`
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
};

How can I edit message by id?

How can I change a message by its ID? I have the following code:
client.on('message', message => {
if(message.content.startsWith(prefix + 'edit')) {
let msg1 = ['message'];
const desc = msg1.content.split(' ').slice(2).join(' ');
const desc2 = msg1.content.split(' ').slice(3).join(' ');
const desc3 = msg1.content.split(' ').slice(4).join(' ');
let server = client.guilds.cache.get(desc);
if (!server) console.log('Не могу получить сервер')
let channel = server.channels.cache.get(desc2);
if (!channel) console.log('Не могу получить канал')
let message = channel.messages.fetch(desc3).then(msg => {
msg.edit('hello')
})
}
})
And I can't make it so that the user can choose which message to change.

TypeError: Cannot read property '0' of undefined (discord.js)

const data = suggestedEmbed.embeds[0];
Hi, I'm having this error and I don't know why it is saying that the code above is the problem. Any solutions for this problem? Thank you for reading.
Code:
module.exports = {
category: "Utility",
description: "Accept valid suggestions!",
expectedArgs: "<messageID> <Reason>",
minArgs: 2,
guildOnly: true,
ownerOnly: true,
callback: ({message, args}) => {
const messageID = args[0]
const acceptQuery = args.slice(1).join(" ");
try{
const suggestionChannel = message.guild.channels.cache.get('834459599699443782');
const suggestedEmbed = suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(data.author.name, data.author.iconURL())
.setColor('GREEN')
.setDescription(data.description)
.addField("📊 Status ✅ Accepted! Expect this coming soon!", acceptQuery);
suggestedEmbed.edit(acceptEmbed);
const user = client.users.cache.find((u) => u.tag === data.author.name);
user.send("Your suggestion has been accepted! Thank you for this suggestion, expect this coming soon!")
} catch(err) {
console.log(err)
}
}
}

Random Meme Command (discord.js v12)

I'm trying to make a 'random meme' command for my Discord Bot. I'm new to working with APIs, but I've tried my best.
The problem is, when I type the command, nothing happens. There are no errors, but the bot doesn't send anything in discord.
This is my code:
if (command === "meme")
async (client, message, args) => {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
Here Is One That Will Show Info About The Meme
if(command === "meme") {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/${random}.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('It seems we are out of memes');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("r/" + random)
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
Let Me Know If It Don't Work, But I Should
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === "meme") {
async (client, message, args) =>
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
});
This should work, not quite sure, haven't tested it. (You can put in a command handler your self)
if (command === "meme")
async (client, message, args) => {
const fetch = require('node-fetch');
let userAvatar = message.author.avatarURL({ format: "png", dynamic: true, size: 2048 }); // this is just the users icon, u can remove it if you want.
fetch(`https://meme-api.herokuapp.com/gimme`)
.then(res => res.json())
.then(async json => {
const embed = new MessageEmbed()
.setAuthor(`${json.title}`, `${userAvatar + "?size=2048"}`, `${json.postLink}`)
.setImage(`${json.url}`)
.setFooter(`👍${json.ups} | ${json.subreddit}`)
.setColor("RANDOM")
message.channel.send(embed).catch((error) => {
console.log("An error has occured on the \"meme\" command\n", error)
})
}
Here you go! I've tested this on my own command handler.

useState does not update the state

I'm trying to update a state using useState hook, however the state won't update. I've checked how to fix it but really have no idea about it what cause this point. This is the whole code I didnt include the urls and import files...
When onchange method trigger ilceZoom function event has value so ı can get it evt.value example values is "1234" but I can not set it using useState future
const ilceUrl = 'URL';
const AddressSearchMaks = (props) => {
useEffect(() => {
ilceLoad();
}, []);
const [ ilceler, setIlceler ] = useState([]);
const [ selectedIlce, setSelectedIlce ] = useState(null);
let queryTask;
let query;
let sfs;
let lineSymbol;
let polygon;
let polyline;
let graphic;
let extent;
let point;
let wMercatorUtils;
let rfConverter;
loadModules([
'esri/tasks/query',
'esri/tasks/QueryTask',
'esri/symbols/SimpleFillSymbol',
'esri/symbols/SimpleLineSymbol',
'esri/geometry/Polygon',
'esri/geometry/Polyline',
'esri/geometry/webMercatorUtils',
'esri/geometry/Extent',
'esri/geometry/Point',
'esri/graphic',
'esri/Color',
'libs/ReferenceConverter'
]).then(
(
[
Query,
QueryTask,
SimpleFillSymbol,
SimpleLineSymbol,
Polygon,
Polyline,
webMercatorUtils,
Extent,
Point,
Graphic,
Color,
referenceConverter
]
) => {
queryTask = QueryTask;
query = Query;
polygon = Polygon;
polyline = Polyline;
graphic = Graphic;
extent = Extent;
point = Point;
wMercatorUtils = webMercatorUtils;
rfConverter = referenceConverter;
sfs = new SimpleFillSymbol(
SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4),
new Color([ 140, 140, 140, 0.25 ])
);
lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0, 255, 255 ]), 4).setWidth(4);
}
);
const getAdres = async (url) => {
let response = await fetch(url);
let data = await response.json();
let list = [];
data.AdresList.Adresler.Adres.forEach((item) => {
list.push({
label: item.ADI,
value: item.ID,
lat: item.LAT,
lon: item.LON
});
});
return list;
};
async function ilceLoad() {
let ilceList = await getAdres(ilceUrl);
setIlceler(ilceList);
}
const convertExtent = (lat, lon) => {
let p;
let ext;
const sr = props.map.spatialReference;
if (sr.wkid == 102100) {
const _p = wMercatorUtils.lngLatToXY(lon, lat);
ext = extent({
xmin: _p[0],
ymin: _p[1],
xmax: _p[0],
ymax: _p[1],
spatialReference: props.map.spatialReference
});
} else {
const res = rfConverter.WgsToItrf(lat, lon);
ext = extent({
xmin: res.x,
ymin: res.y,
xmax: res.x,
ymax: res.y,
spatialReference: props.map.spatialReference
});
p = point(res.x, res.y);
}
p.spatialReference = sr;
return ext;
};
const ilceZoom = (evt) => {
setSelectedIlce(evt.value);
console.log('selectedIlce', selectedIlce);
setError(false);
console.log('error', error);
const qTask = queryTask(maksIlce);
const q = query();
q.returnGeometry = true;
q.outFields = [ '*' ];
q.outSpatialReference = { wkid: 5254 };
q.where = `KIMLIKNO=${evt.value}`;
qTask.execute(q, (evt) => {
const polyGon = polygon({
rings: evt.features[0].geometry.rings
});
props.map.graphics.add(graphic(polyGon, sfs));
});
const extent = convertExtent(evt.lat, evt.lon);
props.map.setExtent(extent);
mahalleLoad();
};
return (
<Select name='adresSelect' options={ilceler} onChange={(e) => ilceZoom(e)} placeholder='İlçe Seçiniz' />
);
};
const mapStateToProps = (state) => ({
map: state.map.map
});
export default connect(mapStateToProps, null)(AddressSearchMaks);
It can be related for some environment binding issue. Try to use the the setState as function:
useEffect(() => {
ilceLoad();
}, []);
const [ ilceler, setIlceler ] = useState([]);
const [ selectedIlce, setSelectedIlce ] = useState(null);
async function ilceLoad() {
let ilceList = await getAdres(ilceUrl);
setIlceler(ilceList); // update the state, it works here
}
const ilceZoom = (evt) => {
setSelectedIlce(prev => {
console.log("prev: ", prev);
console.log("evt.value: ", evt.value);
return evt.value;
});
const qTask = queryTask(url);
const q = query();
q.returnGeometry = true;
q.outFields = [ '*' ];
q.outSpatialReference = { wkid: 5254 };
q.where = `VARIABLE NAME=${evt.value}`;
qTask.execute(q, (evt) => {
const polyGon = polygon({
rings: evt.features[0].geometry.rings
});
props.map.graphics.add(graphic(polyGon, sfs));
});
const extent = convertExtent(evt.lat, evt.lon);
props.map.setExtent(extent);
};
Can you try like this. Because, in your code, you setting the data in selectedIlce, but before it re-render, your trying to checking the value in the console, so better use your console outside the event function, so that when it get updated, it will reflect in the console.
console.log('selectedIlce', selectedIlce);
const ilceZoom = (evt) => {
setSelectedIlce(evt.value);
....
}

Resources