Discord.js bot sending two memes from different reddits - javascript

So basically, I'm trying to get my discord bot to send a meme from r/marvelmemes, as the bot is for a MCU themed server. I followed a tutorial to create my code, and in the tutorial, the coder used r/memes. I only changed one thing. I changed this line:
got('https://www.reddit.com/r/memes/random/.json').then(response => {
Into this:
got('https://www.reddit.com/r/marvelmemes/random/.json').then(response => {
That's all I changed from the original tutorial. When I try to run the bot, it does in fact send a meme from r/marvelmemes. However, it also sends a meme from r/memes. It sends two memes. How do I make it so that it only sends one meme from r/marvelmemes? Here's the full code.
const got = require ('got');
module.exports = {
name: 'meme',
description: "send a meme",
execute(message, args, Discord) {
const embed = new Discord.MessageEmbed()
got('https://www.reddit.com/r/marvelmemes/random/.json').then(response => {
let content = JSON.parse(response.body);
let permalink = content[0].data.children[0].data.permalink;
let memeUrl = `https://reddit.com${permalink}`;
let memeImage = content[0].data.children[0].data.url;
let memeTitle = content[0].data.children[0].data.title;
let memeUpvotes = content[0].data.children[0].data.ups;
let memeDownvotes = content[0].data.children[0].data.downs;
let memeNumComments = content[0].data.children[0].data.num_comments;
embed.setTitle(`${memeTitle}`)
embed.setURL(`${memeUrl}`)
embed.setImage(memeImage)
embed.setColor('RANDOM')
embed.setFooter(`πŸ‘ ${memeUpvotes} πŸ‘Ž ${memeDownvotes} πŸ’¬ ${memeNumComments}`)
message.channel.send(embed);
})
}
}
I use a basic command handler, and here's what it looks like if it helps:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command == 'meme') {
client.commands.get('meme').execute(message, args, Discord);
}
Any help would be appreciated!

I'm pretty sure you have a second bot running because of multiple terminals.
If you have Visual Studio Code, you can see them here:
Here you are able to delete terminals (red box)

Related

im making a discord bot for the first time in discord js and my test command wont work

This is "my code" and the command doesn't work. tried following a YouTube tutorial. this is my first time trying to do something like this. all my code experience comes from simple python code. so if you have any vids that explains this pls send
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions, Message } = require(`discord.js`);
const prefix = '>';
const client = new Client({
intents: [
32767
]
});
client.on("ready", () => {
console.log("botong is online!")
client.user.setPresence({
status: 'online',
activity: {
name: 'status',
type: 'ActivityType.Playing'
}
});
});
client.on("messageCreate", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
//message array
const messageArray = message.content.split(" ");
const argument = messageArray.slice(1);
const cmd = messageArray[0];
//commands
//test commands
if (commands === 'test') {
message.channel.send("Bot is working!")
}
})
client.login("MY TOKEN");
tried to run this and nothing happened, it should send a message in my discord server saying "Bot is Working"
so if you have any vids that explains this pls send
Here's an article from Codeacademy which explains how to create a simple Discord bot. https://www.codecademy.com/article/christine_yang/build-a-discord-bot-with-node-js
Reason why your test message doesn't appear: the message never gets sent because you haven't defined commands so it can obviously never be 'test'.
if (commands === 'test') {
message.channel.send("Bot is working!")
}
Edit: Here's a code sample from the article which sends message to the channel each time someone sends "Hello" there.
client.on('messageCreate', msg => {
// You can view the msg object here with console.log(msg)
if (msg.content === 'Hello') {
msg.reply(`Hello ${msg.author.username}`);
}
});

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにけは、私はDiscordγƒ­γƒœγƒƒγƒˆγ§γ™γ€‚ε§‹γ‚γŸγ„γͺら、!jhelp タむプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにけは、私はDiscordγƒ­γƒœγƒƒγƒˆγ§γ™γ€‚ε§‹γ‚γŸγ„γͺら、!jhelp タむプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

How to clear previous Discord.MessageEmbed data in Discord.js

I'm trying to make a snipe command for the dc bot but I can't get the embed to reset. Tried putting embed = {} in different locations, then it tries sending an empty message the next time and errors out. Also it's let embed now since I was testing, tried const first. Edit: works now when checking messages elsewhere, should have done that to start with. Code:
bot.on('messageDelete', message => {
let embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.username} (${message.author.id})`, message.author.avatarURL())
.setDescription(message.content || "None")
bot.on('message', message => {
const args = message.content.slice(PREFIX.length).split(/ +/);
const cmd = args.shift().toLowerCase();
if (cmd === 'msg'){
message.channel.send(embed)
}
})
})
You don't need a embed = {}, instead use client.snipes = new Map() as collector. So if someone delete message when the bot online, the bot can detect it.
client.snipes = new Map()
client.on('messageDelete', function(message, channel) {
client.snipes.set(message.channel.id, {
content: message.content,
author: message.author,
image: message.attachments.first() ? message.attachments.first().proxyURL : null
})
}) //This will be your collector on your index file.
Then create a command file.
const msg = client.snipes.get(message.channel.id)
if(!msg) return message.channel.send("Didn't find any deleted messages.")
const embed = new MessageEmbed()
.setDescription(`Your_Message`)
.setTimestamp()
if(msg.image) embed.setImage(msg.image) //If image deleted, it will go here.
message.channel.send({ embeds: [embed] })
Every time a message is deleted you are resubscribing to the message event.
I would suggest taking some of that logic to the outside of that scope.
let embed = null;
bot.on('messageDelete', message => {
embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.username} (${message.author.id})`, message.author.avatarURL())
.setDescription(message.content || "None")
})
bot.on('message', message => {
const args = message.content.slice(PREFIX.length).split(/ +/);
const cmd = args.shift().toLowerCase();
if (cmd === 'msg' && embed){
message.channel.send(embed)
}
})

how do I make a discord bot I made configurable per server?

I recently made a discord word filter bot and I was wondering how I could make it configurable per server? I want to be able to make a command that adds words to be filtered to the code and I want people to be able to add a custom prefix per server. I also want people to be able to set their log channel per server. Can someone help me with this please? I spent a lot of time on this bot and I dont want to just keep making more of the same bot for different servers. I'm using discord.js 12.5.3. I'll attach my code below.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', async () => {
console.log('yay, the bot is online')
client.user.setActivity('im real', {type: 'PLAYING'})
})
client.on('message', async message => {
if(message.channel.type === 'dm' || message.author.bot) return;
const logChannel = client.channels.cache.find(channel => channel.id === '921730444498726924')
let words = [β€œbad”, β€œwords”, β€œhere”]
let foundInText = false;
for (var i in words) {
if (message.content.toLowerCase().includes(words[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
let logEmbed = new Discord.MessageEmbed()
.setDescription(<#${message.author.id}> Said a bad word)
.addField('The Message', message.content)
.setColor('RANDOM')
.setTimestamp()
logChannel.send(logEmbed)
let embed = new Discord.MessageEmbed()
.setDescription('That word is not allowed here')
.setColor('RANDOM')
.setTimestamp()
let msg = await message.channel.send(embed);
message.delete()
msg.delete({timeout: '3500'})
}
})
I've tried following a tutorial but it didn't help because I need one specifically for my case. If anyone could help, that would be great.

discord bot not processing the command

I was adding some new commands to my discord v12 bot. But it's not responding to the code I typed. Any help is appreciated.
This section is inside index.js
client.admins = new discord.Collection();
const admins = fs.readdirSync('./custom/admin').filter(file => file.endsWith('.js'));
for (const file of admins) {
const admin = require(`./custom/admin/${file}`);
client.admins.set(admin.name.toLowerCase(), admin);
};
This is the code to process the above lines
if (message.author.bot || message.channel.type === 'dm') return;
const prefix = client.config.discord.prefix;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const admin = args.shift().toLowerCase();
const adm = client.admins.get(admin) || client.admins.find(adm => adm.aliases && adm.aliases.includes(admin));
if (adm) adm.execute(client, message, args);
And the function which I am trying the bot to do is named delete.js
module.exports = {
name: 'snap' ,
aliases: [],
category: 'admin',
utilisation: '{prefix}snap [number]',
execute(message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")
if (message.member.hasPermission('ADMINISTRATOR') ){
const {MessageAttachment} = require('discord.js');
const snaping = new MessageAttachment('./snap.gif')
message.channel.send(snaping)
setTimeout(snapCommand , 9000 ,args, message)
}
else
{
message.channel.send("-_- you are not an admin,Then why are you trying to use admin commands");
}
function snapCommand(args, message){
var del= args ;
del = parseInt(del , 10)
message.channel.bulkDelete(del+2);
}
}
}
when I launch the bot it shows no error msg, So that's a good sign I think, but when I use !snap 5
'!' which is my prefix. The bot does nothing. No error in the console also. Does anyone have any idea to solve this?
Never mind, I fixed it by adding client to the delete.js code
execute(client, message, args) {
if(isNaN(args)) return message.reply("Bruh,Specify how much message should I delete")
if(args>99) return message.reply("You ain't making me do that much work boi")

Categories

Resources