Open and scan dms for key words - discord

I'm working on a bot, and wanted to know if there was a way to open dms from all people in a server, and see if any commands were in there. If so I want the commands to be completed, but only with certain key words. Please help!

You can loop through the Guild's members collection and access the GuildMember's DMchannel using GuildMember.user.dmChannel then fetch all the messages using dmChannel.messages.fetch() then use filter() to get the messages with the keywords you're looking for
message.guild.members.cache.forEach(async (member) => {
const fetchedMsgs = await member.user.dmChannel.messages.fetch()
const messages = fetchedMsgs.filter((message) => message.content.toLowerCase().includes('search term')) // make sure the search term is lowercase
messages.forEach((message) => console.log(`${message.author.username} (${message.author.id}): '${message.content}' # ${message.createdAt}`)
})

Related

Discord.js - Delete all channel by running Discord-Bot without a command

Hey i need for a project a tool to delete all channsl on a Discordserver via a Discord.js Bot.
i got one with handlers and this is my "event code" but dosent work.
Discord.js v14
const client = require("../../index");
module.exports = {
name: "blacksheep"
};
client.on("ready", () => {
var server = Client.guilds.get('1045245227264397382');
for (var i = 0; i < server.channels.array().length; i++) {
server.channels.array()[i].delete();
}})
i dont find the right way to get it worked. thx <3
Then i start the bot all Channels should be deletet without any command.
You need to include error messages or what the results of running this code was for us to actually help you, but for now I'm going to assume that everything in your bot and bot event handlers is working except for the last three lines that loop through the channels and delete them. If that's the case, then you just need to change those lines to something like this (replace your for-loop block with this):
server.channels.cache.forEach((channel) => {
channel.delete();
});
This accesses the server's channel cache, which is a collection, and so it uses the collection's forEach function to loop through all the channels, and then calls each of the channels' delete() functions to delete them.
Note that you may experience severe ratelimiting when doing this, because Discord has heavy ratelimits on requests to server channels.

How to check if message contains emojis discord.js

I need to check if a message sent by user contains emojis because my database can't store this type of data. So I thought that I'll use a message.content.match() or message.content.includes() but when I use it, it still is not enough. I was thinking about making something like blacklist but for emojis and then I realized that I need to save a blacklist of all emojis so I gave up on that. My question for you is, do you know any easier way to make this? I was searching for solution to my problem but I didn't find anything.
Thank you a lot for any help.
if(message.author.id!='botid' && message.author.id===userdbId && message.content.match(/<a?:.+?:\d+>/)){
const name = args.join(" ");
const username = name.slice(0);
conn.query(`UPDATE users SET ignick='`+username+`' WHERE userID='${message.author.id}'`);
console.log(username);
message.channel.send("success message");
conn.end(err => {
if(err){
throw error;
}
console.log('Disconnected from database');
})
}
else{
console.log('bot has been stopped from adding his message to database');
}```
At top of this code i made a connect function and two constructors to pull from database userId
Whenever an emote is used in a message, it follows this format: <:OmegaStonks:723370807308582943>, where the name of the emote is "OmegaStonks" and the id links to the link to the image, like so: https://cdn.discordapp.com/emojis/723370807308582943.png
Detecting this pattern is pretty easy using regex.
<a?:.+?:\d+>
which takes any character from the first : to the second : (and I used a ? to make the wildcard . stop as soon as possible). You also can't have colons in emote names, so it won't abruptly stop there.
Source
Here is how you could do it
client.on('message', msg => {
if(msg.content.match(/<a?:.+?:\d+>/)) return; //or whatever action(s) you want to do
})

How do i make discord.js list all the members in a role?

if(message.content == `${config.prefix}mods`) {
const ListEmbed = new Discord.MessageEmbed()
.setTitle('Mods:')
.setDescription(message.guild.roles.cache.get('813803673703809034').members.map(m=>m.user.tag).join('\n'));
message.channel.send(ListEmbed);
}
Hey so iam making a command which displays all the members with that role but it only seems to be sending 1 of the mods
await message.guild.roles.fetch();
let role = message.guild.roles.cache.find(role => role.id == args[0]);
if (!role) return message.channel.send('Role does not exist'); //if role cannot be found by entered ID
let roleMembers = role.members.map(m => m.user.tag).join('\n');
const ListEmbed = new Discord.MessageEmbed()
.setTitle(`Users with \`${role.name}\``)
.setDescription(roleMembers);
message.channel.send(ListEmbed);
};
Make sure your command is async, otherwise it will not run the await message.guild.roles.fetch(); - this fetches all roles in the server to make sure the command works reliably.
In Discord.jsV12 the get method was redacted and find was implemented.
Aswell as this, I would highly recommend defining variables to use in embeds and for searching since it is much more easy to error trap.
If you have many members with the role, you will encounter the maximum character limit for an embeds description. Simply split the arguments between multiple embeds.

Why doesn't Collection#find work for offline members who have no roles? (discord.js)

My Goal
My goal is to figure out why Collection#find returns undefined when I try to find a user in my server, but they're offline and have no roles.
Expectation
Usually the console logs an array of all the properties of the user
Actual Result
The console logs Collection#find, as undefined if the user in my server is offline and has no roles
What I've Tried
I've tried using Collection#get, but it turns out that it returns the same response. I've tried searching this up on Google, but no one has asked this question before.
Reproduction Steps
const Discord = require('discord.js');
const client = new Discord.Client();
const {prefix, token} = require('./config.json');
client.once('ready', () => {
console.log('Client is online');
const user = client.users.cache.find(user => user.tag === 'Someone#1234');
console.log(user);
};
client.login(token);
Make sure that whoever is helping you, whether it's an alt account or your friend, that they have no roles, and they're completely offline in your server
Output:
Client is online undefined
I had the same problem. I don't know why this happens, but I used this line to fix that:
((await m.guild.members.fetch()).filter(mb => mb.id === "The ID")).first()`
Basically, this collect all the members, then filters them with the property you want, and the first() at the end is to make it a single object instead of a collection.
Instead of the user.tag property, try using the user.username and the user.discriminator properties. This worked for me
const user = client.users.cache.find(user => user.username === 'Someone' && user.discriminator === '1234');
Also check spelling, capitalization, ect.
A simple solution to my problem is just create an async function and use await guild.members.fetch() to cache the users and then use Collection#find to get the user.

How to save some variables

ABOUT ME:
This question is aimed at using for a Discord bot using Discord.js
I'm used to doing coding in older coding languages like C++, C#, Batch, and Game Maker Studio, but I'm still new to Discord.js
THE INTENT:
I want to store some basic variables. Such as "Server Rupees" which is shared by everyone.
And maybe a couple others. Nothing individual. Not a database. Not an array.
THE QUESTION:
I've heard this can be done with a json file. How do I save one variable to a place I can get it back when the bot goes online again?
And once I have it saved. How do I get that variable back?
WHAT I KNOW:
Not a lot for Discord.js . My bot has about 20 different commands, like adding roles, recognizing a swear and deleting that message, kick/ban a user, bulk delete messages, etc.
Yes it can be done with a json file or database,
If you are gonna go with json:
Store the value inside of a json file to start of with, for example:
./my-data.json
{ "Server-Rupees": 200 }
You would get the result by requiring the file
const data = require("path-to-json.json");
console.log(data["Server-Rupees"])
// => 200
If you want to update the value, just update the property value and use fs.writeFile
const { writeFile } = require("fs");
const data = require("path-to-json.json");
data["Server-Rupees"] += 20;
//JSON.striginfy makes the object into a string, `null, 6` makes it prettier
writeFile("path-to-json.json", JSON.stringify(data, null, 6), err => {
if(err) console.error(err);
})
Note: writeFile's path won't always be the same as require's path even for the same file.

Resources