const Discord = require('discord.js');
const bot = new Discord.Client();
let cofig = require('./botconfig.json');
let token = config.token;
let prefix = config.prefix;
bot.on('ready', () => {
console.log(`Запустился бот ${bot.user.username}`);
});
bot.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
}
});
bot.login(token);`
My bot is supposed to answer by Pong! when I type the ping in a channel. It's a simple ping test to check if the bot is alive and behave correctly. However I have an error when I try to make it work.
Error:
SyntaxError: C:\Users\mrakp\OneDrive\Рабочийстол\mamapapads\botconfig.json: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.Module._extensions..json (internal/modules/cjs/loader.js:801:27)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:683:19)
at require (internal/modules/cjs/helpers.js:16:16)
at Object.<anonymous> (C:\Users\mrakp\OneDrive\Рабочий стол\mamapapads\bot.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
Well first off, you can't do
const cofig = require("./botconfig.json")
Then not use the declaration in order to get the token.
In your case, bot.login(token) would actually be bot.login(cofig.token)
But you can also do
const { token } = require("./botconfig.json")
//Rest of code
bot.login(token)
Which would get the token directly, instead of having to use a declaration in order to reference it.
Related
I am getting error when using web3.js to get the balance of an account. I am using ganache. My code is below,
var Web3 = require("web3");
//connect with ganache
const ganacheWeb3 = new Web3(
new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")
);
console.log(ganacheWeb3);
//check the balance of an account
const balanceOfAccount = Web3.Eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"
);
console.log(
balanceOfAccount.then((result) =>
console.log(Web3.utils.fromWei(result, "ether"))
)
);
Web3.eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5",
(error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
);
I have used the normal functional way and callback way. I don't know which one is correct. But still I am getting error. The error is,
const balanceOfAccount = Web3.Eth.getBalance(
^
TypeError: Cannot read properties of undefined (reading 'getBalance')
at Object.<anonymous> (D:\Blockchain Development\Web3.js\intro-to-web3.js\index.js:10:35)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I am trying to get the value of an ethereum account. But getting an error.
Change Web3.Eth.getBalance(...) to Web3.eth.getBalance(...).
Documentation: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getbalance
My Code
const Discord = require("discord.js")
require("dotenv").config()
const Token = "*MY VALID TOKEN*"
const client = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS"
]
})
client.on("ready", () =>{
console.log(`Logged in as ${client.user.tag}`)
})
client.on("messageCreate", (message) => {
if (message.content == "hi!"){
message.reply("Hello")
}
})
const welcomeChannelID = "935422032458444901"
client.on("guildMemberAdd", (member) =>{
member.guild.channels.cache.get(welcomeChannelID).send(`<#${member.id}> Welcome to the Server!`)
})
client.login(process.env.Token)
The Error
D:\DBS\node_modules\discord.js\src\client\websocket\WebSocketManager.js:129
const invalidToken = new Error(WSCodes[4004]);
^
Error [TOKEN_INVALID]: An invalid token was provided.
at WebSocketManager.connect (D:\DBS\node_modules\discord.js\src\client\websocket\WebSocketManager.js:129:26)
at Client.login (D:\DBS\node_modules\discord.js\src\client\Client.js:254:21)
at Object.<anonymous> (D:\DBS\index.js:29:8)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
[Symbol(code)]: 'TOKEN_INVALID'
}
Node.js v17.3.0
I have Checked and Double checked my token, and it IS valid, There is something wrong in my code, can you please help me figure it out? thanks!
.......................................................
If you are using client.login(process.env.Token), then you should have a .env file where you put your token inside. If you're putting your token at
const Token = "*MY VALID TOKEN*"
Then simply just do client.login(Token);
Your token should be in .env file following format:
Token=YourTokenIsHere
For example:
Token=cjKFmWWHeabkY5cjKFmWWHeabkY5cjKFmWW
Not real token in example
Make sure you have the correct token from the Developer Portal
I am trying to make a discord bot for my server and everytime I try to start the bot it gives me the same error every time.
I haven't tried anything else because a google search does not find the error.
I was following a YouTube video that was made in 2017.
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var prefix = config.prefix;
//Startup
client.login(config.token);
client.on("ready", () => {
console.log(`Online ${new Date()}`);
client.user.setGame("Online");
});
client.on("message", async message => {
//Ingore bots
if(message.author.bot) return;
//Prefix in command
if(message.content.indexOf(config.prefix) !==0) return;
const args = message.content.slice(config.prefix.legth).trim().split(/
+/g);
const command = args.shift().toLowerCase();
if (command === "ping") {
message.reply("Pong!");
}
});
I expected the bot to start fully but gave me the following error
"internal/modules/cjs/loader.js:800
throw err;
^
SyntaxError: C:\Users\adoss\Desktop\DiscordBot\config.json: Unexpected
string in JSON at position 37
at JSON.parse (<anonymous>)
at Object.Module._extensions..json
(internal/modules/cjs/loader.js:797:27)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\adoss\Desktop\DiscordBot\bot.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"
I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789
I'm new to programming and I wanted to make a discord bot using Atom and Javascript. I had some previous programming experience, but not much. I tried to find help through other Q/A's with the same error code but I still can't figure out why my program doesn't work. I found how to write this online.
My program is:
const Discord = require("discord.js");
const Config = require("./config.json");
const Token = require("./token.json");
const bot = new Discord.Client({disableEveryone: true})
bot.on("ready", async () =>{
console.log(`${bot.user.username} is online! It's running on
${bot.guild.size} servers!`);
bot.user.setActivity("Work in Progress", {type: "WATCHING"}); })
bot.on("message", async message => {
if{message.author.bot} return;
if(message.channel.type === "dm") return;
message.channel.send("Swift bot testing...") })
bot.login(Token.token);
When I tried to run it with node on Windows Powershell by entering "node app.js", it returned with the error message:
SyntaxError: Unexpected token { at createScript (vm.js:80:10) at
Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10) at Module.load
(module.js:566:32) at Function.Module._load (module.js:498:3) at
Function.Module.runMain (module.js:694:10) at startup
(bootstrap_node.js:204:16) at bootstrap_node.js:625:3
I don't understand what is wrong! Somebody please help me get my program running.
You have a problem in if:
if{message.author.bot} return;
vs
if(message.author.bot) return;