I would like to add one specific member information (username + avatar) into an embed message. Does someone know how to do that?
const feedback = new discord.RichEmbed()
.setColor([0, 0, 255])
.setFooter("Bot created by : " + message.author.username, message.author.avatarURL)
.setDescription("The text I want to be sent")
On the code above, I would like to change "message.author.username" and "message.author.avatarUrl" by a specific discord member identification id such as : 436577130583949315 for example.
However I don't know what is the way from that discord identification number to be able to show the username and the avatar.
Thanks in advance for your help :)
The following code must be modified to use the latest version of Discord.js (v12 at the time of this edit) due to the implementation of Managers.
You can retrieve a user by their ID from the client's cache of users, Client#users. However, every user isn't guaranteed to be cached at all times, so you can fetch a user from Discord using Client#fetchUser(). Keep in mind, it returns a Promise. If the user is in the cache, the method will return it.
Example:
// Async context needed for 'await'
try {
const devID = '436577130583949315';
const dev = await client.fetchUser(devID);
const feedback = new discord.RichEmbed()
.setColor([0, 0, 255])
.setFooter(`Bot created by ${dev.tag}.`, dev.displayAvatarURL)
.setDescription('Your text here.');
await message.channel.send(feedback);
} catch(err) {
console.error(err);
}
Related
I have created a bot using Telegraf. I want that when a user sends a message, the bot will send him the previous message. So I want to take the previous post on id with Gram JS but throws this error
here is my code:
bot.on("message", async (ctx) => {
const { text, message_id } = ctx.message;
const userId = ctx.from.id;
const replyToMessage = await client.invoke(
new Api.channels.GetMessages({
channel: `${ctx.chat.id}`,
id: [message_id - 1],
})
);
console.log(1234, replyToMessage);
ctx.reply(replyToMessage);
});
I was inspecting telegram telethon api for a python task. I have some thougths about your issue.
The thing is telegram says it can not find anything with that id and channel. But I have some questions about your code.
As far as I know telegram either asks for a channel_id and channel_access_hash or the channel_username.
I am seeing that you give the telegram a channel_id and message_id ?
You should check your api docs again and try to find a method you can directly use the channel's username.
Note on that username : Telegram group or chat must be public or you must be auth, and (as far as python telethon) you must add the https:// appendix to channel_username.
I hope you can find a way out. If you further detail your question we can talk it again, I have spend plenty of time with python's telethon api.
I am currently making a bot to notify people by sending a message when a member role is being updated on the server. I don’t know how to set up the initial part which should be formally client.on part.
Here I have shown a bit of my code that I think should be working but unfortunately it is not working.
const Discord = require(‘discord.js’);
const client = Discord.Client();
client.on('guildMemberUpdate', (oldMember, newmember) => {
This is what I’m expecting to do:
Before I give you the code, I'll give you the steps that I took to achieve it.
Tip: ALWAYS use the documentation. The discord.js documentation helped me a lot of times.
Process:
Set up a designated text channel. In my case, I manually grabbed the channel's ID and set it as the variable txtChannel. You will have to replace my string of numbers with your own channel ID.
I cached every single role ID from the "new" member as well as from the "old" member.
Checked whether or not the length of the new member roles array was longer than the old member roles array. This signifies that the member has gained a role.
Created a filter function that "cancels" out every single role ID that both new and old role arrays have in common.
Grabbed the icon URL - I found out that if you try to get the URL of a user who has the default discord icon, it'll return NULL. To bypass this, you could just grab some sort of invisible PNG online and set it as a placeholder. Else you'll get an error saying that it wasn't able to retrieve the proper URL link.
Set up the embed, and sent it into the text channel!
Note:
At first, I couldn't figure out why the bot wasn't registering for other users who have their roles changed. Then I found this question on Stack Overflow. The link states that you have to make sure to enable Guild Members Intent. Just follow the instructions from the link and you should be all set! It's a little bit outdated (in terminology), so when it references "Guild Members Intent" it actually is "Server Members Intent" now.
Code:
It's awfully elaborate, but it gets the job done.
client.on('guildMemberUpdate', (oldMember, newMember) => {
let txtChannel = client.channels.cache.get('803359668054786118'); //my own text channel, you may want to specify your own
let oldRoleIDs = [];
oldMember.roles.cache.each(role => {
console.log(role.name, role.id);
oldRoleIDs.push(role.id);
});
let newRoleIDs = [];
newMember.roles.cache.each(role => {
console.log(role.name, role.id);
newRoleIDs.push(role.id);
});
//check if the newRoleIDs had one more role, which means it added a new role
if (newRoleIDs.length > oldRoleIDs.length) {
function filterOutOld(id) {
for (var i = 0; i < oldRoleIDs.length; i++) {
if (id === oldRoleIDs[i]) {
return false;
}
}
return true;
}
let onlyRole = newRoleIDs.filter(filterOutOld);
let IDNum = onlyRole[0];
//fetch the link of the icon name
//NOTE: only works if the user has their own icon, else it'll return null if user has standard discord icon
let icon = newMember.user.avatarURL();
const newRoleAdded = new Discord.MessageEmbed()
.setTitle('Role added')
.setAuthor(`${newMember.user.tag}`, `${icon}`)
.setDescription(`<#&${IDNum}>`)
.setFooter(`ID: ${IDNum}`)
.setTimestamp()
txtChannel.send(newRoleAdded);
}
})
I'm setting up logging with my Discord bot and I'm trying to figure out how to log bulk deletes, but I don't know how I would actually code it. Here's an example from another bot: https://imgur.com/a/yMQFKO9
Any help would be appreciated. Thanks!
I have tried to replicate the example you gave in your question.
Demonstration
Code
client.on('messageDeleteBulk', async messages => {
const length = messages.array().length;
const channel = messages.first().channel.name;
const embed = new Discord.MessageEmbed()
.setTitle(`${length} Messages purged in #${channel}`)
.setDescription(messages.map(message => `[${message.author.tag}]: ${message.content}`))
.setFooter(`${length} latest shown`)
.setColor('#dd5f53')
.setTimestamp();
// use this to send the message to the channel the bulk delete happened in
messages.first().channel.send(embed);
// alternatively, use this to send the message to a specific channel
(await client.channels.fetch(/* channel ID */)).send(embed);
});
References:
messageDeleteBulk event
MessageEmbed constructor
I am trying to build a setup menu for my bot that the server owner can use to configure the bot. The menu is triggered when the owner types =setup. I want the bot to reply with several embed messages asking the user questions in order to correctly configure the bot.
This is my first Discord.js project so I am unaware of the syntax but trying to learn. I have a constant variable called prefix assigned to = when the bot is implemented into the server.
The first prompt on the bot menu asks the user to change the prefix to anything they want. I need help understanding how to reassign my original constant variable to the new prefix they are requesting.
var PREFIX = '=';
bot.on('message', message=>{
let args = message.content.substring(PREFIX.length).split(" ");
switch(args[0]){
case 'setup':
const embed = new Discord.RichEmbed()
.setTitle('Step 1 of 1')
.setDescription('Set your Prefix')
.setColor(0xF1C40F)
message.channel.sendEmbed(embed);
//I want the user to now enter their own PREFIX and have the
//bot save their responce as the new PREFIX
break;
}
})
What I want to happen is when the user types their desired prefix, the bot will reassign prefix in the code, and delete the bots question and the users response and begin to prompt them with the next question.
depending if your bot is going to be in multiple servers with different prefixes:
If so then you need a database to save the prefix for each server and
then get it when a user sends a message from that server
If not I would use a json file to store the prefix, then have node
edit the file when it needs to change
Or look at https://discordjs.guide/keyv/ there is a great tutorial there to do what you want
You can't prompt the user to respond (from what I know), you'll need to wait for the user to write another message and analyze it.
A message is linked to a user, so when a user initiates the command to change the prefix, you want to make sure that the same user changed the prefix.
This untested but should be close to the solution you're looking for.
let prefix = '=';
let expectingResponseFrom = null;
bot.on('message', message=>{
// same user sent a response
if(expectingResponseFrom !== null && expectingResponseFrom === message.user.id){
expectingRepsonseFrom = null;
prefix = message.content.trim();
return;
}
const regex = new RegExp(`^${prefix}([^\s]+)`, 'g');
cosnt command = regex.exec(message.content)[1] || '';
switch(command){
case 'setup':
const embed = new Discord.RichEmbed()
.setTitle('Step 1 of 1')
.setDescription('Set your Prefix')
.setColor(0xF1C40F)
message.channel.sendEmbed(embed);
// memorize user who initiated a prefix change
expectingResponseFrom = message.user.id;
break;
}
})
The regex allows for a better (my opinion) way of getting the command
console.log(
(/^=([^\s]+)/g).exec("=hello should not get this"),
(/^=([^\s]+)/g).exec("="),
(/^=([^\s]+)/g).exec("= should not get this")
)
You should definitely use a database to store prefixes and other server settings, it's more efficient and stable than using a JSON file for example.
I suggest you use mongoose and/or just MongoDB if you're unsure as to what to use.
I need help with a command, for example, if someone writes
" !report #user Spamming " How can I do so my discord account gets a message from the bot about =
Who reports who and for what reason
I've tried watching videos and posts but I can't get my head around it
client.on('message', async function(message) {
if (message.content.startsWith(prefix + "report")) {
const user = await client.fetchUser(args[1].match(/^<#!?(\d+)>$/)[1]);
if (!user) return message.channel.send('Oops! Please mention a valid user.');
const reason = args.slice(2).join(' ');
const me = await client.fetchUser('123456890'); //My id
me.send(`${message.author} reported ${user} for: \`${reason}\``)
.catch(err => console.error(err));
}
}
)
I want for example
In channel = !report #patrick#4245 He is spamming
Then The bot sends a message to me
#fadssa#2556 Reported #patrick#4245 Reason = He is spamming
Before just copying this code, let's actually think this through...
So, let's start by first getting everything we need for the message. First, we should retrieve a User from the argument provided. We do this by comparing the string to that of a mention and picking out the ID. If one doesn't exist, we return an error telling the user to mention someone.
Now, assuming you already have your arguments declared (if not, see this guide to help), we can simply put together the arguments used for the reason. To do so, we should use Array.slice() and then join those words with Array.join().
Then, since we want the bot to send you a DM, we'll have to find you in the Discord world. For this, we can use client.fetchUser().
Now, we can just send you the DM and you'll be alerted of all reports.
/*
* Should be placed within your command's code, after checking required arguments exist
* Assuming 'client' is the Discord Client and 'args' is the array of arguments
* Must be within an async function to use 'await'
*/
const user = await client.fetchUser(args[1].match(/^<#!?(\d+)>$/)[1]); // see below
if (!user) return message.channel.send('Oops! Please mention a valid user.');
const reason = args.slice(2).join(' ');
const me = await client.fetchUser('189855563893571595'); // replace with your ID
me.send(`${message.author} reported ${user} for: \`${reason}\``))
.catch(err => console.error(err));
Although it may look confusing, using regex is a much better option than message.mentions. There's plenty of whack examples where seemingly perfect code will not return the expected user, so this is why I would definitely choose retrieving the ID from a mention myself.