I have a code which I'm doing on replit, and I'm pretty new to node.js so I really do need assistance with this. I have a code which is this:
const Discord = require("discord.js")
const fetch = require("node-fetch")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
function getQuote() {
return fetch('https://zenquotes.io/api/random')
.then(res => {
return res.json
})
.then(data => {
return data[0]["q"] + " —" + data [0]["a"]
})
}
client.on("ready", () => {
console.log('Logged in as ${client.user.tag}' )
})
client.on("message", msg => {
if (msg.author.bot) return
if (msg.content === "$inspire") {
getQuote().then(quote => msg.channel.send(quote))
}
})
client.login(process.env.TOKEN)
However, I'm receiving the error:
npx node .
/home/runner/1Starty/index.js:2
const fetch = require("node-fetch")
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/1Starty/node_modules/node-fetch/src/index.js from /home/runner/1Starty/index.js not supported.
Instead change the require of /home/runner/1Starty/node_modules/node-fetch/src/index.js in /home/runner/1Starty/index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/runner/1Starty/index.js:2:15) {
code: 'ERR_REQUIRE_ESM'
}
May someone help me on why this is the case?
Open shell and run this command
npm i node-fetch#2.6.6
Related
I'm using Node.js v18.12.1 and Discord.js v14. for developing the Discord bot. I need to read some data from Firebase. I'm confused because I'm used to how Java with Hibernate fetches data differently. Here, I need to use onValue() listener.
My onValue() acts strange. Instead of just reading the data from Firebase, it skips entirely, then it triggers multiple times, each time skipping the body block of its code, and then it actually does the code after.
I've read somewhere on this forum that this can happen because there are more onValue() listeners that are subscribed and they are all fired up. Someone mentioned I need to use the off() function somewhere "before" the onValue(). This confuses me because I'm using this listener in many locations. I need it in each command file, in execute(interaction) functions. You know, when you need to execute slash commands in Discord. I have it something like this:
async execute(interaction) {
const infographicRef = ref(db, '/infographics/arena/' + interaction.options.getString("arena-team"));
var imageUrl = null;
var postUrl = null;
onValue(infographicRef, (snapshot) => {
imageUrl = snapshot.child("image-url").val();
interaction.reply(imageUrl);
})
},
And I planned for each command, in each command.js file to have onValue(). I'm not sure exactly what to do.
Also, I tried to work around this with once() method, I see it in Firebase documentation, but I got the error: ref.once() is not a function.
It seems that after first triggering of onValue method when the body is not executed, my code in interactionCreate.js is triggered as well, it points for a command to be executed again:
const { Events } = require('discord.js');
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
};
my bot.js (which is in my case an index file)
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
The onValue function registers a realtime listener, that continues to monitor the value on the database.
If you want to read a value once, that'd be done with get() function in v9 (which is the equivalent of the once method in earlier SDK versions). Have a look at the code sample in the documentation on reading data once.
I am using web3 function getPastEvents and I am getting error:
Returned error: limit exceeded
I also changed RPC url but same error occured their.
Is there any other way to get event data ?
this is my code:
const http = require("http");
const cron = require('node-cron');
const { randomBytes } = require("crypto");
const web3 = new Web3("https://bsc-dataseed.binance.org/");
//console.log("Hello This",web3);
//console.log("hello");
const dexABI =contractAbi;
const contract_address = "0xd19EA9d72828444BC7bAE231fBa66F8050e72b1b";
const contract = new web3.eth.Contract(dexABI, contract_address);
async function generateEventQuery(result) {
console.log(result);
return ;
}
http
.createServer((req, res) => {
web3.eth
.getBlockNumber()
.then((d) => {
let current_block = d;
console.log(current_block);
contract
.getPastEvents({
fromBlock: Number(23390147),
toBlock: Number(23390147)+100,
})
.then( async(events) => {
let resu = await generateEventQuery(events);
})
.catch((e) => {
console.log("Err",e)
res.write("Err:" + JSON.stringify(e));
res.end();
});
})
.catch((e) => e);
})
.listen(8080);
in the function getPastEvents() you have to take the first parameter as your event name which you want to fetch the data. The name should be as same as in your contract and passed into a string.
Actually, this is an RPC problem. I replaced https://bsc-dataseed.binance.org/ with https://bscrpc.com. Now it works properly.
Public RPC URLs like https://bsc-dataseed.binance.org/ or https://bscrpc.com have rate-limiting to prevent people from over using it.
It's fine for testing but in production you should use your own node or a blockchain API like Infura, Alchemy, QuickNode or any other.
My code for a translator bot is as such, everything works well, except for the "command" command, which I decided to turn into an embed to make it look more slick than unaligned string on the screen. the code is as such:
const Discord = require('discord.js');
const language = require('./langOptions');
const translate = require('#vitalets/google-translate-api');
const config = require('./config.json');
const speech = require('./messages');
const client = new Discord.Client();
const prefix = config.prefix;
const { MessageEmbed } = require('discord.js
');
const express = require("express");
const server = express();
server.all("/", (req, res) => {
res.send("Bot is running!")
})
function keepAlive() {
server.listen(3000, () => {
console.log("Server is ready.")
})
}
module.exports = keepAlive
client.on("ready", () => {
console.log("The bot is ready.");
});
client.on("message", (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// It can be a regular ! message. This says to not bother if it doesn't have a prefix, and
// to not trigger if a bot gives a command.
if (!message.content.startsWith(prefix) || message.author.bot) {
return;
}
// Auto-translates the text into the command's language like !japanese, or !french
if (language.some(ele => ele.name === command)) {
if (args.length === 0) {
message.reply(speech.BOT_FULLNAME_AUTO_ERROR);
} else {
let lang_to = language.filter(ele => ele.name===command)[0].abrv;
let text = args.slice(0).join(' ');
translate(text, {to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => message.channel.send(speech.BOT_TRANSLATION_ERROR + err));
}
}
// Auto translates with abbreviation like !ko, !en, or !de
if (language.some(ele => ele.abrv=== command)) {
if (args.length === 0) {
message.reply(speech.BOT_ABBR_AUTO_ERROR);
} else {
let lang_to = language.filter(ele => ele.abrv===command)[0].abrv;
let text = args.slice(0).join(' ');
translate(text, {to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => message.channel.send(speech.BOT_TRANSLATION_ERROR + err));
}
}
// Specifies the text's language and translates it into a specific language
if (command === "translate") {
if (args.length < 3) {
message.reply(speech.BOT_TRANS_SPECIFIC_ERROR);
} else {
let argFrom = args[0].toLowerCase();
let argTo = args[1].toLowerCase();
let lang_from = language.filter(ele => ele.name === argFrom)[0].abrv;
let lang_to = language.filter(ele => ele.name=== argTo)[0].abrv;
let text = args.slice(2).join(' ');
translate(text, {from: lang_from, to: lang_to})
.then(res => message.channel.send(res.text))
.catch(err => console.log(speech.BOT_TRANSLATION_ERROR + err));
}
}
if (command === "commands") {
const embed = new MessageEmbed()
.setTitle(`Help has arrived`)
.setDescription(`Here are the proper syntax when using Kitsune Saiguu's polyglotirific abilities (I swear that's a word, don't quote me on that though.)`)
.setTimestamp();
message.reply({ content: `**For a list of names and abbreviates go here: **<https://cloud.google.com/translate/docs/languages>
Here are the appropriate syntaxes when using commands:
*!translate from to text*
=>!translate english italian <english-text-here>
Note: This command, like it shows, turns inputted english text to italian.
*!language auto-translate-text*
=>!french english-text-here turns english to french
Note: This shortens the translation process, however, it does not auto-detect different languages.
*!abrv auto-translate-text*
=>!de english-text-here turns english to german
Note: Can work for the first and second examples, and shortens the syntax even further.`, embeds: [embed]});
}
})
client.login(config.token);
And I'm getting this error no matter which embed type I'm using (note that all three types of embed are from the discord.js guide for v13:
/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13
Object.defineProperty(this, 'client', { value: message.client });
^
TypeError: Cannot read properties of undefined (reading 'client')
at new MessageEmbed (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13:60)
at Client.<anonymous> (/home/runner/Kitsune-Saiguu-2/app.js:86:17)
at Client.emit (node:events:390:28)
at MessageCreateHandler.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
at WebSocketPacketManager.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:293:17)
at WebSocket.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (node:events:390:28)
at Receiver._receiver.onmessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/websocket.js:145:47)
~/Kitsune-Saiguu-2$ node app.js
The bot is ready.
/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13
Object.defineProperty(this, 'client', { value: message.client });
^
TypeError: Cannot read properties of undefined (reading 'client')
at new MessageEmbed (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/structures/MessageEmbed.js:13:60)
at Client.<anonymous> (/home/runner/Kitsune-Saiguu-2/app.js:86:17)
at Client.emit (node:events:390:28)
at MessageCreateHandler.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
at WebSocketPacketManager.handle (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:330:35)
at WebSocketConnection.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:293:17)
at WebSocket.onMessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (node:events:390:28)
at Receiver._receiver.onmessage (/home/runner/Kitsune-Saiguu-2/node_modules/ws/li
I didn't really have much of an issue creating embeds before discord.js v13.
Small note: this was the error shown on Repl.it
Anybody help me on creating .env file and modify the codes!
this is discord.js v12
i cant modify the .env codes on this codes!
but it didnot working
pls help me in this system! and it is yarn installed method!
js file => RushGamerzClient.js
const { Client } = require('discord.js');
module.exports = class RushGamerzClient extends Client {
constructor(options = {}) {
super({
disableMentions: 'everyone'
});
this.validate(options);
this.once('ready', () => {
console.log(`Logged in as ${this.user.username}!`);
});
this.on('message', async (message) => {
const mentionRegex = RegExp(`^<#!${this.user.id}>$`);
const mentionRegexPrefix = RegExp(`^<#!${this.user.id}> `);
if (!message.guild || message.author.bot) return;
if (message.content.match(mentionRegex)) message.channel.send(`My prefix for ${message.guild.name} is \`${this.prefix}\`.`);
const prefix = message.content.match(mentionRegexPrefix) ?
message.content.match(mentionRegexPrefix)[0] : this.prefix;
if (!message.content.startsWith(prefix)) return;
// eslint-disable-next-line no-unused-vars
const [cmd, ...args] = message.content.slice(prefix.length).trim().split(/ +/g);
if (cmd.toLowerCase() === 'hello') {
message.channel.send('Hello!');
}
});
}
validate(options) {
if (typeof options !== 'object') throw new TypeError('Options should be a type of Object.');
if (!options.token) throw new Error('You must pass the token for the client.');
this.token = options.token;
if (!options.prefix) throw new Error('You must pass a prefix for the client.');
if (typeof options.prefix !== 'string') throw new TypeError('Prefix should be a type of String.');
this.prefix = options.prefix;
}
async login(token = this.token) {
super.login(token);
}
};
js file => index.js codes on here
const RushGamerzClient = require('./Structures/RushGamerzClient');
const config = require('../config.json');
const client = new RushGamerzClient(config);
client.login();
You have few options to fix the problem:
Use .env file that has
DISCORD_TOKEN="<your-token>"
then use dotenv (install using npm i -G dotenv) on the top of your file, and login with environment variable
require('dotenv').config();
...
client.login(process.env.DISCORD_TOKEN);
Im getting a unexpected token, but I'm not sure what I'm doing wrong.
I tried to delete all modules and then renstall them but that didnt help
import { Client } from 'discord.js';
const client = new Client();
var GphApiClient = require('giphy-js-sdk-core')
client = GphApiClient("MyAPIkey");
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.content.startsWith(`${prefix}!send`)) {
giphy.search('gifs', {"q": "cats"})
.then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) %
totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send("Kapo on teel", {
files: [responseFinal.images.fixed_height.url]
})
})
};
})
This is the error I was getting:
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:811:22)
I think your syntax error is because you were trying to use ES6 modules (eg: import/export) without using something to transpile (eg: babel). There's more on that here if you're interested. In other words, I don't think you can use import. You have to use require. I also fixed the issues with client being defined multiple times. However, this code below still won't work because prefix was never defined anywhere.
const { Client } = require('discord.js');
var GphApiClient = require('giphy-js-sdk-core')
const discordClient = new Client();
giphyClient = GphApiClient('MyAPIkey');
discordClient.once('ready', () => {
console.log('Ready!');
});
discordClient.on('message', message => {
if (message.content.startsWith(`${prefix}!send`)) {
giphyClient.search('gifs', { "q": "cats" })
.then((response) => {
const totalResponses = response.data.length;
const responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
const responseFinal = response.data[responseIndex];
message.channel.send("Kapo on teel", {
files: [responseFinal.images.fixed_height.url]
});
})
} else {
console.log(`message doesn't start with ${prefix}!send`)
}
});