Hello, I had this problem like 1 week ago, and still can't solve it. So, I'm trying to do per-server prefixes, but when I boot up the bot, it sends the boot-up confirmation message, but then it says the error and it shuts down. Here is the error:
guildPrefixes[guildId] = result.prefix
^
TypeError: Cannot read property 'prefix' of null
I can't see anything wrong here, but anyways, here is the code:
module.exports.loadPrefixes = async (client) => {
await mongo().then(async (mongoose) => {
try {
for (const guild of client.guilds.cache) {
const guildId = guild[1].id
const guildPrefixes = {}
const result = await commandPrefixSchema.findOne({_id: guildId})
guildPrefixes[guildId] = result?.prefix || dprefix
console.log(result)
}
console.log('[INFO] Prefixes have been loaded')
} finally {
mongoose.connection.close()
}
})
}
Related
This is the error I am getting when I try to deploy the code:
Error: ERROR processing /home/anooj-patnaik/hh-fcc/hardhat-fund-me-fcc/deploy/00-deploy-mocks.js:
TypeError: Cannot read properties of undefined (reading 'length')
const { network } = require("hardhat")
const {
developmentChains,
DECIMALS,
INITIAL_ANSWER,
} = require("../helper-hardhat-config")
module.exports = async ({ getNamedAccounts, deployments }) => {
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
if (developmentChains.includes(network.name)) {
log("Local Network Detected! Deploying Mocks...")
await deploy("MockV3Aggregator", {
contract: "MockV3Aggregator",
from: deployer,
log: true,
args: [DECIMALS, INITIAL_ANSWER],
})
log("Mocks deployed")
log("---------------------------")
}
}
module.exports.tags = ["all", "mocks"]
I have defined all the variables in a hardhat-helper-config.js and hardhat.config.js. The MockV3Aggregator is in a separate contract
Tried to deploy the code above and faced with an error
When you call await getNamedAccounts(), it looks in your hardhat.config.js for the namedAccounts section, and reads the length of the named accounts.
You'll want to make sure this is in there!
namedAccounts: {
deployer: {
default: 0, // here this will by default take the first account as deployer
},
},
So you may have seen this question type somewhere else. but the thing here is I tried all of the things we need to do according to docs and saw other posts with similar errors but still my error is not fixed. So I use keyv and use MongoDB atlas as storage adapter in this code, but the error is from MongoDB. Also, there is no error in the "keyv" because it works for other people, there is error in the MongoDB
So now I will list whatever I tried:
1. Made sure there is IP access
2. The userid and passcode are correct
3. The MongoDB atlas is running
4. Read the docs and code multiple times
5. If u think adding the +srv with the code will fix the error, it won't, it doesn't work with keyql idk why also it is not present in many codes, I already tried it
So this is the code
const { Client, Intents, MessageEmbed, Collection } = require('discord.js');
let client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
const dotenv = require('dotenv');
const Keyv = require('keyv');
const keyv = new Keyv('mongodb://Discord:password#cluster0.auifa.mongodb.net/Cluster0');
dotenv.config();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (msg) => {
if (msg.author.bot) return;
let number = msg.content.split(' ')[1];
if (msg.content === '!ping') {
msg.channel.send('ping!')
}
// Use like const prefix = await getGuildPrefix(); `
const getGuildPrefix = async () => {
const prefixMap = await keyv.get('prefix');
return prefixMap ?. [msg.guild.id] || "!"
}
// Sets the prefix to the current guild.
const setGuildPrefix = async (prefix) => {
let prefixMap = await keyv.get('prefix');
if (!prefixMap)
{
prefixMap = "!";
}
prefixMap[msg.guild.id] = prefix;
await keyv.set('prefix', `${prefixMap}`);
}
let prefix = await getGuildPrefix();
// Get prefix command.
if ((msg.content === `${process.env.prefix}prefix`) || (msg.content === `${prefix}prefix`)) {
msg.channel.send(`Your server prefix is ${prefix}`)
}
// Change prefix command
const commandPrefix = await getGuildPrefix();
if ((msg.content.startsWith(`${process.env.prefix}setprefix`)) || (msg.content.startsWith(`${commandPrefix}setprefix`))) {
const newPrefix = number;
if (newPrefix.length === 0) {
msg.channel.send(`Please enter a valid prefix`);
}
await setGuildPrefix(newPrefix)
msg.channel.send(`Your server prefix is now '${newPrefix}'`);
}
})
client.login(process.env.token);
And this is the error message
Keyv connection error: MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.auifa.mongodb.net
at Timeout._onTimeout (D:\javascript\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription
Connection string does not look like an Atlas one.
It has to be something like: mongodb+srv://<username>:<password>#cluster0.auifa.mongodb.net/YOUR-DB
Login to your Atlas account then:
Go to Databases page
Click on Connect button
Choose "Connect your application"
Copy your connection string
Docs about Mongo Atlas connection: https://docs.atlas.mongodb.com/connect-to-cluster/#connect-to-a-cluster
So I was making a selfbot (bc why not) and I finished the first command.
It should work but it doesn't
Here's the code:
const Discord = require("discord.js");
const fs = require("fs");
const ConsoleTitle = require("node-bash-title");
const bot = new Discord.Client({disableEveryone: true});
ConsoleTitle("Slefx")
bot.on("ready", async () => {
console.log("Ready!");
setTimeout( () => {
console.log("Ready to go!");
}, 2000)
})
bot.on("message", async () => {
if(message.content === "!embed sus" ) return message.channel.send("https://embed.rauf.workers.dev/?author=Sussy&title=Bakka%2520B%29&description=Fuck%2520you%2520B%29&image=https%253A%252F%252Fmedia.sketchfab.com%252Fmodels%252F230ec756288e444c8e07f486ef9e8786%252Fthumbnails%252Feb28075b3cbe419bab000bd898b6f6ef%252F9d87472aded94922929162557fcec2d6.jpeg&redirect=https%253A%252F%252Ftherickroll.com");
})
bot.login("hahaucanloginwithmyaccountbecauseireplacedmycookiewiththis")
And here's the error:
Uncaught TypeError: Cannot read property 'id' of undefined
Alright have a good day if u see this :D.
You probably need to check where the error is coming from, as you code does not have any 'id'. Would be better if you could check the logs.
I shall start this question with, i'm a beginner for discord.js, and please help me!
My whole index.js is:
const Discord = require('discord.js');
const client = new Discord.Client();
const botsettings = require('./botsettings.json')
client.once('ready', () => {
console.log("Ready!");
});
client.on("message", async message =>{
const playminecraftwithus = message.guild.channels.cache.find(channel => channel.name === 'play-minecraft-with-us')
if(playminecraftwithus.content.startsWith("IGN:")) {
return;
} else {
message.delete();
}
});
client.login(botsettings.token);
and the problem is in this block:
client.on("message", async message =>{
const playminecraftwithus = message.guild.channels.cache.find(channel => channel.name === 'play-minecraft-with-us')
if(playminecraftwithus.content.startsWith("IGN:")) {
return;
} else {
message.delete();
}
});
but error message is like:
(node:13811) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined | discord.js
If you need anything else, please tell me!
I think you meant to type message.content.startsWith() instead of playminecraftwithus.content.startsWith().
playminecraftwithus.content is undefined.
undefined has no method startsWith()
if you want to avoid an error, you could convert to string and use it.
Try this: (playminecraftwithus.content || "").startsWith()
|| means that when previous one is undefined use next. more details on here
{"success":true,"lastUpdated":1598982272495,"products":{"BROWN_MUSHROOM":{"product_id":"BROWN_MUSHROOM","sell_summary":[{"amount":160,"pricePerUnit":13.9,"orders":1},{"amount":28503,"pricePerUnit":13.8,"orders":2},{"amount":71483,"pricePerUnit":13.4,"orders":3},
this is what the api says so i assumed that i could directly get the "pricePerUnit. But I am getting the error TypeError: Cannot read property 'pricePerUnit' of undefined
My code is: ```client.on("message", message => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "bazaar") {
let product = args[0];
fetch(`https://api.hypixel.net/skyblock/bazaar/product?key=${key}`)
.then(result => result.json())
.then(({ BROWN_MUSHROOM }) => {
// Log the player's username
message.reply(BROWN_MUSHROOM.pricePerUnit)
})
}
})```
anybody know how to help?
Try modifying your last block to this:
.then(({ products: { BROWN_MUSHROOM } }) => {
// Log the player's username
message.reply(BROWN_MUSHROOM.pricePerUnit)
})
since BROWN_MUSHROOM appears to be under products field.