Get the previous message to a discord channel - discord

Given a discord message id and a channel id, is there a way of finding the previous message to the same discord channel?
Message ids are intigers, and my impression is that the are monotonously increasing. So if there was a way of looking up all the message ids that a channel has recieved, i think it would be as simple as finding the highest that is less than the id you are interested in.

Im not sure if u meant to find the content of the message itself or the previous message before it but you can read more on txt_channel.history here:
What history does is enabling you to see the message history of a text channel.
So if you want to find the contents of a specific message using it's id you can do:
(of course you need to fetch the text channel, you can look at here)
async for msg in txt_ch.history(limit=[how many messages back you want the loop to go]):
if msg.id == ID_OF_MSG: # you found the message
print("the message with the id has been found")
now this code ^^ is pointing you to the message you gave with the current id but if you want to get the message previous to it you just add this:
async for msg in txt_ch.history(limit=[how many messages back you want the loop to go]):
found_message = False
if msg.id == ID_OF_MSG: # you found the message
found_message =True
elif found_message:
found_message = False
print("previous message")
Of course you can change the last line on the print to something like:
print(msg.content)
to see it's content, or you can send it back to the channel, it is up to you.
side not:
I tried to test it and it doesn't seem that the ids of the messages are one after another so you can't do id-1 to get the previous message id.

Related

Discord Bot crashes trying to edit his own messages from another instance

So I have a order system that sends embeds incl all important information into a channel.
Whenever an order is started that embed then goes into "In progress" status by changing its buttons and adding a "Complete" button which then marks the order as completed.
In total the message is sent and edited twice.
Now here's the issue: If the bot ever crashes, due to a server reboot or similar, editing the messages it sent prior to the crash will yield the error:
(node:6672) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot edit a message authored by another user
Now I can't just go and check if author.id === client.id because that'll obviously just return true. So how can I fix that issue? As of now I decided to just add a try catch but I'd rather just add an if clause at the top of the event.
DiscordAPIError: Cannot edit a message authored by another user means you are trying to edit another user message
Here's the code for editing bot message:
const msg = await message.channel.send("Will be edit..")
setTimeout(function() {
msg.edit("Edited")
}, 1000) // will edit the message after 1000 ms (1 second)

Discord.js V13 -- Store persisting hidden data on the message object

I have coded a bot to send a message response to a given command, !a. I want to store additional data on the message object, so that if the user reacts to that message the bot can read the hidden data property and know the original message resulted from !a.
Ideas I had:
Create a custom property on the message object: Message.Custom_Prop
Hijack an unused property: Maybe Message.webhookId?
Store hidden text in the form of an embed or message content.
I haven't been able to get any of these to work though.
The best way that I can think of is to store an array of message IDs that were triggered by !a. Something like this:
// At the start of your script
const commandResponses = [];
// Logic for sending the command response
message.channel.send("response here").then(msg => commandResponses.push(msg.id));
// Checking whether the message was a response
if (commandResponses.includes(reaction.message.id)) {
// It's a response so do stuff here
}
(Not tested so it's possible that this won't work)

Discord JS v12: How do you get a message's content by it's ID?

I'm relatively new to discord.js, and I've started building a bot project that allows a user to create a message via command, have that message stored in a hidden channel on my private server, and then said message can be extracted through the message ID.
I have the write working and it returns the message ID of the message sent in the hidden channel, but I'm completely stumped on the get command. I've tried searching around online but every method I tried would return errors like "Cannot read property 'fetch' of undefined" or "'channel' is not defined". Here are some examples of what I tried, any help would be appreciated. Note that my args is already accurate, and "args[0]" is the first argument after the command. "COMMAND_CHANNEL" is the channel where the command is being executed while "MESSAGE_DATABASE" is the channel where the targeted message is stored.
let msgValue = channel.messages.cache.get(args[0])
client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content)
let msgValue = msg.channel.message.fetch(args[0])
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
I even tried using node-fetch to call the discord API itself
const api = require("node-fetch")
let msgValue = api(`https://discordapp.com/api/v8/channels/${MESSAGE_DATABASE}/messages/${args[0]}`)
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
Am I missing something or am I making some sort of mistake?
Edit: Thanks for the help! I finished my bot, it's just a little experimental bot that allows you to create secret messages that can only be viewed through their ID upon executing the command :get_secret_message <message_id>. I posted it on top.gg but it hasn't been approved yet, so in the meantime if anyone wants to mess around with it here is the link: https://discord.com/api/oauth2/authorize?client_id=800368784484466698&permissions=76800&scope=bot
List of commands:
:write_secret_message - Write a secret message, upon execution the bot will DM you the message ID.
:get_secret_message <message_id> - Get a secret message by its ID, upon execution the bot will DM you the message content.
:invite - Get the bot invite link.
NOTE: Your DMs must be turned on or the bot won't be able to DM any of the info.
My test message ID: 800372849155637290
fetch returns the result as promise so you need to use the then to access that value instead of assigning it to a variable (msgValue). Also you made a typo (channel.message -> channel.messages).
I would recommend using something like this:
msg.channel.messages
.fetch(args[0])
.then(message => {
client.channels
.fetch(COMMAND_CHANNEL)
.then(channel => channel.send(message.content))
.catch(console.error)
})
.catch(console.error)
I think you were quite close with the second attempt you posted, but you made one typo and the way you store the fetched message is off.
The typo is you wrote msg.channel.message.fetch(args[0]) but it should be msg.channel.messages.fetch(args[0]) (the typo being the missing s after message). See the messages property of a TextChannel.
Secondly, but this is only a guess really as I can't be sure since you didn't provide much of your code, when you try to fetch the message, you are doing so from the wrong channel. You are trying to fetch the message with a given ID from in the channel the command was executed from (the msg.channel). Unless this command was executed from the "MESSAGE_DATABASE" channel, you would need to fetch the message by ID from the "MESSAGE_DATABASE" channel instead of the msg.channel.
Thirdly, if you fetch a message, the response from the Promise can be used in the .then method. You tried to assign the response to a variable msgValue with let msgValue = msg.channel.message.fetch(args[0]) but that won't do what you'll expect it to do. This will actual assign the entire Promise to the variable. What I think you want to do is just use the respone from the Promise directly in the .then method.
So taking all that, please look at the snippet of code below, with inspiration taken from the MessageManager .fetch examples. Give it a try and see if it works.
// We no longer need to store the value of the fetch in a variable since that won't work as you expect it would.
// Also we're now fetching the message from the MESSAGE_DATABASE channel.
client.channels.cache.get(MESSAGE_DATABASE).fetch(args[0])
// The fetched message will be given as a parameter to the .then method.
.then(fetchedMessage => client.channels.cache.get(COMMAND_CHANNEL).send(fetchedMessage.content))
.catch(console.error);

delete bot message after 2 user messages prior

javascript is still vague to my knowledge, and I cannot be precise on the sensibility in the following code I have manufactured. I am programming a discord bot that categorizes messages into a variety of channels, and the question has approached me to how I can program the bot by deleting follow up bot messages after 2 user messages were sent subsequently after the bot message.
if (bot.on(client, user.msg = '2'));{
msg.channel('message' = msg.delete)
}
Help is to be requested and I hope my query makes sense in the context I am implying, Regards, Coder
P.S: How do I change the bot messages text color as well?
No offense, but your code was completely faulty, so I just made some new code.
bot.on('message', aysnc message => {
var messagenumber = 0; //Makes variable for the number of messages sent
if(message.member.user.username === bot.user.username) return; //If the person who posts a message is the bot, it doesn't the code below.
if(messagenumber = 1) return bulkDelete(100), messagenumber = 0 //Checks if the variable is 1, and if it is, this means it's the second time a message posted, so it deletes messages (Limit is 100) then resets variable.
messagenumber = 1; //Makes variable 1 (This is to make it know it is the the second time a message is posted for the next time).
});
I didn't test this code, so it may not work properly, but if it does work I hope it helps you with your bot.
For the P.S (Changing text color): You can use these (Replace "NoKeyWordsHere" with your message). I don't recommend this, cause it'd take a long time to add it to every message sent. (You can use these on your messages too)

Obtain User ID from a DM message Sent To Bot

I want to find the user id of the person who DMs the bot. Is there any way to do it? I am using Discord.js
I tried by storing member author and member Id but it didn't work. But when I store channel, it store it as authors tag. But the id for that channel does not matches with the id of the user who DM the bot. I am trying to make support mail bot. But it requires the user id so that I can continue the thread by DMing the user. But it's not possible until I get the user id or server member object. And I can't store that DMchannel in my database because i use json for storing datas.
Due to my low reputation, I can't comment, sorry if this does not answer your question.
You can get the ID of the person who DM'd your bot by message.author.id (keep in mind, message will need to change to whatever variable your message is stored in).
You can also get the channel ID with message.channel.id.
The channel ID is not the same as the user's ID (they are two different things), which I assumed you misunderstood from id for that channel does not matchs with the id of the user who DM the bot.
Try this:
const client = new discord.Client();
client.login('token here');
/* On message event since you want to
* recieve DM and get ID from user who sent DM to your bot.
*/
client.on("message", (msg) => {
// checks if the message's channel type is 'DM'.
if(msg.channel.type === "dm") {
// you can do anything you want here. In my case I put console.log() function.
// since you wanted user ID, you can use msg.author.id property here.
console.log(`Recieved DM from ${msg.author.tag}, DM content is`, msg.content);
}
});
Please remember, author/member ID and dm message channel ID is completely separate thing.
Also storing member related data in JSON or an SQL is not a really good idea here. I suggest you only doing that for custom data you've generated, or that would be wasting a lot of memory.

Resources