Copying and moving message in another channel - discord.js

My suggestion Script worked totally fine for the last couple of months, but it stopped working a few days ago. I noticed that my .send function was underlined, and it said this:
Property 'send' does not exist on type 'GuildChannel | ThreadChannel'.
Property 'send' does not exist on type 'GuildChannel'
I'm btw. not sure if that's the problem with the script or if they changed anything I didn't notice, and I'm getting no errors. The Script basically just don't work.
My suggestion script:
case "suggestion":
var str = message.content.slice(" .suggestion".length);
const suggestionembed = new Discord.MessageEmbed()
.setThumbnail('png')
.setTitle("Suggestion")
.setColor('#151515')
.addFields(
{ name: "Person, that suggested somenthing:", value: `<#!${message.author.id}>` },
{ name: 'Suggestion:', value: `${str}` },
{ name: 'Channel:', value: `${message.channel}` },
)
.setTimestamp()
await message.guild.channels.cache.find(c => c.name === 'suggestion')
.send({ embeds: [suggestionembed] })
.then(embedMessage => {
embedMessage.react("✅")
embedMessage.react("❌")
});
message.delete();
break;

Just ignore that if you are sure that it's a text channel. That is only there because it can be a VoiceChannel. You won't have autocomplete in Visual Studio Code but it will still work as intended. If you are using TypeScript, you could use as to tell TypeScript it's a TextChannel

Related

Discord.JS getting "Expected a string primitive Received: | undefined" when registering command

i was trying to create a new slash command, i use a folder called commands and i require every file in that folder to register it
this is the command file:
const { SlashCommandBuilder, EmbedBuilder, Client, CommandInteraction, CommandInteractionOptionResolver } = require("discord.js");
module.exports = {
name: "ping",
data: new SlashCommandBuilder()
.setName("ping")
async do(client, interaction, options) {
const check = await interaction.reply({content: "Pinging...", fetchReply: true});
const latency = check.createdTimestamp - interaction.createdTimestamp;
const pingEmbed = new EmbedBuilder()
.setTitle(":ping_pong: Pong!")
.setColor([40,40,38,255])
.setTimestamp()
.addFields(
{name: "Bot Latency", value: `${latency}ms`, inline: true},
{name: "API Latency", value: `${client.ws.ping}ms`, inline: true});
await interaction.editReply({content: "", embeds: [pingEmbed]});
}
};
when i try to load it i keep getting an Expected a string primitive error
i was expecting it to register the command successfully, but instead it keeps giving me an error, i tried everything on the guide what it said
The issue is very simple and straightforward and if you would have reviewed the discord.js documentation, you would have known that slash commands need to have a description to register.
Therefore, add a .setDescription() below your .setName method and give it a description before trying again.

.setname is not a function in discord.js

I have finished completing the code for my bot from a tutorial on YouTube: https://www.youtube.com/watch?v=fN29HIaoHLU
Here is the entire code on replt.it: https://replit.com/#TylerLanier/Comusity-Bot#slash/info.js:6:4
And I am getting this error: TypeError: (intermediate value).setname is not a function at "..."
Here is the code at slash/info.js:
module.exports = {
data: new SlashCommandBuilder()
.setname("info")
.setDescription("Displays info about the currently playing song"),
run: async ({client, interaction}) => {
const queue = client.player.getQueue(interaction.guildId)
if(!queue)
return await interaction.editReply("There are no songs in the queue")
let bar = queue.createProgressBar({
queue: false,
length: 19
})
const song = queue.current
await interaction.editReply({
embeds: [
new MessageEmbed()
.setThumbnail(song.thumbnail)
.setDescription(`Currently Playing [${song.title}](${song.url})\n\n` + bar)
],
})
},
}
The reason behind the error is a capitalisation mistake when you use .setname(). It needs to be .setName() with a capital N. This is why you need to go through your code just to check the spelling of each function and variable you call. You will also have to change this incorrect spelling in every command except the play command as in each file, you are using .setname()

Embed message discord.js

Ive seen many discord embed codes like this:
(This is an old question and im new to coding so...)
const { MessageEmbed } = require('discord.js');
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor('Some name', 'https://i.imgur.com/AfFp7pu.png', 'https://discord.js.org')
.setDescription('Some description here')
.setThumbnail('https://i.imgur.com/AfFp7pu.png')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Inline field title', value: 'Some value here', inline: true },
{ name: 'Inline field title', value: 'Some value here', inline: true },
)
.addField('Inline field title', 'Some value here', true)
.setImage('https://i.imgur.com/AfFp7pu.png')
.setTimestamp()
.setFooter('Some footer text here', 'https://i.imgur.com/AfFp7pu.png');
channel.send({ embeds: [exampleEmbed] });
So, what i dont understand is what is the trigger? Like you're supposed to type .ping for pong right? so what do i type to get my bot type this embed?
The way you're sending your embed is(afaik) specific to version 13 of discord.js and you most likely haven't updated discord.js yet:
channel.send({ embeds: [exampleEmbed] });
the version I am currently using is 12.5.3 .
Check your version of discord.js in package.json and if the version is not 13 or above, update or if you want to stick with version 12.5.3 try some of the methods below:
channel.send( exampleEmbed );
Or like this:
channel.send({ embed: exampleEmbed });
Sending the embed like this: "{ embeds: [exampleEmbed] }" makes discord think you are sending an empty message and therefore it doesn't send anything.
This code is meant to be inside an event handler (such as on.message). If that code is already inside an event handler (except for this const { MessageEmbed } = require('discord.js');, it should go at the top), and if it is still not sending, then you should change this line:
channel.send({ embeds: [exampleEmbed] });
to
message.channel.send(exampleEmbed)
There is no trigger in the code sample you provided. You need to have a listener for the message event or interactionCreate event to listen to traditional message-based commands and slash commands. You can pass in handlers into these listeners and respond to command usages.
Since it looks like you're reading the discord.js guide, I would suggest reading from the start, where you would be introduced to how to handle messages first.
To send it, just use a message event. Like this:
const { MessageEmbed, Client } = require('discord.js');
const client = new Client();
client.on('message', msg => {
const { channel, content } = msg;
if(msg.content === 'someCommand') {
const exampleEmbed = new MessageEmbed()
//setProperties...
channel.send({ embeds: [exampleEmbed] });
}
})
client.login('[TOKEN_HERE'])
What's happening here is that the client is receiving a Message object when someone messages (msg). We then use the channel and content properties to evaluate the command, and send the embed if the command is correct. I took out the property settings to save space. You can add them back.

Error: MessageEmbed field values may not be empty

So I have a section of code which is designed to send an embed to a logging channel with the old and new message whenever a message is updated. However, whenever I test the code, the embed is sent successfully, but an error RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty occurs, and the bot crashes. I can find no reason why this error would occur, because all the fields return the values I specified.
The only thing I noticed that was strange is when I added the code to the bot, all embeds started to encounter the same error, but when I commented out the code, the embeds returned to normal.
Does anyone know why this error would occur? If so, how would I fix it?
This is the code:
var channel = newMessage.guild.channels.cache.find(ch => ch.name === 'bot-log');
var log = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL())
.setDescription(`:pencil: **[Message](${newMessage.url}) by ${newMessage.author} was edited in <#${oldMessage.channel.id}>**`)
.setColor(0x686afd)
.addFields(
{ name: `Old message`, value: oldMessage.content},
{ name: `New message`, value: newMessage.content},
)
.setTimestamp()
.setFooter(`Message ID: ${newMessage.id}`);
return channel.send(log);
});
Its happens because message content can be empty, like if user attach some files without text. You can check newMessage.content.length and oldMessage.content.length, and change it to what ever you want.
Like:
newMessage.content = newMessage.content.length > 0 ? newMessage.content : 'empty message'
oldMessage.content = oldMessage.content.length > 0 ? oldMessage.content : 'empty message'
I Think This Code Is The Right One :v
var channel = message.channel;
var log = new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL())
.setDescription(`:pencil: **[Message](${message.url}) by ${message.author.tag} was edited in <#${message.channel.id}>**`)
.setColor(0x686afd)
.addFields(
{ name: `Old message`, value: message.content},
{ name: `New message`, value: message.content},
)
.setTimestamp()
.setFooter(`Message ID: ${message.id}`);
return channel.send(log);

react-native-gifted-chat showing same message multiple time

I'm using react-native-gifted-chat in my react-native app. As I shown in this image, there is same message displayed multiple time and message: Yes getting new msg 's place is also varied from it's actual position.
My issue is same as this. Can anyone please help me to solve this.
Thank you in advance.
I got a solution of my question. #Ron you are right but in my case the issue is different. I solved it by change my format of parameters. It took different format and I passed different so they conflicted each other. Here is the solution it may useful to others.
parse = snapshot => {
const { timestamp: numberStamp, text } = snapshot.val();
const { key: _id } = snapshot;
const createdAt = moment(snapshot.val().createdAt, "DD/MM/YYYY hh:mm:ss");
const user = { };
var temp_data = snapshot.val()
if(snapshot.val().name == this.state.temp_logged_name) {
user._id = 1;
user.name = temp_data.name;
user.avatar = temp_data.avatar;
}
const message = {
_id,
createdAt,
text,
user,
};
return message;
};
I had encountered this issue as well. I had set up react-native-gifted-chat on my mobile app. And at the other end I had set up a simple HTML page with a script to initialise the Websocket connection and send messages on the onsend event. What I had realised later that while the unique id was getting generated at the app end (because the id was being generated by the library itself), nothing of such sort existed at the other end.
Basically, this weird behaviour crops up when a unique id _id is missing for a message. Each message must have at least the following properties while executing GiftedChat.append(previousMessages, messages).
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2
}
}
There could be two reasons behind it,
1) Each message should be passed a unique id, so just use uuidv4 npm package and append it to _id prop of the object.
Example:
messages: GiftedChat.append(previousState.messages, {
_id: uuidv4(), // or use Math.round(Math.random() * 1000000)
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: "React Native",
avatar: "https://placeimg.com/140/140/any"
},
image: attachment
})
2) Second possibility could be on the gateway you are using to initiate the chat between users. So, some gateways have known issues to repeat the message multiple times. You could to string comparison each time a new message is received and pushed to the chat screen, however it is not advised to do this.
I figured this out by simply applying the filter to the incoming message in useLayout Effect:
useLayoutEffect(() => {
db.collection('Chats').doc(docID).collection('messages').orderBy("createdAt", "desc").onSnapshot(snapshot => {
setMessages(
prev =>
prev
.filter((ftr,index,self) => ftr?.user?._id !== loginUser?.id) //login user id is the current user's id you can do the same for recieved messages
.concat
(snapshot.docs.map(doc => doc.data({
_id: doc?.id,
user: doc.data().user,
text: doc.data().text,
createdAt:new Date(doc.data().createdAt),
})
))
)
})
},[])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Resources