Embeds appearing as empty when sent discord.js [duplicate] - discord.js

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 12 months ago.
i'm getting an error whenever I try to send an embed. This has only just started happening, and i've not done any form of updates (as far as I know) Here's my code:
const ping = new Discord.MessageEmbed()
.setTitle('Pong!')
.setDescription(`🏓 \`${Date.now() - message.createdTimestamp} ms\``)
.setColor(0x39f79e);
message.channel.send('test')
console.log(ping)
message.channel.send(ping)
and here's the error that i'm getting, as well as the content logged to the console:
MessageEmbed {
type: 'rich',
title: 'Pong!',
description: '🏓 `50 ms`',
url: null,
color: 3798942,
timestamp: null,
fields: [],
thumbnail: null,
image: null,
video: null,
author: null,
provider: null,
footer: null
}
/home/runner/Jungle-Bot/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/Jungle-Bot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/Jungle-Bot/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/938846693884047410/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
any help would be appreciated, i'm relatively new to this

With the newest update to Discords API your final line should be changed to this:
message.channel.send({
embeds: [ping]
})

Related

50035 Invalid Form Body - Application command names are unique

I am trying to make a quick bot (with my limited knowledge of discord.js) that has a command to "mine bobux" which determines a random variable and tells the user how much bobux they "mined." After doing node deploy-commands.js (following discordjs.guide) powershell responds with
S[50035]: Invalid Form Body
1[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names are unique
at Q.runRequest (C:\Users\myname\Downloads\bobuxminer\node_modules\#discordjs\rest\dist\index.js:7:581)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Q.queueRequest (C:\Users\myname\Downloads\bobuxminer\node_modules\#discordjs\rest\dist\index.js:5:2942) {
rawError: {
code: 50035,
errors: { '1': [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'put',
url: 'https://discord.com/api/v9/applications/936299610002038784/guilds/399355403567366146/commands',
requestBody: { files: undefined, json: [ [ae], [Object], [Object], [Object] ] }
}
This is the command itself that I am trying to make.
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder().setName('mine')
.setDescription('Mines bobux'),
async execute(interaction) {
var bobuc = Math.floor(Math.random() * 100) + 1;
await interaction.reply(`You mined ${bobuc} bobux`);
},
};
I've checked all my files and found no duplicate commands and do not know how to resolve this issue. If you need anything else, I will provide my other files.
Remove all other instances of the command and only keep the command in the mine.js file.

I am trying to get values from client.users.fetch(user id) but it just isnt working

my code:
if(message.content == prefix + "dev"){
const owner = client.users.fetch('462223589043863562');
console.log(owner.user);
console.log(owner.id);
console.log(owner);
message.channel.send(`eggy is the dev of this chad ass bot. Discord: ${owner}`);
logs:
undefined
undefined
Promise {
User {
id: '462223589043863562',
system: false,
locale: null,
flags: UserFlags { bitfield: 64 },
username: 'eggyy',
bot: false,
discriminator: '0001',
avatar: 'a_de18cc5553a2fd2e5fbd3d3e3491595b',
lastMessageID: '865041520075735040',
lastMessageChannelID: '864827452063875125'
}
}
Also, when doing owner.Promise.User.user it gives an error: TypeError: Cannot read property 'User' of undefined.
<client>.users.fetch() returns a promise which you can handle simply by using await. Therefore, in order to resolve it, you can just replace your current owner definition with const owner = client.users.fetch('462223589043863562');.
However, if you are going to use await, you must make your present function async (e.g. client.on('message', async message => {}).

I tried to do welcome message with my discord bot (Using discord.js) And I have weird error

I dont get what is wrong here in my code.
I used my token where I typed my token goes here
The error :
/home/runner/my-server-bot/index.js:43
client.login('I will hide my token');
^^^^^^
SyntaxError: Unexpected identifier
Can anyone explain to me what's wrong with that code?
client.on('guildMemberAdd', msg => { // Commands Go Inside The client.on('message',
msg =>
msg.guild.channels.get('861132489584934926').send({embed: {
color: 3447003,
author: {
name: client.user.username,
icon_url: client.user.avatarURL
},
title: "Welcome To OP COMMUNITY!",
description: "Have Fun in the server :)",
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "Builded by Oplikoo#9999"
} }
client.login('my token was here');
Your code was really messy! I decided to do a complete rework on it.
I explain how it works with notes in the code below.
client.on('guildMemberAdd', member => { // We don't get msg from this, we get member.
let channel = client.channels.get('861132489584934926'); // Getting the channel
let embed = new Discord.MessageEmbed() // A different form of making an embed
.setAuthor({
name: client.user.username,
icon_url: client.user.avatarURL
})
.setColor('#447003')
.setTitle('Welcome To OP COMMUNITY')
.setDescription('Have Fun in the server :)')
.setTimestamp(new Date())
.setFooter({
icon_url: client.user.avatarURL,
text: 'Builded by Oplikoo#9999'
});
channel.send(embed); // We send the embed we just created});
});
client.login('my token was here');

Unable to schedule expo notifications every 3 days

I'm working on a project where i want to schedule notifications every X days.
here is the part where i schedule notifications :
let notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: title,
body: body,
data: null,
},
trigger: { day: freq, repeats: true },
});
I tried with
trigger: { hour: freq * 24, repeats: true },
But every time i get this error :
[Unhandled promise rejection: Error: Failed to schedule the notification. Trigger of type: calendar is not supported on Android.]
I know some people will maybe say it's because i try it on emulator but it should still work and to be sure i try on my phone too and it still doesn't work.
Try this
const trigger = await Notifications.getNextTriggerDateAsync({
channelId: DECKS_NOTIFICATION_CHANNEL_ID,
hour: 20,
minute: 0,
repeats: true,
//seconds: 2,
})
then
let notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: title,
body: body,
data: null,
},
trigger
});
There are so many types of SchedulabeNotificationTriggers. The one i showed you is for daily. You can check more in this link
Expo Notifications

TypeORM handle database outage

Let's say my MSSQL server has crashed and my app client requests something from the API. Right now it will just spin until the unanswered request is timed out by Express.
When logging is enabled in TypeORM I can see that the relevant query is executed.
I would prefer to return an API response informing the client that the database is unreachable.
This is the actual code in my user controller
public static listAll = async (req: Request, res: Response) => {
const userRepository = getRepository(User);
const users = await userRepository
.find()
res.send(users);
};
I have tried to .catch the request that is being used in the relevant controller, but doesn't seem to change anything. See example below.
const users = await userRepository
.find()
.catch(error => {
console.log(error); // this is never triggered
});
No error message is logged out in console.
These are my connection options in TypeORM
createConnection({
type: 'mssql',
host: process.env.TYPEORM_HOST,
port: parseInt(process.env.TYPEORM_PORT, 0),
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
synchronize: true,
logging: true,
entities: models,
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'src/migration',
subscribersDir: 'src/subscriber',
},
})
.then(connection => {
const server = http.createServer(App);
server.listen({ port: `${process.env.APP_PORT}` }, () => {
console.log(`🚀 Server ready at http://${process.env.TYPEORM_HOST}:${process.env.APP_PORT}`);
});
if (connection.isConnected) {
console.log(`Database ${connection.options.database} connected`);
}
})
.catch(error => console.log(error));
I also tried to set requestTimeout in createConnection to 1000 (ms), with same result.
export default class App {
public app: express.Application;
public db: Connection;
constructor() {
this.app = express();
this.appConfiguration();
}
public async appConfiguration() {
try {
this.db = await Database.init();
// Make use of JSON Body
this.app.use(bodyParser.json());
// Inits Routes
Routes.init(this.app);
} catch(err) {
console.log('database is not reachable, see error:', err)
};
}
public getApp(): express.Application {
return this.app;
}
}
Database.init() is used for creating a connection to the db:
export class Database {
public static init() {
return createConnection({
type: "postgres",
host: process.env.TYPEORM_HOST,
port: parseInt(process.env.TYPEORM_PORT),
database: process.env.TYPEORM_DATABASE,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
entities: [
User
],
synchronize: process.env.TYPEORM_SYNCHRONIZE == "true" ? true : false,
logging: process.env.TYPEORM_LOGGING == "true" ? true : false
});
}
}
Result when changing db name to some random DB I'll get error messages in the console:
[nodemon] starting `ts-node src/server.ts`
Server listening on port 5000
database is not reachable, see error:
{ error: database "express_text_typeorms" does not exist
at Connection.parseE
at Connection.parseMessage
at Socket.<anonymous>
at Socket.emit (events.js:198:13)
at Socket.EventEmitter.emit (domain.js:448:20)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'error',
length: 106,
severity: 'FATAL',
code: '3D000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'postinit.c',
line: '890',
routine: 'InitPostgres' }
Is that what you're trying to acchieve?

Resources