My logging command needs a channel to send messages, I do this with a >logging #channel-here command, it stores on better-sqlite3, my issue is I am not sure on how to read the contents and convert it to a channel.
I have been working on this for several days, and I have tried several different things, this was my latest attempt
const id = sql.prepare(`SELECT channel FROM logging WHERE guildid = ${message.guild.id};`).get();
const logs = client.channels.get(id);
if (!logs) return;
logs.send(`A message was deleted`);
const logs = needs to = the channel id that you see in the channel record if the guildid record matches the one that the message was deleted in.
Instead of saving the channels mention you should save the channels id.
<#channel-id> is used to mention a channel, but discord.js <guild>.channels.get(), takes only the ID.
So you should only store the Channel Id in the Database, in your code for >logging #channel-here just use const mentionedchannel = message.mentions.channels.first();
and then into your DB just write the mentionedchannel.id, then your .get() should work!
Related
I wanna fetch messages in a dm, like i can in a channel
So i have tried
<user>.messages.fetch(id)
But no luck
So what can i do to fetch messages in a dm
Full code
let id = args[0]
let react = args.slice(1).join(' ')
let fetched = message.author.messages.fetch(id)
fetched.react(react)
I tried fetching a channel from the id of the author
But also no luck
You can use message.author.dmChannel to get a DMChannel object of the particular user's DMs. Then, you can use .messages.fetch() to fetch all the messages in the channel, .messages.cache.get() to fetch a message based on its ID or .messages.cache.find() to fetch a message based on any property such as its content. An example:
const dmChannel = message.author.dmChannel
const messages = dmChannel.messages.fetch() // This gives you a list of all the message in the channel
const message = dmChannel.messages.cache.get('message-id') // This fetches the message with the particular message id given
const message = dmChannel.messages.cache.find('message-content') // This fetches the message with the particular message content given
I'm making a ticketing system with buttons. I trying to if user opened a ticket, user can't open a new ticket. Im tried some code:
//ticket channel is created with **"help: " + interaction.user.username** name
if (interaction.guild.channels.fetch('channel name'))
//working with only id
if (interaction.guild.channels.cache.get(c=>c.name==='channel name'))
//reacted nothing
The discord.js channels cache is a Discord.Collection of values, meaning that it is a JS map with some extra quality of life methods added by Discord.js. Discord Collections are keyed using the snowflake id with the value being whatever object is being stored with that id (in this case the channel you want). This means that the method fetch on the collection of channels can always only be passed an ID as stated here in the docs. This would also mean that the Map.get() method you try to use in the second attempt will not return anything as the channel is not keyed by its name, its keyed by a snowflake id.
You can use a piece of code like this one I used in a discord moderation bot to find and return a channel by name if it exists in the cache.
/**
* Get the log channel for the provided guild.
* #param {Discord.Guild} guild The guild to get the log channel for.
*/
#getLogChannel = (guild) => {
const guildLogChannel = guild.channels.cache
.find(channel => channel.name === 'guild-logs');
if (!guildLogChannel) return false;
return guildLogChannel;
}
If the channel has not yet been cached you have no other option than to pass that channel into the interaction as an option, fetch the channel by its snowflake id, or fetch all channels for all guilds the bot is in inside your client.on('ready', () => {}) handler. The last option is what I chose to do for the bot that the above code snippet is taken from.
Using Discord.js in an Express/Node.js app, I'm trying to build a bot that grabs external data periodically and updates Discord with an embed msg containing some elements of that data. I'm trying to add a feature that will check if that data was deleted from the external source(no longer existing upon the next grab), then delete the specific msg in Discord that contains that data that was sent.
Some of the msgs posted in Discord may have duplicate data items, so I want to delete by specific msg ID, but it seems that msg ID is assigned when posted to Discord.
Is there a way to programmatically grab or return this msg ID when sending from Discord.js, rather than manually copy/pasting the msg ID from the Discord GUI? In other words, I need my bot to know which message to delete if it sees that msg's source data is no longer being grabbed.
// FOR-LOOP TO POST DATA TO DISCORD
// see if those IDs are found in persistent array
for (var i = 0; i < newIDs.length; i++) {
if (currentIDs.indexOf(newIDs[i]) == -1) {
currentIDs.push(newIDs[i]); // add to persistent array
TD.getTicket(33, newIDs[i]) // get ticket object
.then(ticket => { postDiscord(ticket); }) // post to DISCORD!
}
}
// if an ID in the persistent array is not in temp array,
// delete from persistent array & existing DISCORD msg.
// message.delete() - need message ID to get msg object...
// var msg = channel.fetchMessage(messageID) ?
Let me refer you to:
https://discord.js.org/#/docs/main/stable/class/Message
Assuming you are using async/await, you would have something like:
async () => {
let message = await channel.send(some message);
//now you can grab the ID from it like
console.log(message.id)
}
If you are going to use .then for promises, it is the same idea:
channel.send(some message)
.then(message => {
console.log(message.id)
});
ID is a property of messages, and you will only get the ID after you receive a response from the Discord API. This means you have to handle them asynchronously.
I already have a variable containing a specific channel, but how can I obtain the last message sent to the channel? I want to make my bot only perform an action if the last message to the channel wasn't by it.
If you already have the specific channel stored in a variable, it's quite easy. You can call the MessageManager#fetch() method on that specific channel and get the latest message.
Example:
let channel // <-- your pre-filled channel variable
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) {
// The author of the last message wasn't a bot
}
})
.catch(console.error);
However if you don't have the complete channel object saved in a variable but only the channel ID, you'll need to fetch the correct channel first by doing:
let channel = bot.channels.get("ID of the channel here");
Recently I believe they've changed from channel.fetchMessages() to channel.messages.fetch()
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
// do what you need with lastMessage below
})
.catch(console.error);
There is a property containing the object of the last writte message. So the most short version of getting last Message is:
let lm = channel.lastMessage;
Of course #Tyler 's version is still working. But my IDE says that he don't know first(). So may this will be deprecated some day?!? I don't know.
Anyway, in both ways you retrieve an object of the message. If you want to have e.g. the text you can do this
let msgText = lm.content; // channel.lastMessage.content works as well
I'm trying to do some analytics on average response time from some of our users on Twilio Chat.
I'm iterating through my channels, and I'm able to pull the info about messages, so I can compare times a message went un-responded to. However, I can't determine which users were in the channel at that time.
Is there anything on the channel that would give me historic member data? Who was in the channel? The channel.messages().list() method is only giving me the text of the messages sent to the channel and who it was by, but the user who may have been in a channel to respond changes throughout a channel's life time.
This is on the backend using the node.js SDK. note: This isn't a complete implementation for what I'm trying to do, but taking it in steps to get access to the information I'd need to do this. Once I have these messages and know which users are supposed to be in a channel at a given time, I can do the analytics to see how long it took for the users I am looking for to respond.
var fs = require('fs');
const Twilio = require('twilio');
const client = new Twilio(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH);
const service = client.chat.services(env.TWILIO_IPM_SERVICE_SID);
async function getChatMessages() {
const fileName = 'fileName.csv';
const getLine = message => {
return `${message.channelSid},${message.sid},${message.dateCreated},${message.from},${message.type},${message.body}\n`;
}
const writeToFile = message => { fs.appendFileSync(fileName, getLine(message)); };
const headerLine = `channelSid,messageSid,dateCreated,author,type,body`;
fs.writeFileSync(fileName, headerLine);
await service.channels.each(
async (channel, done) => {
i++;
let channelSid = channel.sid;
if( channel.messagesCount == 0 ) return;
try {
await channel.messages().list({limit:1000, order:"asc"}).then(
messages => {
messages.forEach( writeToFile );
}
);
} catch(e) {
console.log(`There was an error getting messages for ${channelSid}: ${e.toString()}`);
}
if( i >= max ) done();
}
);
}
I'm beginning to be resigned to the fact that maybe this would only have been possible to track had I set up the proper event listeners / webhooks to begin with. If that's the case, I'd like to know so I can get that set up. But, if there's any endpoint I can reach out to and see who was joining / leaving a channel, that would be ideal for now.
The answer is that unfortunately you can not get this data retroactively. Twilio offers a webhooks API for chat which you can use to track this data yourself as it happens, but if you don't capture the events, you do not get access to them again.