I'm trying to learn how to create NFTs on the Ethereum block chain.
In terminal (Ubuntu 20.04.3 LTS)
Aki-Zeta:~/my-nft$ node scripts/mint-nft.js
I keep getting
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
Syntax Error Unexpected Token {
see bottom for full error
Here is my code using VScode
require("dotenv").config()
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")
const contractAddress = "0xf469355dc12e00d8cda65b3a465bdad65da27e22"
const nftContract = new web3.eth.Contract(contract.abi, contractAddress)
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),
}
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
signPromise
.then((signedTx) => {
web3.eth.sendSignedTransaction(
signedTx.rawTransaction,
function (err, hash) {
if (!err) {
console.log(
"The hash of your transaction is: ",
hash,
"\nCheck Alchemy's Mempool to view the status of your transaction!"
)
} else {
console.log(
"Something went wrong when submitting your transaction:",
err
)
}
}
)
})
.catch((err) => {
console.log(" Promise failed:", err)
})
}
mintNFT(
"https://gateway.pinata.cloud/ipfs/QmcRikKfA6xdaNZkojW28xpvZYysQXSJEb52YdeRJP3GGv"
)
Is it something to do with that "{" in line 6, or something else in line 6?
Prior to running this script I ran "npm install #alch/alchemy-web3", and verified the directories exist (both by going there and with cd). Other people with similar issues are missing something, and I have no idea what I'm missing. I have checked for spurious spaces and semicolons but I am not experienced with this language.
I have been using the tutorials off of the Ethereum project site.
full error
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:471:10)
at startup (node.js:117:18)
at node.js:951:3
I had exactly the same error, and it was just a spurious character in my VScode editor, same example as you from ethereum.org.
As you can see in line 24
change const { createAlchemyWeb3 } to const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
Related
Every time I try to run my discord bot I get this error:
node:internal/modules/cjs/loader:1047
const err = new Error(message);
^
Error: Cannot find module './src/Commands/Tools/ping.js'
Require stack:
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1047:15)
at Module._load (node:internal/modules/cjs/loader:893:27)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at client.handleCommands (/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js:15:25)
at Object.<anonymous> (/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js:19:8)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js',
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js'
]
}
Here are my bot.js, commandHandler.js, and ping.js files and my file structure
bot.js
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/Functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`./src/Functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./Functions/${folder}/${file}`)(client);
}
client.handleCommands();
client.handleEvents();
client.login(token);
commandHandler.js
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
const path = require("node:path");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync(`./src/Commands`);
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`src/Commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`src/Commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command, command.data.toJSON());
console.log(`Command: ${command.data.name} has been registered`);
}
}
const clientId = "1070133880671174697";
const guildId = "1070126560004276305";
const rest = new REST({ version: "9" }).setToken(process.env.token);
try {
console.log("Started refreshing commands.");
await rest.put(Routes.applicationCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully refreshed commands.");
} catch (err) {
console.error(error);
}
};
};
ping.js
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Returns my ping"),
async execute(interaction, client) {
console.log("pinged");
},
};
File Structure
File Structure
I've tried editing it myself, checking I've written the right code in the tutorial, and extensive googling, but nothing works, and for people who have had the same problem theirs just 'magically' fixed.
Edit 1 - I have tried ../../src as #rebe100x suggested but when I did path.basename it gave me this error
Error: ENOENT: no such file or directory, scandir 'Tools'
Edit 2 - I used 'src/Commands/${folder} but now it gives me the same error as before
On commandHandler.js line 15
const command = require(`./src/Commands/${folder}/${file}`);
The file directory is wrong. From your structure, commandHandler.js is in Function > Handlers > commandHandler.js.
Simply change the directory to ../../src/Commands/${folder}/${file} and it should fix the path problem
/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:548:13)
at new Client (/home/kevind/Downloads/VibeUtils2/node_modules/discord.js/src/client/Client.js:76:10)
at Object.<anonymous> (/home/kevind/Downloads/VibeUtils2/commands/role.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/kevind/Downloads/VibeUtils2/index.js:13:21) {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
This is the error I'm getting, however my code looks like
const fs = require('fs');
const {prefix, reactEmoji, token, clientId, guildId} = require('./config/config.json');
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
const { Client, Collection, Intents, Discord } = require('discord.js');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MESSAGES] });
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
const commands = [];
const slashcommandFiles = fs.readdirSync('./slashcommands').filter(file => file.endsWith('.js'));
for (const file of slashcommandFiles) {
const command = require(`./slashcommands/${file}`);
commands.push(command.data.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);
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
client.on('message', message => {
if (message.content.toLowerCase().startsWith('welcome')) {
message.react(reactEmoji);
console.log(`Reacted on ${message.author.tag}'s message.`);
}
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
try {
command.execute(message, args);
}catch (error) {
console.error(error);
message.reply('There was an error while trying to execute that command!');
}
})};
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) 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);
I'm still handing normal commands until v12 gets deprecated,and so I can transition. However I'm having issues with intents. Please help me on what intents are valid, because those look valid to me. If I'm doing something critically wrong, then please let me know. This is one of my first times actually delving into v13, however as far as I've seen I've done everything correct, that is going off of documentation. If I missed something please let me know, because I think that should work. Most of my ready is handled in an event file.Is there an easy way to add all intents? The ways I've seen here don't work
Ensure your intents are turned on in your Developer Portal.
Go to https://discord.com/developers/applications
Click on your application
Click on the "Bot" section
Enable the intents you need there; these are only privileged intents so not everything will be there, you will need the Server Members Intent & Message Content Intent (just so you're ready for when it is enforced)
Upon checking,GUILD_EMOJIS_AND_STICKERS and GUILD_BANS are not valid intents in Discord.js V12. You'll either need to switch or remove those intents from your array. (Added from comments, just so it's easier to find)
As for adding every intent at once, that's not really possible. Though you could run this in the repl and paste the results into the intents array (this is done in V13, I highly suggest running this yourself in a node repl so it uses your Discord.js version):
const discord = require("discord.js"); const intents = Object.keys(discord.Intents.FLAGS); let formattedIntents = []; intents.forEach((intent) => {formattedIntents.push(`"${intent}"`)}); formattedIntents;
(I made this as one-line as possible because I tested it in my bot's eval slash command, but what it does is pretty simple, imports d.js, gets the keys of the discord.Intents.FLAGS, makes an empty array to hold them, loops through the intents and pushes it to the array, then outputs the list of intents.)
Which should output
"GUILDS","GUILD_MEMBERS","GUILD_BANS","GUILD_EMOJIS_AND_STICKERS","GUILD_INTEGRATIONS","GUILD_WEBHOOKS","GUILD_INVITES","GUILD_VOICE_STATES","GUILD_PRESENCES","GUILD_MESSAGES","GUILD_MESSAGE_REACTIONS","GUILD_MESSAGE_TYPING","DIRECT_MESSAGES","DIRECT_MESSAGE_REACTIONS","DIRECT_MESSAGE_TYPING","GUILD_SCHEDULED_EVENTS"
though I'm not sure if you really want or need every intent.
i'm just newbie on nodeJs ,and i need your help
my utile.js file :
const fs = require('fs');
const addNotes = function(name,age,birthday){
const notesExist = loadNotes()
notesExist.push({
name: name,
age: age,
birthday:birthday
})
}
const loadNotes = function (){
try{
binaryVersion = fs.readFileSync('./JsonFile/data.json');
stringVersion = binaryVersion.toString();
dataParsed = JSON.parse(stringVersion);
return dataParsed;
}
catch(err){
return [];
}
}
module.exports = {
addNotes: addNotes,
loadNotes: loadNotes
}
my intro.js file
yargs = require('yargs');
const utile = require('./utile.js');
yargs.command({
command: 'add',
describe: 'Adding new record',
builder:{
name:{
describe:'note name',
demandOption:true, // title option to be requires in the command line
type:'string' //requie a string as title value
},
age:{
describe:'note age',
demandOption:true,
type:'string' //require astring as body value
},
birthday:{
describe:'note birthday',
demandOption:true,
type:'string' //require astring as body value
},
},
handler: function(argv){
// console.log(chalk.green(chalk.red(argv.title)))
/* console.log(chalk.green(chalk.green(argv.body))) */
utile.addNotes(argv.name,argv.age,argv.birthday);
}
});
my data.json file :
{"name":"Hannani","age":25,"birthday":1995}
But when i run the intro.js file by : node intro.js add --name="booktitle" --age="dsds" --birthday="1995" i got i nice erro [I spent 3 hours but i didn't find anything to solve that error ]
Error :
/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1195
else throw err
^
TypeError: notesExist.push is not a function
at Object.addNotes (/home/simo/Documents/nodeJs/utile.js:34:20)
at Object.handler (/home/simo/Documents/nodeJs/intro.js:56:19)
at Object.runCommand (/home/simo/Documents/nodeJs/node_modules/yargs/lib/command.js:240:40)
at Object.parseArgs [as _parseArgs] (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1107:41)
at Object.parse (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:566:25)
at Object.<anonymous> (/home/simo/Documents/nodeJs/intro.js:86:7)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
ps: I didn't change anything in my yargs.js file ..
Please what i'm doing wrong ? Thanks in advance !
THe data.json needs to be array format for you to be able to push. Something like this
[{"name":"Hannani","age":25,"birthday":1995}]
Also, since it is a normal json file you could simply require it as will instead of using fs to read it.
const data = require('./JsonFile/data.json')
Hope this helps.
I am trying to create a bot, which will be given the role when user joins the server by link, but this doesn't work.
Error:
C:\DGhostsBot\bot.js:45
bot.on("guildMemberAdd", (member) => {
^
ReferenceError: bot is not defined
at Object.<anonymous> (C:\DGhostsBot\bot.js:45:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
My code here:
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = "dg!"
client.login(`**************************************************************`);
client.on("message", (message) => {
if(message.content == prefix + "test") {
message.reply("just a command that is used for performance testing. Do not pay attention.");
}
});
client.on("message", (message) => {
if(message.content == prefix + "cake") {
message.reply("here's your cake :3 :cake: ");
}
});
client.on("message", (message) => {
if(message.content == prefix + "help") {
message.reply("it's in development");
}
});
client.on("message", (message) => {
if(message.content == prefix + "kick") {
if(message.member.roles.some(r=>["Developer", "devadmin"].includes(r.name)) ) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member.kick()
}
}
} else {
message.reply("!!!!ACCESS_DENIED!!!!").then(sentMessage => sentMessage.delete("delete"));
}
}
});
bot.on("guildMemberAdd", (member) => {
if (member.id == bot.user.id) {
return;
}
let guild = member.guild
guild.fetchInvites().then(invdat => {
invdat.forEach((invite, key, map) => {
console.log(invite.code)
if (invite.code === "qQAkqFQ") {
return member.addRole(member.guild.roles.find(role => role.name === "Member"));
}
})
})
});
I check a lot of answers on the internet, but nothing of all this doesn't work.
So, I do not know how to fix this error.
Instead of bot use client like you did all the times before.
There are people who do const client = new Discord.Client(); but there are also people who name it bot or even something really weired.
If you want to learn how to make your own bot, you can use the open-source guide created by the members and creators of discord.js wich can be found here: https://discordjs.guide/
You have to change bot.on(...) to client.on(...)
You didn't define bot in previous code, so you can't use it. You defined your Discord client as client in the following line:
const client = new Discord.Client();
That's why you have to use client. You can't create a listenener for a non existing client.
For further details about all events of Discord.js, you can have a look at the official discord.js documentation: https://discord.js.org/#/docs/main/stable/class/Client
There you can also find all details on how to listen to events etc.
I am trying to deploy my functions but that shows an error. I am trying to use cloud speech api & cloud translation api with firebase cloud function.
const functions = require('firebase-functions');
const Speech = require('#google-cloud/speech');
const Translate = require('#google-cloud/translate');
const speech = Speech({keyFilename: "credentials.json"});
const translate = Translate({keyFilename: "credentials.json"});
const Encoding = Speech.v1.types.RecognitionConfig.AudioEncoding;
function getLanguageWithoutLocale(languageCode) {
if (languageCode.indexOf("-") >= 0) {
return languageCode.substring(0, languageCode.indexOf("-"));
}
return languageCode;
}
exports.onUpload = functions.database
.ref("/uploads/{uploadId}")
.onWrite((event) => {
let data = event.data.val();
let language = data.language ? data.language : "en";
let sampleRate = data.sampleRate ? data.sampleRate : 16000;
let encoding = data.encoding === "FLAC" ? Encoding.FLAC : Encoding.AMR;
let request = {
config: {
languageCode : language,
sampleRateHertz : sampleRate,
encoding : encoding
},
audio: { uri : `gs://mimming-babelfire.appspot.com/${data.fullPath}` }
};
return speech.recognize(request).then((response) => {
let transcript = response[0].results[0].alternatives[0].transcript;
return event.data.adminRef.root
.child("transcripts").child(event.params.uploadId)
.set({text: transcript, language: language});
});
});
exports.onTranscript = functions.database
.ref("/transcripts/{transcriptId}")
.onWrite((event) => {
let value = event.data.val();
let transcriptId = event.params.transcriptId;
let text = value.text ? value.text : value;
let languages = ["en", "es", "pt", "de", "ja", "hi", "nl", "fr", "pl"];
// All supported languages: https://cloud.google.com/translate/docs/languages
let from = value.language ? getLanguageWithoutLocale(value.language) : "en";
let promises = languages.map(to => {
console.log(`translating from '${from}' to '${to}', text '${text}'`);
// Call the Google Cloud Platform Translate API
if (from === to) {
return event.data.adminRef.root
.child("translations").child(transcriptId).child(to)
.set({text: text, language: from});
} else {
return translate.translate(text, {
from: from,
to: to
}).then(result => {
// Write the translation to the database
let translation = result[0];
return event.data.adminRef.root
.child("translations").child(transcriptId).child(to)
.set({text: translation, language: to});
});
}
});
return Promise.all(promises);
});
I installed #google-cloud/speech and #google-cloud/translate in npm.
it shows error
Error: Error occurred while parsing your function triggers.
TypeError: Speech is not a function
at Object.<anonymous> (C:\Users\Akash\AndroidStudioProjects\Translator\functions\index.js:6:16)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at C:\Users\Akash\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:18:11
at Object.<anonymous> (C:\Users\Akash\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:38:3)
please help me to find the error if anyone knows. Thank you in advance
It's complaining about this line:
const speech = Speech({keyFilename: "credentials.json"});
You're using Speech as if it's a function, but it's not a function.
Looking at the documentation, it seems that you're supposed to initialize it like this:
const speech = require('#google-cloud/speech');
const client = new speech.SpeechClient();