Cannot read properties of undefined (reading 'on') client.on("ready", () => - javascript

I am coding a Discord bot and found an issue I cannot fix.
checking if the bot was online to send a message in the console and a rich presence
client.on("ready", () => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: 'online',
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
});
});
All the code
const { MessageHandler } = require("discord-message-handler"); // npm install discord-message-handler //
const handler = new MessageHandler();
const discord = require("discord.js"); // npm i discord.js //
const { Options } = require("discord.js");
const { GatewayIntentBits } = require("discord.js");
var logger = require("winston"); // npm install winston //
const { client, Collection } = require("discord.js");
const { config } = require("dotenv");
const Client = {
disableEveryone: true,
};
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console(), {
colorize: true,
});
logger.level = "debug";
// Initialize Discord Bot
var bot = new discord.Client({
autorun: true,
});
client.on("ready", () => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: "online",
game: {
name: "Cool kid the movie 2",
type: "WATCHING",
},
});
});
client.login(process.env.TOKEN);

you have to mention client in the function you created
and also you defined your Discord Bot as bot
so code will be
bot.on("ready", (client) => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: 'online',
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
});
});
here is an example code
const {
Client,
Partials,
Collection,
PermissionFlagsBits,
EmbedBuilder,
} = require("discord.js");
const { config } = require("");// enter your path
const { user, Message, GuildMember} =
Partials;
const client = new Client({
intents: 131071,
Partials: [
user,
Message,
GuildMember,
PermissionFlagsBits
],
allowedMentions: { parse: ["everyone", "roles", "users"] }
});
client.login(//token path).catch((err) => console.log(err));
client.on("ready", (client) => {
client.user.setPresence({
status: "online",
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
})
});

Related

How to catch the message button click event on Slack, and get the input value

I am trying to make a small NodeJS project to connect to Slack, post an interactive message, and receive feedback.
My code to post the message:
require("dotenv").config();
const { App } = require("#slack/bolt");
const express = require('express')
const app = express()
const axios = require('axios');
const APP_PORT = 3001
const LISTEN_PORT = 3002
const { createMessageAdapter } = require('#slack/interactive-messages');
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackInteractions = createMessageAdapter(slackSigningSecret);
app.use('/listen', slackInteractions.requestListener());
(async () => {
const server = await slackInteractions.start(LISTEN_PORT );
console.log(`Listening for events on ${server.address().port}`);
})();
app.listen(APP_PORT, () => {
console.log(`App running on port ${APP_PORT}.`)
})
app.get('/survey', async function sendmessage(){
const url = 'https://slack.com/api/chat.postMessage';
const res = await axios.post(url, {
channel: '#test',
blocks: JSON.stringify([
{
type: "section",
text: {
type: "mrkdwn",
text: "Survey"
}
},
{
type: 'input',
block_id: 'txt_input',
label: {
type: 'plain_text',
text: 'Response'
},
element: {
type: 'plain_text_input',
action_id: 'text_input',
placeholder: {
type: 'plain_text',
text: 'Your response'
},
multiline: true
}
},
{
type: "actions",
block_id: "btn_submit",
elements: [
{
type: "button",
text: {
type: "plain_text",
emoji: true,
text: "Submit"
},
style: "primary",
value: "1"
}
]
}
])
}, { headers: { authorization: `Bearer ${process.env.SLACK_BOT_TOKEN}`}});
});
The above code successfully post an interactive message on Slack channel. When user input the value and click button Submit, I would like to catch it and process.
I have read the Slack guide from Slack Interactive Messages for Node for how to listen to the event, but unable to success in any of it.
I add the below code to listen to the button event, but unable to catch anything.
slackInteractions.action({ type: 'button' }, (payload, respond) => {
// Logs the contents of the action to the console
console.log('payload', payload);
});
slackInteractions.action({ type: 'message_action' }, (payload, respond) => {
// Logs the contents of the action to the console
console.log('payload', payload);
});
What did I do wrong?
I think you need to add the slackInteractions middleware to your Bolt app:
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
receiver: slackInteractions.receiver
});

Discord commands not registering

I'm new to js and i tried making a discord bot, i got the bot on the server but i cant register the commands. This is the error I'm getting:DiscordAPIError[50035]: Invalid Form Body application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. at SequentialHandler.runRequest (c:\Users\Waku\Desktop\Discord bot\node_modules\#discordjs\rest\dist\index.js:708:15) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async SequentialHandler.queueRequest (c:\Users\Waku\Desktop\Discord bot\node_modules\#discordjs\rest\dist\index.js:511:14) { rawError: { code: 50035, errors: { application_id: [Object], guild_id: [Object] }, message: 'Invalid Form Body' }, code: 50035, status: 400, method: 'put', url: 'https://discord.com/api/v9/applications/undefined/guilds/undefined/commands', requestBody: { files: undefined, json: [ [Object], [Object] ] } }
This is the code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('marco').setDescription('Replies with polo!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
Blockquote

S3 Upload Failing Silently in Production

I'm struggling to debug a NextJS API that is working in development (via localhost) but is silently failing in production.
Below, the two console.log statements are not returning, so I suspect that the textToSpeech call is not executing correctly, potentially in time?
I'm not sure how to rectify, happy to debug as directed to resolve this!
const faunadb = require('faunadb')
const secret = process.env.FAUNADB_SECRET_KEY
const q = faunadb.query
const client = new faunadb.Client({ secret })
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1')
const { IamAuthenticator } = require('ibm-watson/auth')
const AWS = require('aws-sdk')
const { randomUUID } = require('crypto')
import { requireAuth } from '#clerk/nextjs/api'
module.exports = requireAuth(async (req, res) => {
try {
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
})
const textToSpeech = new TextToSpeechV1({
authenticator: new IamAuthenticator({
apikey: process.env.IBM_API_KEY
}),
serviceUrl: process.env.IBM_SERVICE_URL
})
const uuid = randomUUID()
const { echoTitle, chapterTitle, chapterText } = req.body
const synthesizeParams = {
text: chapterText,
accept: 'audio/mp3',
voice: 'en-US_KevinV3Voice'
}
textToSpeech
.synthesize(synthesizeParams)
.then(buffer => {
const s3Params = {
Bucket: 'waveforms/audioform',
Key: `${uuid}.mp3`,
Body: buffer.result,
ContentType: 'audio/mp3',
ACL: 'public-read'
}
console.log(buffer.result)
console.log(s3Params)
s3.upload(s3Params, function (s3Err, data) {
if (s3Err) throw s3Err
console.log(`File uploaded successfully at ${data.Location}`)
})
})
.catch(err => {
console.log('error:', err)
})
const dbs = await client.query(
q.Create(q.Collection('audioform'), {
data: {
title: echoTitle,
published: 2022,
leadAuthor: 'winter',
user: req.session.userId,
authors: 1,
playTime: 83,
chapters: 1,
gpt3Description: '',
likes: 20,
image:
'https://waveforms.s3.us-east-2.amazonaws.com/images/Mars.jpeg',
trackURL: `https://waveforms.s3.us-east-2.amazonaws.com/audioform/${uuid}.mp3`,
albumTracks: [
{
title: chapterTitle,
text: chapterText,
trackURL: `https://waveforms.s3.us-east-2.amazonaws.com/audioform/${uuid}.mp3`
}
]
}
})
)
res.status(200).json(dbs.data)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
Replace the async fragments something like this, assuming they are meant to be executed sequentially.
try {
// code removed here for clarity
const buffer = await textToSpeech.synthesize(synthesizeParams);
const s3Params = {
Bucket: 'waveforms/audioform',
Key: `${uuid}.mp3`,
Body: buffer.result,
ContentType: 'audio/mp3',
ACL: 'public-read'
}
await s3.upload(s3Params).promise();
const dbs = await client.query(...);
res.status(200).json(dbs.data);
} catch (e) {
res.status(500).json({ error: e.message });
}

Discord JS - DiscordAPIError: Missing Access

So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
method: 'post',
path: '/applications/901999677011005472/guilds/905266476573950023/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: {
name: 'ping',
description: 'Bot uptime/latency checker.',
type: undefined,
options: undefined,
default_permission: undefined
},
files: []
}
}
I also try looking at my code but I didn't see something wrong.
This is my code, I really think something is wrong in the code.
const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
client.on('ready', () => {
console.log("The bot is online")
// Carlos: 883425101389914152
const guildId = '905266476573950023'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Bot uptime/latency checker.',
})
commands.create({
name: 'add',
description: 'Adds two numbers given by user.',
options: [
{
name: 'number1',
description: 'The first number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
{
name: 'number2',
description: 'The second number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
]
})
})
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, Options } = interaction
if (commandName === 'ping') {
interaction.reply({
content: 'Pong! **60ms**',
// If anyone can see = True, Only command user can see = False
ephemeral: true,
})
} else if (commandName === 'add') {
interaction.reply({
content: 'The sum is ${number1 + number2}'
})
}
})
client.login(process.env.KEY)
For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.
You did not select the right permissions when creating bot login link for your discord server.
Goto developers / oauth again, click bot and select all the required permissions that you're using in this bot.
Then copy the link generated and use it to login with your bot into your server.
don't forget to change this:
content: 'The sum is ${number1 + number2}'
to this:
content: `The sum is ${number1 + number2}`

TypeError: Cannot read property 'setPresence' of null discord.js v13

I have a little problem. I'm doing the event ready, with an event handler, but I come across this error:
client.user.setPresence({
^
TypeError: Cannot read property 'setPresence' of null
I don't really know what I'm doing wrong, here is the code:
const mongo = require('../../mongo');
const mongoose = require('mongoose');
const messageCount = require('../../message-counter')
const Discord = require('discord.js')
module.exports = async (Discord, client) => {
let serverIn = client.guilds.cache.size;
console.log('[INFO] Doose is online');
client.user.setPresence({
status: "dnd",
activity: {
name: `${serverIn} servers! | BETA | d.help`,
type: "WATCHING"
}
});
console.log('[INFO] Connected to MongoDB')
messageCount(client)
};
MUST READ: Extra Info
Using discord.js V13
Presence can be set via the options parameter in the Discord.Client(options) constructor like so:
const client = new Client({
presence: {
status: 'online',
afk: false,
activities: [{
name: ...,
type: ...,
}],
},
intents: [...],
partials: [...],
});
This should help !!
client.on('ready', () => {
client.user.setActivity(`!help || ${client.guilds.cache.size} Servers `, { type: "LISTENING" })
console.log(`Logged in as ${client.user.tag}`);
})
and for the other , you can use something like this ⬇️
client.user.setPresence({
status: "idle"
})

Categories

Resources