client.on('raw', async dados => {
if(dados.t == 'PRESENCE_UPDATE' && this.client.guilds.cache.get("948835296089342012").members.cache.get(dados.d.user.id)){
let membro = this.client.guilds.cache.get("948835296089342012").members.cache.get(dados.d.user.id)
if(dados.d.activites.state == null) return membro.roles.remove("653651520361070612")
if(dados.d.activities.state == undefined) return membro.roles.remove("653651520361070612")
let valor = dados.d.activities.state.toLowerCase()
let n = valor.search(`discord.gg/server`)
if(n>=0) membro.roles.add("653651520361070612")
if(n<0 && membro.roles.cache.has("653651520361070612")) membro.roles.remove("653651520361070612")
}
log=
user: { id: '932194344859996180' },
status: 'online',
guild_id: '947899731303096320',
client_status: { web: 'online' },
activities: [
{
type: 4,
state: 'aa536a43',
name: 'Custom Status',
id: 'custom',
created_at: 1647655901662
}
]
}
I'm creating an event to identify the member's Status, for example: if the member has the url in the discord.gg/3 status the member will receive a position and when he removes the status the bot will remove the selected position
The presence is only available on GuildMember not an user. Get the member who used the command from message.member (make sure that the command is used in a guild)
Now read the member's presence through message.member.presence. Seems like you are trying to get member's custom status. It's one of presence.activities array and has the type Activity. Find in that array which has the type is CUSTOM, that is what you need. Note that presence can be null so you need to check if it exists.
This is the code I have tested and it works. Hope it works for you too:
const member = message.member; // Get member from message
const custom = member.presence?.activities?.find(x => x?.type === 'CUSTOM'); // Get the custom status from member's presence
if (custom?.includes('cat') console.log('This user has `cat` in his/her custom status');
else { console.log('This user doesn\'t have `cat` in his/her custom status'); }
const Command = require("../../structures/Command");
module.exports = class teste extends Command {
constructor(client) {
super(client);
this.client = client;
this.name = "teste";
this.category = "Fun";
this.description = ".";
this.usage = "";
this.aliases = [];
this.enabled = true;
this.guildOnly = true;
}
async run({ message, args}, t) {
const user =
this.client.users.cache.get(args[0]) ||
message.mentions.members.first() ||
message.author
console.log(user.presence.activities.state)
}
}
I also tried to use this without being on the basis of the Event but on the command, it always returns undefined
log=
[
Activity {
id: 'custom',
type: 'CUSTOM',
url: null,
details: null,
state: 'aa536a43',
applicationId: null,
syncId: null,
platform: null,
party: null,
assets: null,
flags: ActivityFlags { bitfield: 0 },
emoji: null,
sessionId: null,
buttons: [],
createdTimestamp: 1647656752595
}
]
Related
Yes I know TLDR but I would appreciate the help
Ok I have this wall of code below I use for applications
It uses a button to start the application (asking questions)
and after the application is filled in it sends that application to a specified applicationChannelId
is there any way I could add buttons to the application that was sent to the applicationChannelId to accept or deny members?
Accept would add a role by id and sends a message to the original applicant
//Not the code I tried using just an example for what the Accept button would do
//
let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
member.roles.add(teamRole)
member.send("You have been accepted into the team")
Deny would send a message to the original applicant
I have tried doing this for the past few days but just can't get it to work it either does nothing or breaks everything
I have removed some info from the code below to make it shorter
Code for my button I already use to start the application for an applicant
client.on("message", async (message) => {
const reqEmbed = {
color: 0xed5181,
title: 'Blind Spot Team Requirements',
url: 'link',
author: {
name: '',
icon_url: '',
url: '',
},
description: '',
thumbnail: {
url: '',
},
fields: [{
"name": `Read through these Requirements`,
"value": `- requirments will go here`,
}, ],
image: {
url: '',
},
footer: {
text: 'Blind Spot est 2019',
icon_url: 'link',
},
};
//
// Don't reply to bots
let admins = ['741483726688747541', '741483726688747541'];
if (message.content.startsWith(`#blindspot`)) {
message.delete();
const amount = message.content.split(" ")[1];
if (!admins.includes(message.author.id)) {
message.reply("You do not have permission to do that!");
return;
}
// Perform raw API request and send a message with a button,
// since it isn't supported natively in discord.js v12
client.api.channels(message.channel.id).messages.post({
data: {
embeds: [reqEmbed],
components: [{
type: 1,
components: [{
type: 2,
style: 4,
label: "Apply",
// Our button id, we can use that later to identify,
// that the user has clicked this specific button
custom_id: "send_application"
}]
}]
}
});
}
});
Rest of code that handles questions and sends application to applicationChannelId when complete
// Channel id where the application will be sent
const applicationChannelId = "652099170835890177";
// Our questions the bot will ask the user
const questions = ["These are the questions but have deleted them to make this shorter",];
// Function that will ask a GuildMember a question and returns a reply
async function askQuestion(member, question) {
const message = await member.send(question);
const reply = await message.channel.awaitMessages((m) => {
return m.author.id === member.id;
}, {
time: 5 * 60000,
max: 1
});
return reply.first();
}
client.ws.on("INTERACTION_CREATE", async (interaction) => {
// If component type is a button
if (interaction.data.component_type === 2) {
const guildId = interaction.guild_id;
const userId = interaction.member.user.id;
const buttonId = interaction.data.custom_id;
const member = client.guilds.resolve(guildId).member(userId);
if (buttonId == "send_application") {
// Reply to an interaction, so we don't get "This interaction failed" error
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "I have started the application process in your DM's.",
flags: 64 // make the message ephemeral
}
}
});
try {
// Create our application, we will fill it later
const application = new MessageEmbed()
.setTitle("New Application")
.setDescription(`This application was submitted by ${member}/${member.user.tag}`)
.setFooter("If the #Username doesn't appear please go to general chat and scroll through the member list")
.setColor("#ED4245");
const cancel = () => member.send("Your application has been canceled.\n**If you would like to start your application again Click on the Apply button in** <#657393981851697153>");
// Ask the user if he wants to continue
const reply = await askQuestion(member, "Please fill in this form so we can proceed with your tryout.\n" + "**Type `yes` to continue or type `cancel` to cancel.**");
// If not cancel the process
if (reply.content.toLowerCase() != "yes") {
cancel();
return;
}
// Ask the user questions one by one and add them to application
for (const question of questions) {
const reply = await askQuestion(member, question);
// The user can cancel the process anytime he wants
if (reply.content.toLowerCase() == "cancel") {
cancel();
return;
}
application.addField(question, reply);
}
await askQuestion(member, "Would you like to submit your Application?\n" + "**Type `yes` to get your Application submitted and reviewed by Staff Members.**");
// If not cancel the process
if (reply.content.toLowerCase() != "yes") {
cancel();
return;
}
// Send the filled application to the application channel
client.channels.cache.get(applicationChannelId).send(application);
} catch {
// If the user took too long to respond an error will be thrown,
// we can handle that case here.
member.send("You took too long to respond or Something went wrong, Please contact a Staff member\n" + "The process was canceled.");
}
}
}
});
at this point I just feel like not even doing this and keep it as is because its driving me insane
You very well can! just send it as you send your normal buttons!
const {
MessageButton,
MessageActionRow
} = require("discord.js"),
const denybtn = new MessageButton()
.setStyle('DANGER')
.setEmoji('❌')
.setCustomId('deny')
const acceptbtn = new MessageButton()
.setStyle('SUCCESS')
.setEmoji('✔')
.setCustomId('accept')
client.channels.cache.get(applicationChannelId).send({
embeds: [application],
components: [new MessageActionRow().addComponents["acceptbtn", "denybtn"]]
});
const collector = msg.createMessageComponentCollector({
time: 3600000,
errors: ["time"],
});
await collector.on("collect", async (r) => {
if (r.user.id !== message.author.id)
return r.reply({
content: "You may not accept/ deny this application",
ephemeral: true,
});
if (r.customId === "acceptbtn") {
let teamRole = message.guild.roles.cache.find(role => role.id == "761996603434598460")
member.roles.add(teamRole)
member.send("You have been accepted into the team")
}
if (r.customId === "denybtn") {
member.send("You have been rejected");
}
});
NOTE: Please be mindful that since your question lacks the functions / method definitions you are using I have used discord.js v13's methods, you may update your discord.js version and the code will work as intended ALTHOUGH the component collector's functions have been directly copy pasted from your question and in some instances such as member#send member is not defined, so please take this as an example and I urge you to write the code instead of copy pasting directly!
Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.
So I was trying to put code into my Discord bot to give it a custom status for users to see, then when I found the code I had no idea where to put it.
Here's the code: where should I put it?
* Sets the full presence of the client user.
* #param {PresenceData} data Data for the presence
* #returns {Promise<ClientUser>}
* #example
* // Set the client user's presence
* client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
* .then(console.log)
* .catch(console.error);
*/
setPresence(data) {
return new Promise(resolve => {
let status = this.localPresence.status || this.presence.status;
let game = this.localPresence.game;
let afk = this.localPresence.afk || this.presence.afk;
if (!game && this.presence.game) {
game = {
name: this.presence.game.name,
type: this.presence.game.type,
url: this.presence.game.url,
};
}
This code above belongs to the ClientUser.js file. It might belong to other files like Presence.js
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: 'online',
activity: {
name: ".help",
type: "PLAYING"
}
});
});
The status can be online, idle, dnd, or invisible. (dnd is Do not disturb)
The other variable here is activity. It is a group of two variables: name and type.
The name is what the bot is doing. This is a string of your choice. The type is the other thing that will help it display as. It can be "PLAYING", "STREAMING", "WATCHING", "LISTENING", and "CUSTOM_STATUS".
You can put it anywhere but most likely you want to put it into your ready event like
client.on('ready', () => {
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
console.log(`${client.user.username} is up and running!`);
})
I have an array of user objects called allUsers and I need to check each object in it with the groupId which is passed to the function and return userNames which have the passed groupId.
I attempted this in the following manner.
vm.setNames=function(groupId){
var products = "";
angular.forEach(vm.allUsers,function (f) {
if(f.groupId==groupId){
vm.user=f;
users= users+','+" "+vm.user.userName;
}
})
return users= ;
}
I want to have it in a map with group id as the key and relevant user names as values and return the relevant user names. How can I do that?
You can easily achieve that using the Array.reduce prototype function:
var allUsers = [
{ groupId: 1, userName: 'mario' },
{ groupId: 1, userName: 'luigi' },
{ groupId: 2, userName: 'peach' },
{ groupId: 2, userName: 'koopa' }
]
var getNames = function getNames(groupId, users) {
return users.reduce(function(res, u) {
if (u.groupId === groupId) {
res = res + (res.length > 0 ? ', ' : '') + u.userName
}
return res
}, '')
}
console.log(getNames(1, allUsers))
How can I include hasOne associated model data in the JSON POST?
Structured data is required by my web API in the form of:
{
id: 1234,
name: 'Aaron Smith',
address: {
address1: '1925 Isaac Newton Sq',
address2: 'Suite 300',
city: 'Reston',
state: 'VA',
zip: 20190
}
}
#nonino
I think I know how to do it but I am also having a similar problem. I can't actually get my associations to give me the associated data. Anyway from what I have scrounged on the internet make a custom writer like this or just in the default writers getRecordData: function(record,operation)
Here is my custom writer
Ext.define('Wakanda.writer', {
extend: 'Ext.data.writer.Json',
// alternateClassName: 'SimplyFundraising.data.WakandaWriter',
alias: 'writer.wakanda',
writeAllFields: false,
getRecordData: function(record,operation) {
debugger;
Ext.apply(record.data,record.getAssociatedData());
debugger;
var isPhantom = record.phantom === true,
writeAll = this.writeAllFields || isPhantom,
nameProperty = this.nameProperty,
fields = record.fields,
data = {},
changes,
name,
field,
key;
if (writeAll) {
// console.log("getRecordData1", this, arguments);
fields.each(function(field){
if (field.persist) {
debugger;
name = field[nameProperty] || field.name;
data[name] = record.get(field.name);
} else {
}
});
} else {
changes = record.getChanges();
debugger;
// console.log("getRecordData2", this, arguments, changes);
for (key in changes) {
if (changes.hasOwnProperty(key)) {
field = fields.get(key);
name = field[nameProperty] || field.name;
data[name] = changes[key];
}
}
if (!isPhantom) {
debugger;
data[record.idProperty] = record.getId();
if(operation.action !== 'destroy'){
data[record.stampProperty] = record.get(record.stampProperty);
}
}
}
return {'__ENTITIES': [data]};
}
});
The key I think is in the getRecordData where I have a statement Ext.apply(record.data,record.getAssociatedData()); If record.getAssociatedData does indeed return your data then the Ext.apply statement will merge your current record.data with your record.getAssociatedData into 1 json file. At least this is what I hope happens. Can't test until I get my associations setup correctly.
Hope this helps,
Dan
getRecordData: function(record,operation) {
debugger;
Ext.apply(record.data,record.getAssociatedData());
debugger;