#development
1 messages Β· Page 954 of 1
o
you want to redefine the value of a variable you passed?
I just wanna map the error from the try catch block to the function callback
if callback is a function, then you need to call it, not define it
or THROW an error idk
but like
that's literally what I just said
its an async function, why use a callback?
yeah
I'm not very good with async sorry, the promise never fails thats the issue I think
I cant seem to get .catch to work on it
...
sorry bro lmao, I know I'm stupid rn, sometimes my brain doesnt work
@magic jackal ```js
async function bla() {
throw 123;
}
try {
await bla()
} catch(e) {
console.log(e) /// 123
}
bla().catch(e => console.log(e)) // 123
async function f() {
return 1;
//this does not wait at all, but I'll just prove a point
}
let x = await f(); //assuming the current scope is async
this is the same as doing
f().then
I'm on my phone
holy fuck
I guess Tim's got this lol
mk I see
lmao
lol
Honestly not sure whats wrong here, all of the files are formatted the same, anyone know whats wrong?
at C:\Users\Samst\IdeaProjects\ClockMaster\index.js:64:41 at Array.forEach (<anonymous>) at C:\Users\Samst\IdeaProjects\ClockMaster\index.js:61:16 at FSReqCallback.oncomplete (fs.js:155:23)``` ```js jsfile.forEach((f, i) => { let props = require(`./Commands/${f}`); console.log(`${f} loaded!`); bot.commands.set(props.help.name, props) }) });``` ```js module.exports.help = { name: "wcsetup" }module.exports.help = { name: "convert" }```
@gritty bolt
are you sure all of them are?
and all of them are properly saved?
maybe one of them doesnt have a help object or you forgot to save it
if you want to remove it from the middle, string.replace("word","")
ok so you know dadbot
from the beginning or end, you can use string.slice()
alright thanks
nope still not working @quartz kindle
I have no idea what could possibly be wrong
they all look the same
@gritty bolt well thats what the error says it wrong, and errors dont lie
you can add a console.log to see which one is it
i've found which ones they are
it goes in order
but i've sifted through all of them and it's the same piece of code just with different stuff in the "s
aha i found it
also check if you didnt misspell module.exports somewhere
can you no longer create emojis using discord.js?
s
<vc>.leave()
thank
@earnest phoenix you can't just yardim botum outside of #commands
@misty sigil iirc ofc
I'm not sure tho
How do you guys make your admin web panel's for bot's over 1k servers?
ugh, i think my admin dashboard needs a hell of a lot of work
the copyright notice at the bottom says 2004, and it certainly looks like it
1k servers how?
in case youre wondering, this is ALL table layouts and colours/styling inside the html tags as color attributes.
Anyone knows how I get the data from my MYSQL database where id = a certain value and item is not?
I tried WHERE id = "id" AND NOT item = "item"Β΄
But that doesnt work
<>
?
So WHERE id = id AND item <>"item"
Yeah
you can also use !=
which i find more readable, but thats because of C++, PHP, javascript
help me pls
Try npm i?
I use the glitch: c
how do i convert
[ [ 'hello', [ 'How', 'Are', 'You' ] ] ]
to
[ { 'hello': [ 'How', 'Are', 'You' ] } ]
(Array to object)
Is there a way or do i have to custom code it?
you probably have to implement it yourself
although if the outer structure is still an array you don't really get any benefit of using an object inside
aight thanks
someone help me pls
name checks out
-ask2ask
Don't ask to ask.
Just ask your question, it wastes time if you say "i need help" or "can someone help me?" instead of just saying what the problem is. Save your time and other people's time and just ask the question.
Please read https://dontasktoask.com/ for an explanation on why this is an issue.
they asked above
smh
@cerulean hornet https://support.glitch.com/t/error-can-not-find-bindings-file/7085
module.exports = {
name: "warn",
description: "Warn a user",
category: "mod",
usage: "<User mention> <Reason>",
run: async (bot, message, args) => {
let user = message.mentions.users.first();
if (!user) return message.channel.send(`You did not mention a user!`);
if (!args.slice(1).join(" "))
return message.channel.send(`You did not specify a reason!`);
warns.findOne(
{ Guild: message.guild.id, User: user.id },
async (err, data) => {
if (err) console.log(err);
if (!data) {
let newWarns = new warns({
User: user.id,
Guild: message.guild.id,
Warns: [
{
Moderator: message.author.id,
Reason: args.slice(1).join(" "),
},
],
});
newWarns.save();
message.channel.send(
`${user.tag} has been warned with the reason of ${args
.slice(1)
.join(" ")}. They now have 1 warn.`
);
} else {
data.Warns.unshift({
Moderator: message.author.id,
Reason: args.slice(1).join(" "),
});
data.save();
message.channel.send(
`${user.tag} has been warned with the reason of ${args
.slice(1)
.join(" ")}. They know have ${data.Warns.length} warns.`
);
}
}
);
},
};```
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:268) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
error ^
da fuq did i do wrong
you didnt show the error
i didnt?
you didnt
uh let me try to realod it and see if it shows it
hol dup
both successfully load without error
when executed they dont work and they throw an error
idk what the error is tho
you need mongo/mongoose
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (/home/runner/nypsi/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/nypsi/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/nypsi/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/home/runner/nypsi/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/home/runner/nypsi/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/home/runner/nypsi/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:310:20)
at Receiver.receiverOnMessage (/home/runner/nypsi/node_modules/ws/lib/websocket.js:800:20)
at Receiver.emit (events.js:310:20)
at Receiver.dataMessage (/home/runner/nypsi/node_modules/ws/lib/receiver.js:436:14)
at Receiver.getData (/home/runner/nypsi/node_modules/ws/lib/receiver.js:366:17)
at Receiver.startLoop (/home/runner/nypsi/node_modules/ws/lib/receiver.js:142:22)
(node:268) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:268) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
oh
lmfao
and discordjs
still everything but the error
how did you not install mongoose/mongo and made a mongo save im guessing
what
said*
what package are you using to save it
idk
are you just copying and pasting code
@river terrace and are you using mongodb as the database
and do you have a schema located at ..models/warns
@cerulean hornet https://support.glitch.com/t/error-can-not-find-bindings-file/7085
@honest perch didn't work: c
How do I add reactions, one after each other, fast?
.then(msg => { msg.react(acceptEmoji) .then(() => { msg.react(denyEmoji)``` I'ver tried this but it is really slow to add reactions
I've tried with await and it is still slow
already exported to another project but the error continues
can you show me your package file
@opaque seal discord.js adds a delay between all requests, but since this delay is fixed, reactions suffer the most
In ejs we do something like var something=<%-something%>
can we do it the other way
<% var something=%>something
you can reduce this delay in the client options
@opaque seal discord.js adds a delay between all requests, but since this delay is fixed, reactions suffer the most
Because I saw a ModMail bot which added reacitons real fast
restTimeOffset in your client options
Where can I find my client options?
new Discord.Client({options here})
when u are initializing your client
oh ok
can you show me your package file
@honest perch ```{
"name": "battlebot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "12.x"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^12.2.0",
"moment": "^2.26.0",
"parse-ms": "^2.1.0",
"quick.db": "^7.1.1",
"dotenv": "^8.2.0",
"ytdl-core": "^3.1.0",
"yt-search": "^1.1.2",
"ffmpeg-binaries": "^4.0.0",
"node-opus": "^0.3.3",
"superagent": "^5.2.2",
"ms": "^2.1.2",
"random-puppy": "^1.1.0",
"youtube-info": "^1.3.2",
"simple-youtube-api": "^5.2.1",
"convert-seconds": "^1.0.1",
"jimp": "^0.12.1",
"node-fetch": "^2.6.0",
"number-to-words": "^1.2.4",
"merge-img": "^2.1.3",
"weather-js": "^2.0.0",
"gifencoder": "^2.0.1",
"snekfetch": "^4.0.4",
"table": "^5.4.6",
"array-sort": "^1.0.0",
"opusscript": "^0.0.7",
"node-gyp": "^6.1.0",
"mathjs": "^6.6.5",
"request": "^2.88.2",
"quick.hook": "^1.5.1",
"cpu-stat": "^2.0.1",
"os": "^0.1.1",
"mal-scraper": "^2.6.9",
"google-translate-api": "^2.3.0",
"node-superfetch": "^0.1.10",
"better-sqlite3": "^7.0.1",
"nekos.life": "^2.0.7",
"fs": "^0.0.2",
"request-promise-native": "^1.0.8",
"fs-nextra": "^0.5.1",
"youtube-api-v3-search": "^1.2.1",
"youtube-search": "^1.1.4",
"express": "^4.17.1",
"firebase": "^7.14.6",
"moment-duration-format": "^2.2.2",
"date-format": "^3.0.0",
"sqlite3": "^4.2.0",
"dblapi.js": "^2.4.0"
},
"devDependencies": {},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}```
And what's the downside of reducing the restTime?
Lemme know if someone has idea of https://discordapp.com/channels/264445053596991498/272764566411149314/717469990613155890
And what's the downside of reducing the restTime?
@opaque seal Probably more chances to get ratelimited
you will be more likely to hit the rate limits
Ikr lmfao
Uhm, I'm gonna stick to the default value then
ye
if there is someone experienced with EJS reply to this https://discordapp.com/channels/264445053596991498/272764566411149314/717469990613155890
did you install every package you could find
@honest perch are all the bot uses: c
How can I get the Usernamen with OAuth2?
you do the oauth flow with the identify scope
@cerulean hornet idk then, try asking on the glitch forums
you do the oauth flow with the
identifyscope
@mossy vine yes
yes
How can I remove the last comma from a string?
How could I delete only one line from fs ? For example i want to delete only this line in a fs file "420686077070934016":{"leaveserverc":"false"}
delete object & then rewrite @clever tree
How can I get the Usernamen with OAuth2?
@radiant estuary
I want to delete a membersetting from a server when this person leaves
exactly what i said ye
check if the fs file containt the .id of the guild or member what ever
define delete []
then rewrite
@earnest phoenix But how ? fs needs an input like :
serverlevel[message.guild.id] = {
serverlevel: "true"
}
Which input is for delete? Or which function fs.writeFile
require the data first
then
if (serverlevel[message.guild.id]) // do something
Any idea why this happens?
So this is my querry:
SELECT * FROM reps WHERE repid = "${args[1].toUpperCase}"
Args[1] is set to 1.
It sais it can't find the row but when I do this in the command line:
SELECT * FROM reps WHERE repid = "1";
It finds a row
@earnest phoenix yea. And now what is the delete function. serverlevel[message.guild.id].delete()
?
How can I get the Usernamen with OAuth2?
Anyone know my solution?
no problem π
@quartz kindle if you set the restTimeOffset to, for example, 5000, will discord.js wait 5 seconds before every request?
hey
anyone got any idea how to use the bot's current voice channel for a connection
instead of message.member.voice.channel.join
So I have thise message.createdTimestamp but when I use this: client.moment(time).format("MM/DD HH:mm"); it kinde gives a weird date. Anyone knows how to solve that?
Does anyone know how to turn a discord timestamp into a date using moment.js?
"content":"{@user}",
"embed":{
"color":-9270822,
"title":"welcome",
"description":"hi {user} welcome",
"author":{
"name":"{user}#{user-discriminator}",
"icon_url":"{user-avatar-url}"
},
"thumbnail":{
"url":"{user-avatar-url}"
},
"footer": {
"text": "userid: {user-id}"
}
}
}```
**embed for welcome**
what weird date did it give you?
console.log(message.createdAt)
does anyone know how to get current vc of bot?
You know a solution?
anyone?
on which guild?
well, the only guild it's in
VC id : 709992213047672833
Guild ID : 709990437007392828
guild.voice.channel in djs v12
ty
or client.voice.connections.first().channel
i got this right
```let statuses = [${bot.users.size} users! | db!help, ${bot.guilds.size} servers! | db!help];
setInterval(() => {
let status = statuses [Math.floor(Math.random() * statuses.length)];
bot.user.setActivity(status, { type: "WATCHING"})
// watching, stremaing, playing
}, 10000);```
how come it shows on the bot that theres 0 users
d.js v12?
11
wtf
How can you have an empty title for an addField()?
hi
i'm trying to log into the discord thing i'm making and uhh, im' getting an error, Error: Unknown authentication strategy "discord" i kno what it means but how can i make it not error and make me log in? the code passport.authenticate('discord')
How do I remove the f irst 2 indexes of an array?
pm2 says heap size is Code metrics value ββββββββββββββββββββββββββ¬ββββββββββββ β Heap Size β 49.70 MiB β β Heap Usage β 96.26 % β β Used Heap Size β 47.84 MiB β β Active requests β 0 β β Active handles β 8 β β Event Loop Latency β 0.09 ms β β Event Loop Latency p95 β 2.39 ms β ββββββββββββββββββββββββββ΄ββββββββββββ
but I've done pm2 start index.js --node-args="--max_old_space_size=4096"
node v12
How do I add more heap to pm2?
How should I fix a 503 error/overloaded
@earnest phoenix in D.js v12 \u200b
\u200b isnt at all related to discord.js, its a unicode character
@astral yoke on the sidebar you will see a file called "packages" click it and then click on the search bar at the top, or the little drop down box thingy, then type in "node" and see what comes up, install the one that you need and bam bam bam ur good to go
thats all i know lol
wHAt
try google?
anyone?
ill google it for you hang on
ty
um
ty
?
found another thats way better
try that
that looks just about perfect
for the question u asked
is that even relevant? That's from 2018
client.on('message', (msg) => {msg.content}); Will msg.content contain the command prefix?
nope
How's it possible to remove the very last string from an array that equals to a specified string?
If you didn't know what i was talking about... Well
["--dark", "--dark", "--dark"] you see that the array contains 3 of the same string... But how can remove the very last one of them that equals to a specified string?
You could start from the back of the array and check each element until you find one that equals some other string and remove it
But there's the thing... How do you even start from the back of the array...
reverse the array
You could use a for loop starting with the last index if you need to keep the array order
Or reverse, iterate, reverse again
Oh the array.reverse()
Or do what teemaw said
Yea well... Lemme try
if you're wondering how to start from the last index: for(let i = array.length-1; i >= 0; i--)
@Misly i've gotten it to a point where it's functional. i still need to make it prettier.
@grizzled raven ^
@quartz kindle Trickier way to iterate backwards for(let i=x.length; i--;pi=3.14)
good trick
another trick ```js
let i = array.length;
while(--i) {
}
but this one will ignore index 0 lul
Just do while(iβ) instead?
Lol
fun fact for(;;) does the same as while(true)
isn't while faster than for o.o
they both compile to the same thing afaik
while(true) is certainly more readable though
but for(;;) is shorter :^)
I mean for arguments sake you could just do while(1)
i love this "fight"
this is real programming
ikr uwu
lol
to make it more readable you should use recursion or high order functions instead of looping
LOL
do
goto hast
hast
goto mich
node v12.0.0, with pnpm
7:21 AM
Installingβ¦
7:21 AM
Performing headless installation
7:21 AM
7:21 AM
Total install time: 2642ms
Nothing happened and nothing in console, how can I fix this?
is (node .) the problem
I try refreshing and now glitch doesnβt even load
Which Bot Library Is Recommended?
there is literally no vaguer question than that
Which Is Recommended
for what language
These Languages
choose one
Java
I use JDA
Noice
I suggest you learn java before writing a bot then
What About HTML5
thatβs not a programming language
But Itβs A Coding Language
Look At Google
have fun writing a bot in a language thatβs meant for browser games
my friend programmed a flying pizza with the marquee tag
HTML can only represent states, it doesn't handle any logic
lol "Plain text"
I think that's a list of supported syntax highlights for some mobile app
What About Python
I think you should do some research into good programming languages for beginners
you clearly have no idea what youβre doing
Anyway Gtg Iβm Learning JavaScript
Bruh
that's some ancient HTML
anyone know how on earth i can add an uptime command
what language
anyone know how on earth i can add an uptime command
@misty sigil what language?
djs, i shoulda specified that
store the current time when the bot starts, and subtract that from the current time at the time the command is received
suprisingly simple
Iβm Using Node.Js And Learning JavaScript
best thing is
is that the time the nodejs server has been running or the amount of time since the discordjs login?
i have ab!reload, i dont have to restart
former
nodejs process
since the websocket can close without the process exiting
nodejs process, as if thats longer than login
it probably is by a little bit
you can get ws uptime as well
maybe there is reconnect logic
I think djs has built in property for this
I'd hope so @proven lantern
the gateway reconnects all the time though
true
so process and ws uptime can become very disjoined
ws uptime shouldnβt go above like 12 hours
in discordβs case
but process can go on for as long as you want
they probably only handle closure
And not reconnect
ws connections have to be reset every few hours otherwise discord closes the connection
i remember looking at some source
but i think it was eris, not discord.js
and it did in fact reset client.uptime on every reconnect
if you log gateway events you should get fairly common reconnects
does anyone know how can i show all the roles that the user has ? tried with user.roles.find(roles => `${roles}`).join(', '), true) but didn't work
thatβs just because discord required it a few months ago
yeah ik
but apparently discord.js doesnt make it reset the client.uptime getter
while eris does
not sure how easy it is to access the websocket conn with djs
@quiet sedge user.roles is a collection with all the users roles. you should be able to iterate over the collection to see all the roles for that user
they like to make shit like that inaccessible for some dumb reason
its js, you can pretty much hack anything via prototypes
prototyping is really dumb
i immediately dislike any codebase that uses them
completely defeats the point of classes lol
my lib has to use them in order to intercept some parts of djs that i couldnt make work with class extensions
maybe you don't need a class
strong oop is by far the best way to write code in this context
if itβs available
makes everything a lot easier to abstract
well in the context of any package
Ahh you're talking about libs in general
pure functional programming is better that oop
@quiet sedge use a map
Is args[0] getting first argument of split message? ( in d.js )
pure functional programming is a bit niche
itβs not better, thatβs completely subjective
itβs a damn lot more efficient at scale but very hard to work with for much else
const GetLinkByModule = require('node-fetch')
const LinkDiscordP = ["discord.gg/", "https://discord.gg/"]
if(LinkDiscordP.some(link => message.content.toLowerCase().includes(link))){
let LinkGetDiscordApi = GetLinkByModule("https://discord.com/api/v6/invites/" + idk)
}```hi, i would like to make it so that when a link and post on the server its sends me all kind of info. except that I've been stuck here for a while
@fallow steppe we don't know, how did you define args
you obvs followed a tutorial
since you're asking such thing
@wicked pivot discord.js has a function that can fetch invites already
no need to make extra work
@proven lantern it's subjective, as Jacher said, and imo pure functional programming gets messy after a bit
can the fetch invite give me info on a link from a server or the bot es but not otherwise? @earnest phoenix
imo = in my opinion
@white anvil I have to disagree that "oop is by far the best way to write code in this context" as like you said it's all subjective and different programming paradigms exist for a reason
just in case
yeah on the subject of distributed open source packages, structures are usually beneficial
@quiet sedge use a map
@copper cradle i tried. but i get TypeError: Cannot read property 'map' of undefined
then
hence why djs is absolutely bursting with them
embed.addField("Roles:", user.roles.map(roles => `${roles}`).join(' | '), true)
roles.cache
Hey, i gotta question
I have this
try {
message.channel.send(embed).then(m => m.delete({ timeout: 10000 }));
db.set(`welcomeMessage_${message.guild.id}`, welcome);
func.embed(message.channel, `**Successfully set a welcome message!**`);
} catch (error) {
message.channel.send(
"Invalid Message: please re-type the command with a valid message!"
);
}
Its supposed to catch the error right? Well it doesnt do that, it gives me this
Ping me if ya have any solution
and the error says
or just .catch
Not a well formed url
.setImage on the embed is probs malformed
ye i purposely made a bad image url to see if it would catch
ah
since this is a feature for other people to add an image
then it's just what steven said
after sending a message, after your .then you can add a .catch(console.error)
thanks @earnest phoenix that did the job π
it's the {}
ohh this is new to me lel
you can .catch((e) => { code }) if you want
Yep
can i catch(e) or do i need to catch console.error
catch(function)
do you want it to print to console?
oh
thats what that does
i see thanks
And, is e the same as err the same as error?
it's just a callback, providing console.error just makes it log the error for you easily
catch is a higher-order function
that's just the name you want the parameter to be
so catch(function(err) { /scope/}) has e as error in the scope
lol tru @proven lantern
so say i have this
exports.engine = async function (data) {
}
in the same file, can i do this
module.exports = function (app) {
engine(app.data);
}
or something like this.engine or exports.engine...
exports.engine
developing question
i have ram usage, not CPU, how does one implement this
save everything to disk
os module
cool
bro you're funny @proven lantern
@misty sigil system ram or process ram?
i mean cpu, sorry
someone can help me ?
https://discordapp.com/channels/264445053596991498/272764566411149314/717529088688128072
system cpu or process cpu?
process would be preferred
await message.channel.send(embed).then(async msg => {
await db.set(`welcomeMessage_${message.guild.id}`, welcome);
await func.embed(message.channel, `**Successfully set a welcome message!**`);
}).catch((e) => {
return message.channel.send(`Invalid URL!`)
})
For the then statement what has to go before the arrow function, it seems m and msg works, does js automatically know what that is?
are you using node? @misty sigil
node? yes
process cpu is not an easy thing to obtain from node's internal tools
oh you want process cpu
do you know any api for spotify catch?
oh well ill stick with my ram
node's internal tools will give you system time and user time at a specific point in time, you have to measure 2 points and compare system time and user time, and how much of each time was used
@misty sigil you could spawn a top | grep and get process cpu that way
did someone say something similar to top gear
lmao
@amber fractal sorry for the ping mate just one thing
await message.channel.send(embed).then(async message => {
await db.set(`welcomeMessage_${message.guild.id}`, welcome);
await func.embed(message.channel, `**Successfully set a welcome message!**`);
}).catch((e) => {
return message.channel.send(`Invalid URL!`)
})
Is this a proper way of doing this? And I tried changing the then async message to then async randomblah it still works? So why do I need to specify message
if you're awaiting it, you can use try/catch, but if you're using .then you need to use .catch as well
you choose between them
oh ok,
and whats the thing with message?
Why does it also work when i replace it with random
wdym
Like
.then(async random => {});
channel.send() returns a promise of the sent message
like that
that's just a variable
when you do .then(bla => {}) this bla is the message object that you just sent
like passing it to a function
so i fucked express that much if you try render a route it sends you an ocelot-stream.
ohhh, so you could return it later on or something
Thanks steven! I understand
ocelot stream? lmao
Hey tim is this the correct way to check in MS how long something took?
let before = new Date();
await reloadCommands(client)
let after = new Date();
let reloadTime = before - after;```
can someone try look at my renderer then ig?
octet-stream is basically binary data, aka no mime type
bro that's octet stream @sick cloud
you need to set content-type to text/html or something
i'm using a custom ejs renderer so where
octet = byte
like if you let x = await message.channel.send("x") x will be a message, same if you do message.channel.send("x").then(y => {//y would be the same message as x if you used this instead})
exports.engine = async function (filePath, options, callback) {
const file = await fs.readFileSync(filePath);
const defaultLayout = await fs.readFileSync(path.join(__dirname + '/../views/layouts/default.ejs'));
const contents = ejs.renderFile(file, options);
const data = {
contents: Buffer.from(contents),
layout: 'default'
}
const layouts = {
default: {
contents: Buffer.from(defaultLayout)
}
}
const res = render(data, layouts);
const rendered = res.contents.toString();
console.log(rendered)
return callback(null, rendered);
}
set a content-type header in your express response
text/html
where does the callback return to?
the route
and then the route sends it?
app.get('/', async (req, res) => {
await res.render('index', { greeting: 'world' });
});
um express docs says the callback will auto send it
hi
https://expressjs.com/en/advanced/developing-template-engines.html this is what i based mine off
do it before the await
Mine is just simple https://oliy.is-just-a.dev/o3be35_4106.png res.render("page")
i'm getting TypeError: OAuth2Strategy requires a verify callback for some reason. code: js const discordStrategy = require('./strategies/discordstrategy'); and the second function is a callback ```js
passport.use(new DiscordStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CLIENT_REDIRECT,
scope: ['identify', 'guilds']
}, (accessToken, refreshToken, profile, done) => {
console.log('e')
}));
@sick cloud try this res.type("html").render()
it should be the default, idk if ejs is changing it somewhere
set it with res.set('Content-Type', 'text/html');?
wait are you sending html or json?
html?
@digital ibex https://github.com/jaredhanson/passport-google-oauth/issues/126 check this
i render the ejs content, then the layouts module just renders another ejs page with the original page's content jammed in
The first answer, it is for google, but oauth is basically all the same
as a layout
oo, thank u
why is it using buffers tho
try res.set('Content-Type', 'text/html'); @sick cloud
or try using dev tools and see what's actually being sent over the wire
i don't know but that's what the module wants
also no way to check dev as literally it sends the octet when you hit enter to /
Connot read property of find
exports.run = (Discord, clinet, message, args, config) => {
if (!message.member.hasPermission("MANAGE_SERVER")) return message.channel.send("**You do not have permission to run this. You need `MANAGE_SERVER` permission.**")
let cat = args.join(" ")
let category = message.guild.channels.cache.get(c => c.type === "category" && c.name === cat);
if (!category) {
message.channel.send("That category is not in the server. Please make sure you typed the exact catagory.")
} else {
open dev tools then press enter
Why did you pass a function to get? @nocturne dagger
what are the headers? @sick cloud
what?
I asked how to get a category by name and that was what I was told
is that incorrect?
there's no response headers
oh
use .find
then it didn't send any
is message.content.includes.toLowerCase("hi") possible?
I tried that
What was the exact error?
still exact same error cannot read property of find
did you set your render engine @sick cloud
yes
makes the command incase sensitive?
app.engine('ejs', exports.engine);
app.set('views', path.join(__dirname + '/../views'));
app.set('view engine', 'ejs');```
are you getting the correct html in console?
since you're logging it in the render function
then it's just message.guild.channels.find(x)
Can someone explain to me how I add a bot in a server? Owo bc I'm dumb-
console.log(rendered)
so it never reaches this point of code
I- no okay sorry for bothering yall o.O
are you using https://www.npmjs.com/package/ejs?
yes
@earnest phoenix get an invite link for the bot then it's pretty simple https://oliy.is-just-a.dev/5i9wwq_4108.png
@amber fractal i'm getting the same error, but this time i'm doing: ```js
passport.use(new DiscordStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: process.env.CLIENT_REDIRECT,
scope: ['identify', 'guilds']
}, function (accessToken, refreshToken, profile, cb) {
console.log(profile)
}));
const ejs = require('ejs');
const render = require('layouts');
const fs = require('fs');
const path = require('path');
const engine = async function (filePath, options, callback) {
const file = await fs.readFileSync(filePath);
const defaultLayout = await fs.readFileSync(path.join(__dirname + '/../views/layouts/default.ejs'));
const contents = ejs.renderFile(file, options);
const data = {
contents: Buffer.from(contents),
layout: 'default'
}
const layouts = {
default: {
contents: Buffer.from(defaultLayout)
}
}
const res = render(data, layouts);
const rendered = res.contents.toString();
console.log(rendered)
return callback(null, rendered);
}
module.exports = function (app) {
app.engine('ejs', engine);
app.set('views', path.join(__dirname + '/../views'));
app.set('view engine', 'ejs');
}
then in the express server i do this: templateEngine(app) where app is the express server
sorry for wall of code lol
@sick cloud it looks like you can just app.set('view engine', 'ejs'); without defining a custom one
Steven can you help me with something in DM's i dont want to flood the chat
Sure, my dms should be open
ahh
so yeah not that easy
just checked something, it doesn't even reach the fs readFileSync's in the engine
so the entire function is not even being called
so yea somethings rly broken
does it not like that it's async?
you dont need async if you're using readFileSync lol
oh ok
removed async and stuff but it still sends an octet and no console.logs
maybe try naming it something else since the default ejs also uses that name?
gotcha
// index.js
const ljs = require('./.src/templatingEngine');
const app = express();
//...
app.engine('ljs', ljs);
app.set('views', './views');
app.set('view engine', 'ljs');
app.get('/', async (req, res) => {
res.set('Content-Type', 'text/html');
return res.render('index', { greeting: 'world' });
});
// .src/templatingEngine.js
const engine = function (filePath, options, callback) {
const file = fs.readFileSync(filePath);
const defaultLayout = fs.readFileSync(path.join(__dirname + '/../views/layouts/default.ejs'));
console.log(file)
console.log(defaultLayout)
const contents = ejs.renderFile(file, options);
const data = {
contents: Buffer.from(contents),
layout: 'default'
}
const layouts = {
default: {
contents: Buffer.from(defaultLayout)
}
}
const res = render(data, layouts);
const rendered = res.contents.toString();
console.log(rendered)
return callback(null, rendered);
}
another code wall but that's exactly how it is right now
nothing else
How do you guys think this would place a space at the end of text?
args.join(" ").split("--dark").join(" --dark").split(" ").reverse().slice(1).reverse().join(" ").split(" --dark").join("--dark").split(" ").join("%20").........
so i'm super confused
well you're not exporting the engine function @sick cloud
o
@digital ibex try adding cb(null, user) after console.log(profile)
kk
really weird that it's not even getting called
yeah
what if you got rid of async in index for the / route
@amber fractal so like js passport.use(new DiscordStrategy({ clientID: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, callbackURL: process.env.CLIENT_REDIRECT, scope: ['identify', 'guilds'] }, function (accessToken, refreshToken, profile, cb) { console.log(profile) cb(null, profile) })); ?
since it doesn't look like it needs it
kk
https://www.npmjs.com/package/passport-discord says you need to do that to verify
still nothing
i've already installed it
Ik
How when i eval this
args.join(" ").split("--dark").join(" --dark").split(" ").reverse().slice(1).reverse().join(" ").split(" --dark").join("--dark").split(" ").join("%20") there's no space at the end but in my supreme command... It places a space at the end for no reason
but in the docs it says to do that
so try to return cb(null, user) since you dont have it find errors anywhere
@sick cloud also try not returning the result of res.render
still nothing, i've tried all those small weird things
alright dumb thing right here, seems my listener broke in the first place
lol nice
however the layout logic is broken so
ignore the name but
app.engine('aaaa', function (filePath, options, callback) { logger.info(filePath)
that never logs still
but it is rendering now
ok cool, fixed it
express engines seem to be having issues so i'm just doing a func:
app.get('/', async (req, res) => {
return res.send(await render('index', { greeting: 'world' }))
});
works well now
For my VIP feature of my bot, how do I check if a user has a specific role in my support server, if so then they can run a command.
But I want this to work on any guild not just the support server
Get your support servers id, when they run the command, get the support server guild then check if they have a role on it.
Ye thats what im trying to do, tho i can figure out the specific syntax
I did
const partnerRole = client.guilds.cache.get("713260797891051540").roles.cache.get("714644627608698920").id
console.log(partnerRole)
if (message.author.roles.has(`${partnerRole}`)) {
tho thats wrong i think
const Discord = require("discord.js");
const client = new Discord.Client();
const embed = new Discord.RichEmbed()
.setTitle("Docs")
.setDescription("Please input a type!\n\n`.docs scripts`\n`.docs actions`\n`.docs mods`")
client.on("message", message => {
if(message.content === ".docs") {
message.channel.send(embed).catch(console.error);
}
});```
v11.6.4 no errors in log
this is the simplest thing wtf
V11 is deprecated, I'd update to v12 if I were you
Also, is v11 working with the new gateway system?
Because the old endpoint died a few months earlier
Ye
hmm
why do i get this
1: 0xa2afd0 node::Abort() [node]
2: 0x97a467 node::FatalError(char const*, char const*) [node]
3: 0xb9d7aa v8::Utils::ReportApiFailure(char const*, char const*) [node]
4: 0x7f5c941b2489 Require(v8::Local<v8::Object>, char const*) [/rbd/pnpm-volume/64a4d873-3972-4972-a7b7-61d54a6a4eed/node_modules/quick.eco/node_modules/better-sqlite3/build/Release/better_sqlite3.node]
5: 0x7f5c941b28ee Integer::Init(v8::Isolate*, v8::Local<v8::Object>, v8::Local<v8::Object>) [/rbd/pnpm-volume/64a4d873-3972-4972-a7b7-61d54a6a4eed/node_modules/quick.eco/node_modules/better-sqlite3/build/Release/better_sqlite3.node]
6: 0x7f5c941bb077 RegisterModule(v8::Local<v8::Object>, v8::Local<v8::Object>) [/rbd/pnpm-volume/64a4d873-3972-4972-a7b7-61d54a6a4eed/node_modules/quick.eco/node_modules/better-sqlite3/build/Release/better_sqlite3.node]
7: 0xa025c9 [node]
8: 0xa016bb node::binding::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&) [node]
9: 0xc06bab [node]
10: 0xc08156 [node]
11: 0xc087d6 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x13a9f19 [node]
/opt/watcher/app-types/node/start.sh: line 51: 3149 Aborted (core dumped) node src/index.js```
when trying to switch to v12
well given that you're using sqlite
is there anyone, familiar with Glitch, Visual Studio Code, and Github, who is willing to teach me how to bring my glitch project into VSC so that I can upload it into a VPS. If so, your help is greatl appeciated, and pls ping me π
developing question of 3am
How do I make a bot send a message to a specific channel when my bot gets added.
pls ping me
@misty sigil depends whether you know the channel or not
what lib
discord.js
client/bot.on
use the guildCreate event, it gives the guild it joined as the arg
so just fetch the channel and send to it
client.on('guildCreate', (guild) => {
// v11
const channel = client.channels.get(id);
// v12
const channel = client.channels.cache.get(id);
// finally
if (!channel) return;
channel.send(`Joined ${guild.name}`);
});```
Ok, so now I have a problem
/home/runner/ZWrlds-Moderation-BotBeta/commands/ban.js:9
return await msg.channel.createMessage('You need to specify a user')
^^^^^
SyntaxError: await is only valid in async function
I don't know how I'm supposed to make that work
I'm looking to stop my bot from replying to other bots but I can't find much. Library is Eris if anyone can help
hmm
here in discord.js its if(<message>.author.bot)return;
@misty sigil I don't think I remember how to make it an async function
No, I can't
If you know you don't need the await, you can remove it since you're using it with return. If you want to mark the function as async but don't know how to, consider reading this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
const discord = require("discord.js");
const commands = require(".");
const info = require("../info.json");
const command = "ban";
if (command === 'ban') {
if (mentioned === false)
return await msg.channel.createMessage('You need to specify a user')
if (checkForMod(msg.channel.guild.members.get(mentioned.id)))
return await msg.channel.createMessage('I cannot ban that user')
let reason = msg.content.split(' ').slice(2).join(' ').length === 0 ? 'Unspecified' : msg.content.split(' ').slice(2).join(' ')
try {
let dm = await bot.getDMChannel(mentioned.id)
await bot.createMessage(dm.id, `You have been **banned** by **${nickName}** for ${reason}`)
let embed = createEmbedFields(null, mentioned, [{ name: 'User banned', value: `<@!${mentioned.id}> has been banned by ${nickName}` }, { name: 'Reason', value: reason }], 'Banhammer', true)
await bot.banGuildMember(msg.channel.guild.id, mentioned.id, 7, `Banned by ${msg.author.id} | Reason: ${reason}`)
await msg.channel.createMessage({ embed })
} catch (e) { await msg.channel.createMessage('That user cannot be banned'); console.log(e) }
await bot.emit('command', msg, command, mentioned)
}
What is require(".") supposed to do? What file is this? Where are you getting the msg object from?
Well it's suppose to be a command that bans a person
Okay, but do you know what you're doing with all those variables all around the place? Did you define them somewhere?
I'm got that part of the code from a github repo I'm pretty sure
shouldn't you write your own code
As long as you give credit to the original owner your ok
As long as u understand the code
If you don't have a good knowledge on the code or the programming language you're using, you should try learning it before attempting to make a Discord bot.
Like why you're using Eris properties yet require Discord.js at the top of the file.
message.guild.channels.create(${user.username}, {
is creating `{ TypeError [INVALID_TYPE]: Supplied parameter is not an User nor a Role.`` i dont understanf
ping me if u know
Uh. I cant see the second parameter
I can only see the first
@earnest phoenix try js bot.guild.cache.size
How can I get the Name, who used discord OAuth2?
Imagine saying that he should downgrade to v11 cause it does not work on v12
rip
lol
@earnest phoenix bot.guilds.cache.size instead of bot.guilds.size
ah
what is the ipcSocket 9997? @golden condor
and cluster count is always 1 right?
cause you only need to spawn 1 cluster
Just depends on how many you need
No that's a discord thing
who know why i cant to connect heroku with github? when i try to connect the site say this message
Couldn't connect to GitHub
Error: remote was closed, authorization was denied, or an authentication message otherwise not received before the window closed.
Sure thats fine
idk,first try when i tried to connect i saw a new tab
i click connect and showed this error
Did you authorise it?
yea
I'm not sure
Hi
huh? I dont need to verify my phone! YES
@earnest phoenix
Is my bot
and embed+ to
You need to tell it what node version to use
i just installed now 14.4.0
how do you do a permission check on a on_message event?
ive tried it but cant get it to work
how to reinstall package-lock.json and package.json?
if your package.json has been deleted, you can do npm init or npm init -y
on cmd?
npm init and npm init -y
one of the two
to reinstall
ok
i want to reinstall package json
because i ve had problems with heroku
by reinstall you mean create, right?
get your dad's
:))
bruh
but . . . . nvm
Since when does Heroku require credit card
wait there is Credit generator xD
wouldn't work
nope
ik
if you verify, you'll get extra hours that can get your bot up 24/7
yes
not really 24/7 but ye
cuz the free hours is only for 28 days
because it restarts every 24 hours
yes
you won't notice it though
:((
it restarts fast
no
wrong emoji : /
How can I use .pipe() for ffmpeg filters (in music)
ahm i dont have music bot so . . . nvm
can't help ya
if you don't know how to help then dont respond lol?
I canβt help you sorry man
@golden condor uh pipes are indefinite of filters
Well they can be used for filters I think
Yeah there is a bot that uses pipe with ffmpeg for filtrs
do you know what is a pipe
Not quite
it's a way to transport data in a stream, there are 3 default pipes in ffmpeg
pipe 0 is std in
pipe 1 is std out
pipe 2 is std err
Ok
there's also named pipes which are pipes on a system level and IPC works mostly via named pipes
pipes are irrelevant to filters
they're just a direction to transfer data
Oh
you can apply a filter regardless whether you're using pipes or not
So is there no way to use filters with ffmpeg?
h o w t o s e n d d m ?
you can apply a filter regardless whether you're using pipes or not
Sorry didn't read this
@pure lion by sending the dm
@earnest phoenix via bot lmao
send the dm via the bot
say i wanted to rickroll someone-
you're a little late on that
i unfortunately broke my magic crystal ball during quarantine and I can't read your mind to know which lib you're using π
read the docs https://discodrd.js.org
h
Lmao
send method on the user
sending the dm is a 50/50 chance it will succeed since they need to have their dms enabled
discodrd.js.orgβs server IP address could not be found.
are you re-
c:
So is there anyway to use filters with ffmpeg then (with a discord.js stream music)
just pass the filter arguments to ffmpeg
what is an arc?
just pass the filter arguments to ffmpeg
How
like a parabola
oh i found it
API documentation for the Rust Arc struct in crate std.
seems cool
Do I do that in discordjs or in ffmpeg?
@pure lion message.author.send("hi this dm")
in ffmpeg you need to tell it to take input from pipe:0 and send the output through pipe:1
in code you need to send your stream data to ffmpeg's stdin and read ffmpeg's stdout
no i cannot
@pure lion message.author.send("hi this dm")
but i want to dm a mentioned user
then check for any mentioned users
lmao
So how would I send a pipe to a stream that discord.js has started I'm a bit confused
you don't send a pipe
haven't we already established that a pipe is just a direction
let user = message.mentions.members.first()
user.send("This is DM")
I am using wrong terminology sorry
yes
@pure lion
i wouldn't know how to do it in node because node is an absolute disaster to work with
o
ty
but you need to read the stream from d.js and send the data you read to ffmpeg's stdin
i know how to do it in java cpp and c# just not node because i hate working with trashy environments
i want to make this channel to be the SEC STACKOVERFLOW
i agree
node is pretty garbage when you gotta do anything close to low level shit
@mossy vine π‘
eh?
u said NodeJS is garbage
:oo
I'm confused a lot
me 2
thank you tony
tony ??
nah ok this guy is trolling im out
lmao
I'm confused by this
I found a package that I think helps

stop trolling man
I really am very confused by this, maybe I could do it via cli (exec)