How to use an EmbedMessage From a Different File? - javascript

I'm having trouble with an embedmessage. I provided my code below of my index.js in which I'm trying to use a function made in "globalspeakfunction.js".
Don't worry about the variables I'm sending they look extra in this but I only provided the relevant code to hopefully reduce confusion.
I'm building up my EmbedMessage in GlobalSpeakFunction.js and then sending it in the channel of the message provided in "index.js".
However my console gives back "cannot send empty message" and when I do a console.log of the EmbedMessage it returns the embed perfectly?
I tried adding a string "test" after my embedmessage in the send() function and then it returned
[object Object]test
I have no idea what's going on here. Am I not able to buildup an EmbedMessage in a different file and then send it back to my bot? Or is there something I'm just overlooking?
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
const speak = require('../GlobalSpeakFunction.js');
client.on('message', message => {
if (message.content.toUpperCase().includes(`test`)){
speak("778978295059972106", message, "test", "Default");
}
}
GlobalSpeakFunction.js
const Discord = require("discord.js")
module.exports = function speak(charID, data, message, emotion){
var EmbedMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('title')
.setURL('https://discord.js.org/')
.setDescription(message)
.setThumbnail('https://drive.google.com/file/d/17J90PzTLBR96wTwk_Wl3U06-or6ZjPW2/view')
.setTimestamp();
message.channel.send(EmbedMessage);
}

I'm not sure where you experienced the 'Cannot send an empty message' error, I can't reproduce it locally. However, there are a few issues here:
Firstly, you're using toUpperCase() on message.content, and later checking whether it includes (lowercase) "test". Thus, this if statement will never execute.
Secondly, the order of arguments in the speak() function is charID, data, message, emotion, but you're passing them as "778978295059972106", message, "test", "Default" (notice how data and message are swapped when calling the function).
Thirdly, the setThumbnail() function expects a direct link to an image (one that ends with a file extension, like .png or .jpg). You're providing a Google Drive link, which is additionally set to private, which makes it unreadable for anyone but you. I'd recommend uploading it to an image host and getting the direct link from there.
Also, [object Object] is just a string representation of an object. JavaScript tries to convert your MessageEmbed (which is an object) to a string (because you're trying to append 'test' to it).

Related

discord.js Property 'messages' does not exist on type 'TextChannel'

Today I switched from JS to TS (mainly because of its type annotation) and when trying to save a channel to a variable, I got the following error: Property 'messages' does not exist on type 'TextChannel' (got the error when trying to access the messages property somewhere in the code). The discord.js docs show that messages is a valid property of TextChannel, so what's going on here?
The code I'm using to get the channel is channel = guild.channels.cache.get(id) and I added as TextChannel to the end (and declaring the variable likes this: let channel: TextChannel). I also tried BaseGuildTextChannel but got the same results.
I also tried logging the type of the channel variable with console.log(typeof channel) but it just returned object
reproducible example as requested
import {Client, TextChannel} from 'discord.js'
const client = new Client({intents: []})
client.once("ready",()=>{
client.channels.fetch("id of a text channel").then((chan:TextChannel)=>{
if (!chan.isTextBased()) return //TS2339
chan.messages.fetch().then(()=>{ //TS2339
console.log("fetched messages")
})
})
})
client.login("token")
Using resolve will keep your code cleaner and allow you to visualise your code better than chaining .then statements.
Doing this and enabling Message Intents should fix your code.
const guild = client.guilds.resolve('ID');
const channel = guild.channels.resolve('ID');
if(!channel.isTextBased()) return;
const messages = await channel.messages.fetch();

bot.sendMessage is not a function

I'm currently making a discord bot that will send out messages. Unfortunately the messages are receiving errors such as bot.sendMessage is not a function. I'm fairly new to coding so this one has me stumped. Even any google searches have not been able to help me to the point where I can understand it.
I've tried bot.send as maybe .sendMessage is now outdated I had read somewhere I believe.
var exampleSocket = new WebSocket(dataUrl);
bot.send({to: flowChannel,message: 'Websocket connected'});
exampleSocket.onopen = function (event) {
logger.info('got to here');
The output should post in my channel that the websocket connected.
bot.send({to: flowChannel,message: 'Websocket connected'});
Client.sendMessage() was removed in Discord.js 9.0 back in 2016.
I've tried bot.send as maybe .sendMessage is now outdated I had read somewhere I believe.
TextBasedChannel.sendMessage(), TextBasedChannel.sendCode(), TextBasedChannel.sendEmbed(), TextBasedChannel.sendFile(), and TextBasedChannel.sendFiles() are all deprecated.
The equivalent of your code today is as follows...
flowChannel.send('Websocket connected')
.catch(console.error); // Catch the rejected promise in the event of an error.
Discord.js Docs (Stable)
#sendMessage is deprecated.
You need to pass 'message' through and use message.channel.send()
Channel can also be a DM.
TextChannel.sendMessage (and DMchannel.sendMessage) along with all type of sendXX functions, is deprecated.
The function TextBasedChannel.send take as argument a MessageOptions value (or directly an Attachment or RichEmbed) if you want to pass anything other than just text.
To access the send function, you need a TextChannel or a DMchannel which you can get:
In the message that triggered your function like this: client.on('messages', (msg) => {msg.channel.send('Hello')})
If you have a Guild instance: guild.channels.get('channel id') or guild.channels.find(d => d.name === '<channel name>)') (note: you'll have to check if the channel is a TextChannel and not a voice one)
with the Client.channels method, which list all of the Channels that the client is currently handling, mapped by their IDs - as long as sharding isn't being used, this will be every channel in every guild, and all DM channels

How to fix this 'Attachment is not a constructor' error with my bot?

When I made my bot for Discord and tried to attach an image, I can't because of this error
It's a bot for Discord that runs on Discord.js
I tried const Attachment on the beginning, but that didn't work, removed new and const in the code didn't work too
case 'about':
message.channel.send('I am Damabot, developed by Damadion!')
const attachment = new Attachment('./DidYouThinkIAmTheRealFace.png')
message.channel.send('I am Damabot, developed by Damadion!' + attachment)
console.log('Bot successfully replied')
break;
I expected it to send an attachment, but it didn't and sent this error
You can do it like this:
message.channel.send('I am Damabot, developed by Damadion!', { files: ['./DidYouThinkIAmTheRealFace.png'] });
It adds the file directly into the message, so you don't have to create Attachment. I use this my BOT, and it works just fine.
Attachment is a class within Discord.js. Unless you're using a destructuring assignment for your require statement (const { Attachment } = require('discord.js')), Node.js is trying to construct an Attachment object based on a class within your code. When it finds that there is none, it throws your error.
If you want to stick to constructing Attachment objects, you can use:
const attachment = new Discord.Attachment('./path/to/file.png', 'name'); // name is optional
message.channel.send('Hey there', attachment)
.catch(console.error);
Otherwise, you can use the files property of a message like so:
message.channel.send('Hey there', {
files: ['./path/to/file.png']
})
.catch(console.error);
The latter allows you to also send an embed (and maybe use the attachment in your embed).
Discord.js Docs
For me the following code worked:
const attachment = new Discord.MessageAttachment("url");
channel.send(attachment);
Discord.Attachment was replaced with Discord.MessageAttachement
I had the same problem. I ran npm install to update my packages and to check if my discord version was outdated and therefore causing any issues.
After that, I decided to go through the docs and found this snippet here:
const attachment=new Discord.MessageAttachment("enter the URL u wanna enter here")
const generalChannel=client.channels.cache.get("enter ur channel id here")
$generalChannel.send(attachment);
At least, it has worked for me. Please let me know if it works for you as well.

Discord make channel using bot

I'm making a discord bot, and I'm trying to make use of the createChannel function shown here in the documentation. For some reason, I am getting the following error:
TypeError: bot.createChannel is not a function.
My code is within a function which I pass a message to, and I have been able to create roles and add users to roles within the same function. It's just the createChannel function that's not working. Below is the relevant portions of the code.
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createRole(data);
var newrole = server.roles.find("name", name);
message.author.addrole(newrole);
/* The above 3 lines all work perfectly */
bot.createChannel(server,name);
}
I have also tried bot.addChannel, and bot.ChannelCreate, since ChannelCreate.js is the name of the file which contains the code for this command. Also, I have attempted specifying channel type and assigning a callback function as well, but the main issue is the TypeError saying that this isn't a function at all. Any idea what I'm doing wrong?
Additionally, I plan to use ServerChannel.update() at some point in the future, so any advice on getting that to work once the previous problem is resolved would be greatly appreciated.
Alright, after a few days of trying things and going through the docs, I have discovered the solution. I am using a more recent version of Discord than the docs I was reading were written for. In the newer version, channels are created with a method in the server, not a client method. so, the code should be:
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createChannel(name, "text");
}
The "text" value is the type of channel you are making. Can be text or voice.
I'll post a link to the most recent documentation for anyone else who encounters this problem here.
The answer should update documentation link to the GuildChannelManager which is now responsible for creating new channel.
(Example from docs)
// Create a new text channel
guild.channels.create('new-general', { reason: 'Needed a cool new channel' })
.then(console.log)
.catch(console.error);
https://discord.js.org/#/docs/main/stable/class/GuildChannelManager
#Jim Knee's I think your answer is v11, I'm new in discord.js, using Visual Studio Code's auto-code thingy. You can do all the same things except your thing must be this. If you are poor people, getting errors on doing #Jim Knee's answer, this is the place for "YOU!"
Get rid of server.createChannel(name, "text/voice");
And get it to THIS server.channels.create(name, "text/voice");
Hope I can help at least ;)
I'm just a new guy here too
I think you have not logged in with your bot.
From the docs:
const Discord = require('discord.js');
var client = new Discord.Client();
client.login('mybot#example.com', 'password', output); // you seem to be missing this
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
Alternatively, you can also login with a token instead. See the docs for the example.

InDesign scripting of the Socket object yields cryptic error message

I'm working on a broadcast e-mail template that would pull the latest three articles off our blog from an RSS feed and insert the relevant sections into the document.
I looked at the documentation, and based on the bit about the File object, some of my own debugging, and an InDesign forum post I've learned that it's not possible to use the File object to source an online XML file.
The alternative (without resorting to an external script, one of which didn't work for me anyways), it seems, is to use the Socket object. So I went back to the documentation and copied/pasted this code verbatim from there:
reply = "";
conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
conn.close();
}
When I ran it, I received this descriptive error message:
A search for "89858 javascript error" yielded nothing useful.
So I'm stuck. Either Adobe's code sample has an error, or, more likely, there's something wrong on my end. If I had to guess, I'd guess that it's some kind of proxy problem, but I don't know for sure and don't know how to find out.
Can anyone help? The principles of the Socket object make sense to me, but if I can't get even the sample to work, I don't really have anywhere to go with this.
The error above occurs when you return certain objects (XML, Socket) from a function call, but the return values does not get assigned anywhere.
function test() {
var xml = new XML('<test />');
return xml;
}
test();
The above will cause an error. To get around it you have to assign the return value somewhere.
var result = test();
Try to put all collect all function calls result. I am not sure which one causes the error.
var reply = "";
var conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
var result = conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
var close = conn.close();
}

Categories