I'm working on my discord bot and I want it to save messages that i sent it to save, how do I do this since the rest of the internet doesn't ask this question for some reason. i've been looking for someone to point me in a direction but haven't found anything
This is a really simplified version of what you want to do but I'm sure if you read it you'll understand and it will get the job done.
const discord = require('discord.js'); // Import discord.js
const client = new discord.Client(); // Initialize new discord.js client
const messages = [];
client.on('message', (msg) => {
if (!msg.content.startsWith('+')) return; // If the message doesn't start with the prefix return
const args = msg.content.slice(1).split(' '); // Split all spaces so you can get the command out of the message
const cmd = args.shift().toLowerCase(); // Get the commands name
switch (cmd) {
case 'add':
messages.push(args.join(' ')); // Add the message's content to the messages array
break;
case 'get':
msg.channel.send(messages.map((message) => `${message}\n`)); /* Get all the stored messages and map them + send them */
break;
}
});
client.login(/* Your token */); // Login discord.js
Related
I'm trying to save a value of the server being "Down" or "Up", it seems to be working fine, however, when I clear the console, then run the bot again, it looks to have reset the database fully, is there a way to make the database, work like a normal database would? (Save after restart)
I'm having a check to see if the server is up, then don't allow it to run the command and say it's already online.
I wasn't like this before, and I haven't used quick.db for a while, so sorry if I missed anything.
Code:
// Main requirements
const { ROLE_SSUPIN, CHANNEL_SSU, CHANNEL_ROLESEL, BOT_PREFIX } = require('../../config.json')
const commandName = 'ssu'
// Optional Requirements
const { MessageEmbed } = require('discord.js')
const { QuickDB } = require('quick.db');
const db = new QuickDB();
// Main Code
module.exports = async client => {
client.on('messageCreate', async message => {
if (message.author.bot) return;
if (!message.content.toLowerCase().startsWith(BOT_PREFIX)) return;
const command = message.content.split(' ')
const args = message.content.substring(1).split(' ')
if (command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith(commandName)) {
const ssuStatus = await db.get("ssu.status")
await db.set("ssu.status", "down");
console.log(ssuStatus)
if (!message.member.roles.cache.get('998320362234323026')) return message.reply("Only staff with `SSU Permissions` can use this command!")//.then(m => {setTimeout( function() { m.delete(), message.delete() }, 10000)});
if (!message.channel.id == CHANNEL_SSU) return message.reply(`Please use this command in <#${CHANNEL_SSU}>.`)
if (ssuStatus == 'up') return message.reply(`Server Status is already set to Online. Say \`${BOT_PREFIX}Server Status Set Offline\` if you believe this is a mistake.`)
message.channel.send(`
Start up done.
`)
.then(await db.set("ssu.status", "up"))
}
})
}
I had "await db.set("ssu.status", "down");" in the start of each function, so it was reseting it back to "Down", I didn't mean for it do that, if you have the same issue, make sure that you don't have anything that sets the database value in the start, as it might be the reason it's getting reset and you think it's wiping.
My bot is not reading the Discord chat. I want it to read the chat and if it finds certain words it will give a certain response. This is my current message event code. This is my first JavaScript project and I have just started learning it so please rip it apart so I can learn quicker :)
At the moment I can get the bot to load into discord. I can turn it on with .node but I can not get it to read a message using message.content.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
var name = "Poker Bot";
var usersHand
let firstCardValue
let secondCardValue
let firstCardSuit
let secondCardSuit
//starts the bot and sets activity to a funny quote. it also will give a command prompt notification that the
// bot is online
client.on("ready", () => {
console.log(`Bot is online: ${name} !`);
client.user.setActivity('Burning The Fucking Casino Down');
});
//check discord chat to see if a user has posted.
client.on("messageCreate", message => {
//console.log is there to test user input. If it works the message in the discord channel will appear in console
console.log(`The user has said: ${message} `);
//look for poker hand ~~~ position ~~~~ event (ex: AA CO PF ) (PF= PreFlop)
if (message.content.toLowerCase == 'AK' || message.content.toLowerCase == 'AA' || message.content.toLowerCase == 'KK'){
message.reply("RECOMMENDED PLAY SHOVE: ALL IN")
}
.content is not a method, it's a property, you must now also enable the Message Content intent on your bot page as well as in your code.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
client.on("messageCreate", message => {
// || "String" like you did before would return "true" in every single instance,
// this is case sensitive, if you wanna make it case insensitive
// use `message.content.toLowerCase() == "lowercasestring"`
if (message.content == "AK" || message.content = "AA" || message.content == "KK") {
message.channel.send("Recommend Play is to shove all in" + message.author);
}
})
client.login(token);
Judging by your information, you dont just want to send a response if the message contains only those strings, but may just contain then.
To check for that, I would suggest to use regex#test
Still as #iiRealistic_Dev rightfully mentioned: message.content is not a function, so removing the brackets is the way to go.
client.on("messageCreate", (message) => {
if (/AK|AA|KK/.test(message.content)) {
message.channel.send("Recommend Play is to shove all in" + message.author);
console.log('it got to here');
}
});
I need the code to send a message to a channel I have looked on stack overflow but there all too old and through up a error
There is a guide for this on the discord.js guide.
const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');
An improved version would be:
<client>.channels.fetch('<id>').then(channel => channel.send('<content>'))
At first you need to get the channel ID or Channel Name to do that
/* You handle in command and have message */
// With Channel Name
const ChannelWantSend = message.guild.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = message.guild.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');
/* If you start from root of your bot , having client */
// With Channel Name
const ChannelWantSend = client.channels.cache.find(channel => channel.name === 'Channel Name');
// With Channel ID
const ChannelWantSend = client.channels.cache.get(channelId);
ChannelWantSend.send('Your Message');
// In both case If ChannelWantSend is undefined where is a small chance that discord.js not caching channel so you need to fetch it
const ChannelWantSend = client.channels.fetch(channelId);
Discord.js sending a message to a specific channel
Not sure if you have tested out this code yet, but it looks like this may answer your question?
I haven't tested this, but the thread I linked seems to have tested it as of June 2020!
Shortly, I send message to specific channel like under.
<client>.channels.cache.get("<channel_id>").send("SEND TEXT");
Under code piece is my own usage.
In my case, I save all of Direct Messages to my own channel.
const Discord = require('discord.js');
const client = new Discord.Client();
function saveDMToAdminChannel(message) {
var textDM = `${message.author.username}#${message.author.discriminator} : ${message.content}`;
client.channels.cache.get("0011223344556677").send(textDM);
// "0011223344556677" is just sample.
}
client.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type == 'dm') {
saveDMToAdminChannel(message);
}
});
In my own channel, DM's are saved like,
00:00 User1#1234 : Please fix bug
07:30 User2#2345 : Please fix bug!!
10:23 User3#3456 : Please fix bug!!!!
I have been working on a new Discord Bot which would be able to relay an announcement from the origin server to all other servers the bot is in. I am very new to programming so is there any hope for my idea. I'll send my current code right now.
const discord = require('discord.js');
const bot = new discord.Client();
const token = '<token>';
const PREFIX = '&';
const server;
const DChannel;
bot.on('ready', () =>{
console.log('Milsim Network Online');
server = bot.guilds.get(719415100221554688);
DChannel = server.channels.get(719424622633680906);
console.log('--------------------\n\n\nREADY: '+ new Date() +'\n\n\n--------------------');
})
bot.on('message', message=> {
let args = message.content.substring(PREFIX.length).split(" "); // Single Argument Commands //
switch(args[0]) {
case 'ping':
message.channel.send('pong!');
break;
case 'UMA':
message.channel.send('website link here');
break;
case 'info':
message.channel.send('Please select: **PMC**, **MILSIM**, or **UMA** to learn more about them');
break;
}
if (message.channel.type.toLowerCase() == 'dm' || message.channel.type.toLowerCase() == 'group') {
var embed = new Discord.RichEmbed()
.setAuthor(message.author.username, message.author.avatarURL)
.setDescription(message.content)
.setTimestamp(new Date())
.setColor('#C735D4');
DChannel.send(embed);
}
})
bot.login (token);
I understand it may seem very disorganized and messy and I apologize for that.
Here's a step in the desired direction. My example gets the rest of the message content (not including the command) and sends it to the first channel of every guild the client is in. Note that 'first' channel means the one lowest on the channel list.
let announcement = args.slice(1).join(' ');
bot.guilds.cache.forEach(guild => {
let channel = guild.channels.cache.first();
channel.send(announcement);
});
It does appear that you're not using discord.js v12, so the above code will only work if you remove all instances of cache, e.g bot.guilds.cache.forEach() --> bot.guilds.forEach()
I'm attempting to make a discord bot that checks messages sent in channels for a prefix and argument (!send #Usermention "message"), but despite running, the program closes out as soon as a message is typed in my discord server, not outputting any error messages, so I'm not really sure what to do...
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const prefix = "!";
client.on("message", (message) =>
{
msg = message.content.toLowerCase();
if (message.author.bot) { return; }
mention = message.mention.users.first(); //gets the first mention of the user's message
if (msg.startsWith (prefix + "send")) //!send #name [message]
{
if (mention == null) { return; } //prevents an error sending a message to nothing
message.delete();
mentionMessage = message.content.slice (6); //removes the command from the message to be sent
mention.sendMessage (mentionMessage); //sends message to mentioned user
message.channel.send ("message sent :)");
}
});
client.login(auth.token);
mention = message.mention.users.first();
It is message.mention**s**. You were missing an s.
Also, you might want to use send, rather than sendMessage, since sendMessage is deprecated.