discord.js bot restarting for no clear reason
for the past several weeks, my bot has been restarting for no reason what-so-ever. there is nothing in the logs stating any sort of error, the shards just keep restarting and it hits the 1000 login limit every 3-5 hours. what am I doing wrong?
sharding code incase:
const {ShardingManager, Shard} = require("discord.js");
const botsettings = require('./botsettings.json');
const manager = new ShardingManager("./bot.js", {
token: botsettings.token,
totalShards: "auto",
});
manager.on('shardCreate', shard => {
console.log(`[${new Date().toString().split(" ", 5).join(" ")}] Launched shard #${shard.id}`);
})
manager.on('ready', () => {
console.log('Shard ready').catch(console.error);
})
manager.on('disconnect', (a, b) => {
console.log('Shard disconnected').catch(console.error);
console.log(a)
console.log(b)
})
manager.on('reconnecting', (a, b) => {
console.log('Shard reconnecting').catch(console.error);
console.log(a)
console.log(b)
})
manager.on('death', (a, b) => {
console.log('shard died').catch(console.error);
console.log(a)
console.log(b)
})
manager.spawn(this.totalShards, 5500, -1)
See also questions close to this topic
-
Is it possible to have an onclick() inside a functional component that executes a function of the caller in Javascript?
Hey there I'm new to Javascript and I've been looking through the forum to find an answer to my problem. I have a functional component that I call and inside of that one I want to place a button, the problem is that the function I want to call is in the file of the caller, so I always get an error. I tried multiple solutions including a function handler but it didn't work. Now I try it here, maybe someone knows something about that.
-
Return modified array after adding one element at certain position
Is there any function which inserts value at certain index and returns modified array like
filter
ormap
?I already tried
array.splice(item, 0, index)
but it returns[]
instead of modified array -
Getting an error while trying to interact with a server using socket io with node js and a react frontend
I am getting this error on the frontend.
Access to XMLHttpRequest at 'http://localhost:6969/socket.io/?EIO=4&transport=polling&t=NWJnNb2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The socket io documentation says that if the server is configured properly then it probably happens because the browser isnt able to reach the Socket.io server and in that case the following command:
curl "https://api.example.com/socket.io/?EIO=4&transport=polling"
is going to return something similar to this:
0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
and it did.(I replaced the
https://api.examle.com
part withhttp://localhost:6969
and it returned a similar output in the console)But the documentation never explains what to do in case this actually happens and it only says "this could mean that your browser wasn’t able to reach the Socket.IO server." How do I fix it?
Here is the server code if it helps:
const express = require('express'); const app = express(); const cors = require('cors'); const socket = require('socket.io'); require('dotenv').config(); app.use(cors({ origin: '*' })); const server = app.listen(process.env.PORT, (): void => { console.log('Server listening on port ' + process.env.PORT); }); const io = socket(server); io.on('connection', (s: any) => { s.on('join', (data: any) => { console.log(data); }); s.on('disc', (data: any) => { console.log(data); }); });
And here is the frontend React code:
import React, { useState, useEffect } from 'react'; import io from 'socket.io-client'; const App = () => { // let socket; const PORT = 'http://localhost:6969/'; const [state, setState] = useState({ username: '', room: '', }); const [socket, setSocket] = useState(''); useEffect(() => { setSocket(io('http://localhost:6969', { transport: ['websocket'] })); }, [PORT]); const handleChange = (e) => { setState((prev) => { return { ...prev, [e.target.name]: e.target.value, }; }); }; const Join = (e) => { socket.emit('join', state.room); console.log(socket); }; return ( <div> <input name='username' type='text' onChange={handleChange} /> <input name='room' type='text' onChange={handleChange} /> <button onClick={Join}>Join </button> </div> ); }; export default App;
-
Sending formdata from front-end to back end using Axios
i am trying to send an https request from my front-end(react js) to my back-end (nodejs) using axios.This https request has a csv file converted in formData.My code for sending teh request is this:
let formData = new FormData(); formData.append('file', this.state.selectedFiles); //selectedFiles is input from a ui form const {data : QueryResult} = await axios({ method: 'post', url: "https://localhost:3000/...",formData, headers: {'x-observatory-auth': localStorage.getItem("token")}, }); }
I process this in back end using :
function AddSessions(req,res){ let stream = fs.createReadStream("./upload_folder/upload_file.csv"); let csvData = []; let csvStream = fastcsv .parse() .on('error', function(error) { res.status(400).send("Incorrect Data format.Please enter a csv file"); return }) .on("data", function(data) { csvData.push(data); }) .on("end", function() { // remove the first line: header csvData.shift(); let insert_query = "INSERT IGNORE INTO Sessions(SessionID, StationID,PointID, Username, VehicleID, connectionTime,"+ " doneCharginTime, Timezone ,KwhDelivered ,Protocol,Payment ) VALUES ?"; db.query(insert_query, [csvData], (err, db_res) => { if (err) { res.status(400).send("Incorrect Data format for Sessions or File is too big(larger than 1GB)") console.log(err)} else{ let count_query = "SELECT Count(*) as count FROM Sessions"; db.query(count_query, (err1, result) => { if (err1) res.send(err1.message) else { res.status(200).send({SessionsInUploadedFile :db_res.affectedRows + db_res.warningCount , SessionsImported : db_res.affectedRows, TotalSessionsInDatabase :result[0].count}); } }) } }); } ); stream.pipe(csvStream); } } module.exports = AddSessions
The error i get is :
code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1", sqlState: '42000', index: 0, sql: 'INSERT IGNORE INTO Sessions(SessionID, StationID,PointID, Username, VehicleID, connectionTime, doneCharginTime, Timezone ,KwhDelivered ,Protocol,Payment ) VALUES '
and i can't seem to understand what i am doing wrong.
Note that using postman this request can be done fine.I've been stuck in this for way too long and i can;t find a solution so any help would be very welcome.
Thanks in advance.
-
Combine arrays in map function
I have an issue, or at least I'm not having the solution.
Im getting some API calls via a map and I can console.log all results which is great, but the problem is that I want to combine all the results in one array.
var alpha = ['a', 'b', 'c', 'd', 'e'];
alpha.map(alpha => { fetch(`https://myurl.com/api/members/page?prefix=${alpha}`) .then(res => res.json()) .then(data => matches.push) .then(() => console.log(matches)) })
I guess I have to do some sort of await or something?
-
bcrypt is causing POST request 500?
I have no idea why but I’ve started getting these errors on Vercel, but no issues on LocalHost, even doing
yarn build && yarn start
I have made sure that I'm using CORS in Next.js
And my api code
import bcrypt from 'bcrypt' import { NextApiRequest, NextApiResponse } from 'next' import { connectPrisma } from 'utils/connectPrisma' export default async (req: NextApiRequest, res: NextApiResponse) => { if (req.method === 'POST') { const { email, password } = req.body if (!email || !password) return res.status(422).json({ error: 'Please complete all fields' }) try { const { client } = await connectPrisma() const user = await client.user.findFirst({ where: { email } }) if (user) { return res.status(422).json({ error: `User already exists with that email` }) } const hashedPassword = await bcrypt.hash(password, 8) await client.user.create({ data: { email: email, password: hashedPassword } }) res.status(201).json({ message: 'Success test' }) } catch { res.status(500).json({ error: 'Unable to insert user' }) } return } return res.status(500).json({ error: 'Invalid request' }) }
As soon as i comment the
const hashedPassword = await bcrypt.hash(password, 8)
I'm able to do POST request
-
Discord bot codes not working (python). How can I fix it?
I recently started coding and decided a good, fun way to learn would be to make a Discord bot. So I did some coding, learnt from a Youtube video and it was all going well but now none of my codes are working and the bot is basically useless. Could someone please look at this code and tell me what's wro
import discord import os import requests import json import random client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('Hello'): await message.channel.send('Hi!') client.run(os.getenv('TOKEN')) sad_words = ["sad","alone","scared","depressed","SAD","Sad"] starter_encouragements = [ "You got this. I know you do 😁", "I know it's hard, but you'll get through this :)", ] def get_quote(): response = requests.get("https://zenquotes.io/api/random") json_data = json.loads(response.text) quote = json_data[0]['q'] + " -" + json_data[0]['a'] return(quote) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return msg = message.content if message.content.startswith('inspire'): quote = get_quote() await message.channel.send(quote) if any(word in msg for word in sad_words): await message.channel.send(random.choice(starter_encouragements)) client.run(os.getenv('TOKEN'))
Thanks so much
-
can't send an empty message
Hi I am trying to make a giveaway bot I have found this script online but I can't make it to work, when I config it as it says on GitHub and I try it out it comes with an error saying
[Giveaway] Started. [Giveaway] Starting a giveaway. [Giveaway] Giveaway details: [Giveaway] Channel: 805865272900583455 [Giveaway] Author: 361853762291105794 [Giveaway] Time: 5 [Giveaway] Item: 400k ingame monetos test test es C:\Users\Administrator\Desktop\Botten\node_modules\discord.js\src\rest\RequestHandler.js:154 throw new DiscordAPIError(request.path, data, request.method, res.status); ^ DiscordAPIError: Cannot send an empty message at RequestHandler.execute (C:\Users\Administrator\Desktop\Botten\node_modules\discord.js\src\rest\RequestHandler.js:154:13) at processTicksAndRejections (node:internal/process/task_queues:94:5) at async RequestHandler.push (C:\Users\Administrator\Desktop\Botten\node_modules\discord.js\src\rest\RequestHandler.js:39:14) { method: 'post', path: '/channels/805865272900583455/messages', code: 50006, httpStatus: 400
as you can see the console log is fine and i do not know how to resolve this as i have tried my best
here is the code
const Discord = require('discord.js'); const ms = require("ms"); /** * @param {Discord.Client} client - the discord's client * @param {object} options - options of the package */ module.exports = async function(bot, options) { class Giveaway { constructor(bot, options = {}) { this.botPrefix = (options && options.prefix) || '!'; this.startCmd = (options && options.startCmd) || 'giveawaystart'; this.giveawayRole = (options && options.giveawayRole) || null; this.embedColor = (options && options.embedColor) || '#7aefe0'; this.reactEmote = (options && options.reactEmote) || `✅` } } var giveawayBot = new Giveaway(bot, options); giveawayBot.log = (msg) => { const loggableMsg = msg.split("\n").map(function(e) {return '[Giveaway] ' + e}).join("\n") console.log(loggableMsg) } async function start() { if (typeof giveawayBot.giveawayRole !== 'string' && giveawayBot.giveawayRole !== null) throw new TypeError(`giveawayRole must be a string`); giveawayBot.log("Started.") bot.on("message", async message => { if(!message.content.startsWith(giveawayBot.botPrefix)) return; const msgArray = message.content.slice(giveawayBot.botPrefix.length).split(" ") const command = msgArray[0] const args = msgArray.slice(1) switch(command) { case giveawayBot.helpCmd: giveawayBot.help(message); break; case giveawayBot.startCmd: giveawayBot.start(message, args); break; default: giveawayBot.log("Not matching command.") break; } }) } if(bot.readyTimestamp) { start() } else { bot.on("ready", () => { start() }) } giveawayBot.help = (message) => { } giveawayBot.rollIt = (randomNumber, values) => { for (let i = 0; i < randomNumber; i++) { if(i == randomNumber - 1) { return values.next(); } else { values.next() } } } giveawayBot.start = (message, args) => { let doesHaveRole if(giveawayBot.giveawayRole == null) { doesHaveRole = true } else { doesHaveRole = message.member.roles.cache.find(r => r.id === giveawayBot.giveawayRole) } if(!doesHaveRole) return message.reply("you don't have the required role to do that.") giveawayBot.log("Starting a giveaway.") const channel = message.channel, time = ms(args[0]), item = args.slice(1).join(" "); if(isNaN(time)) return message.reply("make sure to provide correct time.").then(msg => msg.delete(5000)) if(item == undefined || item == null || item.length < 1) return message.reply("you didn't specify what do you want to give away.").then(msg => msg.delete(5000)) giveawayBot.log(`Giveaway details:\n Channel: ${message.channel.id}\n Author: ${message.author.id}\n Time: ${time}\n Item: ${item}`) const første = new Discord.MessageEmbed() .setColor(giveawayBot.embedColor) .setTitle(item) .setDescription(`Ends in: ${ms(time)}`) .setAuthor(message.author.tag, message.author.displayAvatarURL) .setTimestamp() .addField(`React with the ${giveawayBot.reactEmote} emote`, `to take part in this giveaway.`) .setFooter(bot.user.username, bot.user.displayAvatarURL) message.channel.send(første).then(async msg => { await msg.react(giveawayBot.reactEmote) const timeInterval = setInterval(function() { console.log(ms(msg.embeds[0].description.slice(9))) if(ms(msg.embeds[0].description.slice(9)) <= 5000) { const anden = new Discord.MessageEmbed() .setColor(giveawayBot.embedColor) .setTitle(item) .setDescription(`Ended.`) .setAuthor(message.author.tag, message.author.displayAvatarURL) .setTimestamp(msg.embeds[0].timestamp) .setFooter(bot.user.username, bot.user.displayAvatarURL) msg.edit(anden) clearInterval(timeInterval) } else { const tredje = new Discord.MessageEmbed() .setColor(giveawayBot.embedColor) .setTitle(item) .setDescription(`Ends in: ${ms(ms(msg.embeds[0].description.slice(9)) - 5000)}`) .setAuthor(message.author.tag, message.author.displayAvatarURL) .setTimestamp(msg.embeds[0].timestamp) .addField(`React with the ${giveawayBot.reactEmote} emote`, `to take part in this giveaway.`) .setFooter(bot.user.username, bot.user.displayAvatarURL) msg.edit(tredje) } }, 5000) setTimeout(function() { msg.channel.fetchMessage(msg.id).then(mesg => { const reactions = mesg.reactions.find(reaction => reaction.emoji.name == giveawayBot.reactEmote) giveawayBot.log(`Reaction count: ${reactions.count}.`) const randomNumber = Math.floor(Math.random() * (reactions.count - 1)) + 1; let values = reactions.users.filter(user => user !== bot.user).values() const winner = giveawayBot.rollIt(randomNumber, values).value if(winner == undefined) return mesg.channel.send("No one reacted to the message, so no one wins."); mesg.channel.send(`The winner of \`${item}\` is... <@${winner.id}>!`) }) }, time) }) } return giveawayBot; }
and this is in my index file
const Giveaway = require("discord.js-giveaway"); const giveaway = Giveaway(bot, {})
-
Using Classes for Discord Bots
I wanted to make a Poker Bot with python for discord so that I can play with my friends. I've never made a discord bot yet and I started to look around for some tutorials. What I found is that most of the people are not using classes for their bots. Are there any reasons for not using a class? My suggestion was to use for example a class for the player and a class for the game manager. Does anyone have a better idea how to implement a Poker Bot or can anyone tell me how to properly use classes to create a discord bot? Or is it maybe better to use another language for this project?
Thanks for your time
-
My code only seems to be working with some subreddits
It works with "memes" and some other subreddits but not with "kungenavedsbyn". I'm probably really dumb but I can't figure out how to fix it.
bot.on('message', async msg => { if (msg.content === '-örsk') { let subreddits = [ "kungenavedsbyn" ]; let subreddit = subreddits[Math.floor(Math.random()*(subreddits.length))]; let img = await api(subreddit) const Embed = new Discord.MessageEmbed() .setTitle(`Här har du lite örsk`) .setURL(`https://www.reddit.com/r/kungenavedsbyn`) .setColor('RANDOM') .setImage(img) msg.channel.send(Embed) } });
Here's the message I get when I write the command in dc:
(node:11700) UnhandledPromiseRejectionWarning: err: [object Object] (Use
node --trace-warnings ...
to show where the warning was created) (node:11700) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async functioch(). To terminate the node process on unhandled promise rejection, use the CLI flag--unhandled-rejections=strict
(see https://nodejs.org/ap (node:11700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled -
Message cache not updating immediately after edit
The message cache doesn't always update immediately after editing, is this intentional?
If I run the below code multiple times, I get inconsistent results. Fetched after edit is sometimes the old content.
var channel_id = '' var msg_id = '' ;(async () => { var channel = await client.channels.fetch(channel_id ) var msg = await channel.messages.fetch(msg_id ) console.log('before edit:', msg.content) console.log('edited:', (await msg.edit(parseInt(msg.content, 10) + 1)).content) msg = await channel.messages.fetch(msg_id) console.log('fetched after edit:', msg.content) })()
Note I start off with a message with content '1' for the above.