#development

1 messages ยท Page 1796 of 1

quartz kindle
#

registerfont must be called before a canvas is created

jovial nexus
#

it is

quartz kindle
#

not in the code above

#

show full code then

small tangle
#

How can i limit the click of a slash command button to only the executor of the slash command?

jovial nexus
quartz kindle
#

try changing the font format

slender wagon
#

how do i use a foreach function with mongoose, to get everything inside a collection

quartz kindle
#

convert it to ttf

jovial nexus
quartz kindle
#

did you convert it?

jovial nexus
quartz kindle
#

where is your bot hosted?

jovial nexus
#

localy

#

its not hosted yet

quartz kindle
#

and the font files are there in the fonts folder?

jovial nexus
#

yes

quartz kindle
#

try ctx.font = "115px 'TT Norms'"

#

with quotes around the name

slender thistle
#

Is there really no way to get the window size with Rust's turtle? ๐Ÿ‘€

jovial nexus
quartz kindle
onyx hare
#

i hate vsc sometimes i put .setTitle() and it changed it to SVGTextPositioningElement() -_-

quartz kindle
#
const Canvas = require("canvas");
Canvas.registerFont(`${process.cwd()}/TTNorms-Regular.otf`, { family: "ttnorms" });

const canvas3 = Canvas.createCanvas(200, 100);
const ctx3 = canvas3.getContext("2d");
ctx3.font = "50px ttnorms";
ctx3.fillText("test", 10, 50);
m.channel.send({
    files: [{
        name: "test.png",
        attachment: canvas3.createPNGStream()
    }]
});
``` this is what i did
quartz kindle
jovial nexus
#

2d

quartz kindle
#

you're not creating a ctx in your code

jovial nexus
#

i need to go il see it later thanks

modest maple
slender thistle
#

Is it called when the window is created?

modest maple
#

Idk

#

Never used the module but possibly

jovial elk
#

hmmm what "this is the last version to support user bots." mean exactly?

#

anyone knows?

slender thistle
#

Meaning you can log in as a user only in this version and any versions below that

modest maple
#

And by that it means sorta

#

Its possible but so much is outdated now and is depreciated

sick agate
#

Yup

jovial elk
#

oh i see, thanks guys ๐Ÿ™‚

sick agate
#

Why???

slender thistle
#

Oh nice the crate's latest version doesn't even work

#

I have to use the master branch from GH

modest maple
#

What are you trying to do

#

And wdym by doesnt work

slender thistle
#

Trying to run turtle

modest maple
#

Out of curiosity what are you trying to make?

slender thistle
#

Just whatever that involves shapes and colors on a board

modest maple
slender thistle
#

Oh

jovial nexus
# quartz kindle ```js const Canvas = require("canvas"); Canvas.registerFont(`${process.cwd()}/TT...
const Canvas = require("canvas");
Canvas.registerFont("./fonts/TTNorms-BlackItalic.otf", { family: "ttnorms" });

async function img() {

  const canvas = Canvas.createCanvas(1772, 763);
  const ctx = canvas.getContext('2d');

  ctx.font = "115px ttnorms";
  ctx.fillText("test", 700, canvas.height / 2 - 150);

  const buffer = canvas.toBuffer('image/png')
    fs.writeFileSync('./image.png', buffer)
}```full code, still giving me error
#

still not understand why

modest maple
#

Why is that function async?

jovial nexus
#

the rest of the code is in comments, it uses await for some images

quartz kindle
#

try with other fonts

#

also which version of canvas are you using?

#

try other versions

jovial nexus
#

lastest

#

do i need to install that font on my computer first? or just the file

quartz kindle
#

you just need the file

jovial nexus
#

yah

#

canvas is trolling me

#

other font same error

quartz kindle
#

did you get any errors when installing canvas?

jovial nexus
#

no, but i can try and reinstall it

#

still error

#

yes

#

yup

quartz kindle
#

it seems to be a windows problem

#

there are issues about it saying it works on ubuntu but not on windows

jovial nexus
#

super wierd

#

i have 5 fonts

#

all the same error except the _2

quartz kindle
#

try installing the font on windows first

jovial nexus
#

f*k canvas ima restart the pc maybe that fixes it

#

im back

pale vessel
#

bet it didn't work

jovial nexus
#

lemme se

pale vessel
#

You did register those fonts, right?

jovial nexus
#

ye

quartz kindle
#

check this

#

really weird issues on windows

jovial nexus
#

hell no its still not working

jovial nexus
#

im desesperated

slender wagon
#

let's say i have alot of buttons with the same id, would this work on only 1 of them?

#
<button class="get-btn" onclick="document.getElementById('confirm').style.display = 'block'">BUY <span style="font-size: 20px;">&#8680;</span></button>
pale vessel
#

Yes

slender wagon
#

is there a way to get through this

#

or just different ids?

quartz kindle
#

ids are unique

pale vessel
#

IDs are meant to be unique

quartz kindle
#

classes are not

slender wagon
#

oh ok so a class should do it

jovial nexus
#

ok i see the problem with canvas

pale vessel
jovial nexus
#

i think i got the problem

quartz kindle
#

also, would probably be better to define styles in css rather than in js

jovial nexus
#

how can i

#

edit the data of a .ttf file

quaint wasp
#

I get the stupid "NaN" when trying to get the latency....
My code for that is:

        { name: "Latence", value: "``" + m.createdTimestamp - message.createdTimestamp + "``", inline: false},

My ping command uses the same thing for the latency, and it works.. Also m is the quick message the bot sends before the stats command, and it messures the time difference.
Code:

        const m = await message.channel.send("Ping");
         m.edit(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(message.client.ws.ping)}ms`);
quartz kindle
#

you're supposed to change your code to match it

jovial nexus
#

i cant changue canvas

#

the problem is the font internal name

quartz kindle
#

you can change your code lol

#

{family: "TT Norms"}

#

ctx.font = "100px TT Norms Regular"

#

at least thats what i understood from the guys "solution"

jovial nexus
#

If the fonts internal name has more that 3 words, canvas cant read it, a lot of issues are opened saying that

quartz kindle
#

the third word is the font type

#

like regular, italic, bold, etc

jovial nexus
#

thats the problem

quartz kindle
#

if you want to change the font just google any font editor

#

there are even online font editors that you can do in the browser

jovial nexus
#

YES

#

JAJA

#

just changued the internal name of the font to one with only one word and workeds

quartz kindle
#

lmao

visual dock
#

Hello,
Please tell me where this code is wrong that the button below the embed is not shown

latent heron
#

i fear entering this channel

#

i can feel xetera's existence if i even mention CSS

visual dock
#

Helpppp : (

quartz kindle
#

they show how to do it

quartz kindle
#

then why are you doing it wrong?

visual dock
quartz kindle
#

its component:button

#

not button:button

visual dock
#

Awww THANKS
Testing...

visual dock
visual dock
quartz kindle
#

how did you create disbut?

visual dock
quartz kindle
#

disbut

#

show how you defined it

visual dock
quartz kindle
#

did you initialize it in your index.js?

visual dock
#

No โ˜น๏ธ

quartz kindle
#

then read the docs again and do it

visual dock
#

ok Thanks

visual dock
solemn latch
#

yeah, those docs cover everything you need

visual dock
solemn latch
#

hmm, im not sure then. i am using that library and it seems straight forward with the docs.
it even gives copy pasteable examples

visual dock
#

I sent my sample code, you saw it was not a problem

blissful pulsar
#

c

visual dock
#

heelp : (]

solemn latch
#

where are you setting the id?

#

oh nvm its a url doesnt need an id iirc

#

try their support server i guess

visual dock
solemn latch
#

still, try their support server.

#

they would know best

#

oh thats ALL code related to buttons?

#

your missing some stuff then

visual dock
signal estuary
#
client.on('guildMemberAdd', member => {}

This event isnt triggered any more. It isnt triggered for my friend using v12 and for me v13 not, too

slender thistle
#

What intents do you have set?

blissful pulsar
#
Error: listen EADDRINUSE: address already in use :::8000
spare badger
#

@blissful pulsar Something probably went wrong when closing the script causing the script not to exit properly. Try to find the proces in your task manager and close it that way, then try to run it again.

clear marlin
#

kill the process

#

it'll work

blissful pulsar
spare badger
#

@blissful pulsar When you are using something that utilizes network ports, you have to make sure you close the script properly everytime you close it. It will otherwise keep using that port and you won't be able to restart the script. So make sure you close the process (via taskmanager if using windows) and try to start it again.

clear marlin
# blissful pulsar how ?

Okay, so try this
netstat -ano | findstr :8000
and then check the process id (pid).
then do
taskkill /PID <PROCESS_ID> /F

spare badger
#

Such commandline pro

clear marlin
#

๐Ÿ˜Ž

clear marlin
#

yes

#

ofc

spare badger
blissful pulsar
clear marlin
#

wow

#

sad

#

can you show the output

#

when you did the netstat command

spare badger
#

Maybe you are then trying to utilize port 8000 twice in your script?

solemn latch
#

Hmm, anyone got any ideas on how to make a button with no characters the same width as a char with 1 character on mobile?
Buttons with zero width chars are thinner than one with a character and it looks bad.

clear marlin
#

the output

blissful pulsar
clear marlin
#

@blissful pulsar do netstat -a

#

are there any active ports

blissful pulsar
clear marlin
#

pretty awkward

mild creek
#

k

clear marlin
#

okay I think I got an answer

#

try
killall -9 node

true ravine
#

I know the Sherlock Holmes of this server will be slamming away at their keyboards to tell me to ask my question in the discord developers server, but I am not going to. Basically, I wanna know what are the repercussions of sending one unsolicited message to every server containing my bot. Is this just API abuse, or is it something that actually incurs consequences other than a ratelimit?

winged mulch
#

I have this line:

const client = require("detritus-client")

And apparently there is a syntax error in the detritus code because I get this error? ```/home/evan/node_modules/detritus-client-rest/lib/client.js:38
buckets;
^

SyntaxError: Unexpected token ;
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
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> (/home/evan/node_modules/detritus-client-rest/lib/index.js:20:14)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

clear marlin
#

so basically you want to send a message to all servers. It's not api abuse, no. You can actually do it

const guildList = <Client>.guilds.cache.map(guild=>{
const channel = guild.channels.cache.first() //the first guild cached
channel.send("Message");
})
})
true ravine
#

I know I can, I'm asking if I should

solemn latch
clear marlin
#

so basically if you send a message every second

#

that's api aboose

#

Discord.js tries to decrease it by using "cache" as you can see the in example^

#

so basically you can do it

misty sigil
#

anyone know any good ways to filter profanity

opal salmon
#

does anyone know how to do mimu embeds

clear marlin
misty sigil
true ravine
#

I'm kinda stuck because my bot was in 3000 servers when discord introduced their verification requirement but I didn't have any valid ID so I abandoned the project. I have now been trying since January to get it verified, and I just got a response saying I they won't verify me if my bot isn't online. But I can't really bring it online because the core feature relies on a privileged intent which I don't have permission to use because I'm in more than 75 servers. My two options are either to make my bot leave most of its servers, bring it online and wait for verification, or create a new bot and then use the original bot to advertise the new one once, then delete it

#

(sorry for the novel)

misty sigil
#

remove the core feature ๐Ÿง 

true ravine
#

But then it's just a ping bot lmao

clear marlin
#

so you can check like , F$#k

solemn latch
#

The proper option is to just start over and not spam messages on the old bot.

lyric mountain
#

you'll just be invite-locked

true ravine
#

I know I can start it, it just won't do anything because the main feature needs the intent

lyric mountain
#

(if you had them on in dashboard)

#

are the intents turned on?

#

like, in the dashboard?

true ravine
#

No because I need to apply for them

lyric mountain
#

if you had it previously enabled you could still use them, but now you're kinda locked off

true ravine
#

(sorry woo I'm not ignoring you)

lyric mountain
#

well, just change code not to use them

#

fetch everywhere

solemn latch
#

Oh np. Not much to say in reply to what I said

true ravine
#

So is there a way to make my bot leave every server aside from a simple loop?

nova basin
#

._.

#

Wtf

misty sigil
rose warren
true ravine
#

I meant without doing that

#

I'm weighing up which is the better option

rose warren
#

Then a loop is your solution I guess

true ravine
#

Oh alrighty

rose warren
#

If you delete the application you'll have to resubmit to topgg etc

true ravine
#

Yeah ideally I don't wanna do that

rose warren
#

And if your bot is verified by Discord it's the same issue. You'll have to re-apply.

true ravine
#

Thanks for your advice everyone

nova basin
#

._.

#

How i can make it please ?

rose warren
#

There's a js lib that can do that. Can't remember what it's called. I used it for a project 3 years ago. Just Google it.

rose warren
#

I guess do inspect element on that webpage if you can and see what JS they're using

rose warren
rose warren
#

Just Google "javascript typing text" or something like that

rose warren
nova basin
solemn latch
#

ahhh, i just want buttons to all be the same size and discord just doesnt want it angeryBOYE

quaint wasp
#

How do you fix this error? I cant find any sollution for it..

29.06 12:11:34 [Bot] (node:218) 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: 3)
29.06 12:11:34 [Bot] (node:262) UnhandledPromiseRejectionWarning: #<Response>
29.06 12:11:34 [Bot] (node:262) 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)
29.06 12:11:34 [Bot] (node:262) [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.```
latent heron
#

uhh

quaint wasp
#

I dont know from where its coming

latent heron
#

did you write an async function in your bot code without a .catch()?

#

that's basically what it's saying

#

it's banshee screaming that because then it can't handle the promise

quaint wasp
#

o..

latent heron
#

you have to have a catch state if it rejects

#

and you don't

#

so it's throwing its hands up

proper pelican
#

handler?

#

@quaint wasp

quaint wasp
#

you need it??

#

ok

#
client.on('message', message => {
  if (!message.content.startsWith(config.prefix) || message.author.bot) return;


//-------------------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------------------



  const args = message.content.slice(config.prefix.length).split(/ +/);
  const commandName = args.shift().toLowerCase();

  const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));



  // If command exist
  if (!command) return message.channel.send(`Sorry, I didn\'t find the command. \n Please use **${prefix}help** to see all the commands.`)

  // Check if command can be executed in DM


  // Check if user is in cooldown
  if (!cooldowns.has(command.name)) {
    cooldowns.set(command.name, new Discord.Collection());
  }

  const now = Date.now();
  const timestamps = cooldowns.get(command.name);
  const cooldownAmount = (command.cooldown || 3) * 1000;

  if (timestamps.has(message.author.id)) {
    const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

    if (now < expirationTime) {
      // If user is in cooldown
      const timeLeft = (expirationTime - now) / 1000;
      return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
    }
  } else {
    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
    // Execute command
    try {
      command.execute(client, message, args, Discord);
    } catch (error) {
      console.error(error);
      message.reply('there was an error trying to execute that command!');
    }
  }
}); 

client.login(process.env.TOKEN)```
signal estuary
#

What Intent do I need for this event: messageReactionAdd

pale vessel
#

GUILD_MESSAGE_REACTIONS for guilds and DIRECT_MESSAGE_REACTIONS for DMs

signal estuary
#

thx

#

Then why isnt this event triggered anymore: client.on('messageReactionAdd', (reaction, user) => {}
I already added the Intent: GUILD_MESSAGE_REACTIONS

#

I am using v13

pale vessel
#

Make sure you provided the intents property in ClientOptions, it's outside ws on v13

prime glacier
#
\node_modules\youtube-sr\build\Util.js:262
        const author = playlistDetails[1]?.playlistSidebarSecondaryInfoRenderer.videoOwner;
                                          ^

SyntaxError: Unexpected token '.'```
earnest phoenix
fair axle
sudden geyser
#

performance is not everything

#

So you may want to search around for what mongoose does that mongodb doesn't

glad sphinx
#

Good day.
How long is it possible to add a game if it is not in the TYPE list?

sudden geyser
#

Confused. Please provide more context.

autumn rampart
#

how would i add a slash command to my bot

opal plank
glad sphinx
sudden geyser
#

Is this a bot you made or someone else's bot

glad sphinx
#

This is your bot. Which I added to my discord.

autumn rampart
glad sphinx
sudden geyser
#

This is not my bot.

#

But it's someone's bot.

#

This isn't the right place to look for bot support.

opal plank
#

wheres the image

sudden geyser
#

You should see if the bot has a support server on its page.

opal plank
#

you are suppose to click there

worn sonnet
#

What you guys think about it?

opal plank
#

i personally dislike it

copper cradle
#

yeah

#

what's the point of it

#

I thought threads would go under a message

sudden geyser
#

Are you writing a Discord clone?

#

I like the look of the threads branching from a text channel, but I feel it may take up too much space.

#

Especially since threads are (probably) dynamic and fluctuate.

quaint wasp
#

I am trying to create a muted role setting but when I run it it doesnt reply at all, and gives no error.

      
muteRole = await message.guild.roles.create({
  data: {
name: "Muted",
color: "RED",
permissions:["SEND_MESSAGES"]
  }
});

message.guild.channels.cache.forEach(async (channel, id) => {
await channel.createOverwrite(muteRole, {
SEND_MESSAGES: false,
  MANAGE_MESSAGES: false,
        ADD_REACTIONS: false
             });
          });
      const created = new MessageEmbed()
      .setTitle("Role Created")
      .setDescription("The muted role has ben setted up.")
      .setColor("RANDOM")
      message.channel.send(created)

opal plank
quaint wasp
#

lint?

quaint wasp
#

ya?

sudden geyser
#

Nevermind, the linting got me

quaint wasp
#

...

autumn rampart
#

can you have the slash command and prefix

quaint wasp
#

ya

#

why not?

quaint wasp
#

ah great now I can't connect to the database no matter how I try.

fresh verge
#

How do I make my bot send these type of messages? (Bottom message AKA the one that is only visible to me.)

pale vessel
#

You need to use interactions for those

#

They're ephemeral messages

opal plank
#

so

#

are u using my example?

earnest phoenix
#

hi

#

and no, its bascally me rewritting from d.js of my current

opal plank
#

all good, what u got so far?

earnest phoenix
#

for an example?

#

it logged in ofc.

restive furnace
#

erwin adversiting detritus for everyone mmLol

earnest phoenix
#

Meru is my client...

opal plank
#

this is why ts helps you

#

it tells you what events it has

#

you probably intiated a commandClient

#

so you need to do commandClient.client

earnest phoenix
#

ahhh..

opal plank
#

which can be either a cluster or just a single client

earnest phoenix
#

so its Meru.client.client i need

opal plank
#

what IS meru?

#

show me where u declare it

earnest phoenix
#

mk

opal plank
#

so its a shardClient

#

cuz u dont pass in shardCount

#

so it defaults to 1

earnest phoenix
#

o

opal plank
#

so yeah, Meru.client.on('messageCreate')

earnest phoenix
#

BobaSip thank.

opal plank
#

idk what kind of intellisense u have with js

#

just remember in almost ALL events emitted by detritus, tis called CONTEXT

#

so messageCreate doesnt output a message object

earnest phoenix
#

ah. so not newUser, oldUser either?

earnest phoenix
#

:o

#

Ok that makes sense

opal plank
#

its basically payload.message instead

#

or you can destructure it directly into message

earnest phoenix
#

like ctx.user/ctx.msg (py)

opal plank
#

kind of yeah

autumn rampart
#

i get this (node:21918) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of undefined

#
const Discord = require('discord.js');

module.exports = {
    name: 'play',
    aliases: ['p'],
    description: 'plays a song/nasheed',

    async execute (client, message, args) {
        if(!message.membe.voice.channel) return message.reply('Pleases be in a vc to use this command.');

        const music = args.join(" "); //&play song name
        if(!music) return message.reply("Invalid song/nasheed name.");

        await client.distube.play(message, music);
    }

}
sudden geyser
#

.membe is not a thing.

#

You probably meant .member

autumn rampart
#

ok

#

(node:22029) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of undefined

#

i still get this

#
const fs = require('fs');
const Discord = require("discord.js");
const { prefix, token } = require('./config.json');



const client = new Discord.Client();
client.commands = new Discord.Collection();
client.cooldowns = new Discord.Collection();


const commandFolders = fs.readdirSync('./src/commands');

for (const folder of commandFolders) {
    const commandFiles = fs.readdirSync(`./src/commands/${folder}`).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const command = require(`./src/commands/${folder}/${file}`);
        client.commands.set(command.name, command);
    }
    
}



client.once('ready', () => {
    console.log('bot is online');


client.user.setPresence({
    status: 'available',
    activity: {
        name: 'Answering &help',
        type: 'WATCHING',
        url: 'https://www.youtube.com/channel/UC1RUkzjpWtp4w3OoMKh7pGg'
    }
});
});
 


#
client.on('message', 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;
    
        if (command.guildOnly && message.channel.type === 'dm') {
            return message.reply('I can\'t execute that command inside DMs!');
        }
    
        if (command.permissions) {
            const authorPerms = message.channel.permissionsFor(message.author);
            if (!authorPerms || !authorPerms.has(command.permissions)) {
                return message.reply('You can not do this!');
            }
        }
        try {
            command.execute(message, args);
        } catch (error) {
            console.error(error);
            message.reply('there was an error trying to execute that command!');
        }
    });

const distube = require('distube');
client.distube = new distube(client, { searchSongs: false, emitNewSongOnly: true });
client.distube
    .on('playSong', (message, queue, song) => message.channel.send(
        `Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`,
    ))
    .on('addSong', (message, queue, song) => message.channel.send(
        `Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`,
    ))
    .on('error', (message, e) => {
        //console.error(e)
        message.channel.send(`An error encountered: ${e}`)
    })

client.login(token);
opal plank
#

@earnest phoenix doing good so far?

clever agate
#

My bot doesn't send the image manipulation, it doesn't send errors, and it doesn't send the image, I'm My bot doesn't send the image manipulation, it doesn't send errors, and it doesn't send the image, I'm hours looking for the error, but I can't find it, can someone help me?

modest maple
#

dont ask to ask

#

you need to give more context e.g. code blocks, logs etc...

timid blaze
#

:emoji:

earnest phoenix
opal plank
#

<shard>.gateway.setPresence

#

in ur case, Mura.client.gateway....

clever agate
# clever agate code

I tried putting try {} catch(e) {} to see if it catches the error and sends it to the console, but it doesn't work.

opal plank
cinder patio
#

maybe the code block doesn't even execute

opal plank
#

just use a debugger

#

and see whats error'ing

opal plank
#

(assuming u use VSC)

boreal iron
#

No error, no image probably means an error in the image code which canโ€™t be shown if the content type still is an image

lost wadi
#

help

let cofresFiltrados = datosCofre.cofres.filter(x => {
        if(Date.now() > x.cooldown) {
          x.nombre = `โœ… ${require("ms")(x.cooldown)}`
       } else {
         x.nombre = `โฑ ${require("ms")(x.cooldown)}`
       } 
       })
       console.log(cofresFiltrados) //[]

you know why an empty array prints me
||if there are objects in cofresFiltrados||

autumn rampart
boreal iron
#

๐Ÿคฆโ€โ™‚๏ธ

sudden geyser
#

damn why is stackoverflow so agressive with its reputation points

#

can't downvote the question

autumn rampart
#

why

sudden geyser
autumn rampart
#

i was following a toturial

#

@sudden geyser

sudden geyser
#

That does not mean by feedback is not useful.

boreal iron
#

โ€ฆTried to open it?

clever agate
earnest phoenix
#

so I have this line of code that begins a trivia game in which the bot initially notifies the user who triggers the command that the game has started. However I have two seperate initial messages the bot sends and I'd like them to be delayed by 2 or 3 seconds, how would I do this?

async def trivia(ctx, client):
  await ctx.send("My trivia game has 10 questions that you will get to answer.")
  await ctx.send("The game will start in 5 seconds. Get ready!")
boreal iron
sudden geyser
clever agate
#

I will send again

boreal iron
#

Just copy the message ID

clever agate
clever agate
boreal iron
#

Thatโ€™s no code

#

Code != file

clever agate
#

lol

boreal iron
#

canโ€™t open that on mobile

clever agate
#

I said wrong, sorry

clever agate
#
const Discord = require('discord.js')
//const gif = require('@jimp/gif');
module.exports = {
  name: "profile",
  aliases: ["perfil"],
  type: "profile",
   execute(client,message,args) {

    client.db.user.findOne({_id: message.author.id}, async function(e,d) {
      //images
    const background = await(client.jimp.read("./profileTemp.png"));
    const avatar = await(client.jimp.read(message.author.avatarURL({size:4096, format: "png"})));
    const back = await(client.jimp.read("https://media.discordapp.net/attachments/847097535410733056/859427425182810142/20210622_191823.jpg"));
    const verified = await(client.jimp.read("./verified.png"));
  const mask = await(client.jimp.read("./mask.png"));

  //fonts
  const font = await(client.jimp.loadFont(client.jimp.FONT_SANS_32_WHITE));
  const lilita = await(client.jimp.loadFont("./font.fnt"));
  avatar.resize(128,128);
  mask.resize(128,128);
 back.resize(1080,720);
avatar.mask(mask);
verified.resize(36,36);

background.composite(avatar,35,11);
if(verified) return background.composite(verified, 675, 647);
  background.print(lilita,197,58, message.author.username);
  /*background.print(lilita, 786,75, coins);
 background.print(lilita, 931,76, gems);
*/
if(d.config.about) {
 background.print(lilita, 45, 652, d.config.about);
} else {
  background.print(lilita, 45,652, "Use #about e conte mais sobre vocรช!");
}
back.composite(background,0,0);

var image = new Discord.MessageAttachment(await back.getBufferAsync(client.jimp.MIME_PNG));
 client.jimp.write("./assets/profile.png");
message.reply(image);
    });
  }
};```
#

@boreal iron spoonfeed

sudden geyser
#

The essence of sharing code is preserving code that is relevant to the context and leaving out code that is irrelevant in that context.

boreal iron
#

You may try to save the image on the disk to see if itโ€™s a valid PNG image

#

(after the manipulation is done)

clever agate
#

I'll see

autumn rampart
#

i am still getting the error\

earnest phoenix
pale vessel
#

setRateLimitPerUser

#

Ye

clever agate
slender thistle
#

Oh dear

earnest phoenix
#

I'm trying to make a trivia game, but I've run into a problem. Here's my code:

async def trivia(ctx, client):
  point_count = 0
  question_count = 0
  question_limit = 10
  await ctx.send("My trivia game has 10 questions that you will get to answer.")
  await asyncio.sleep(3)
  await ctx.send("You will have 10 seconds to answer each question.")
  await asyncio.sleep(3)
  await ctx.send("The game will start in 5 seconds. Get ready!")
  await asyncio.sleep(5)
  trivia_questions = [
    "What is the rarest M&M color? - Brown",
    "What is the common name for dried plums? - Prunes",
    "What was the first soft drink in space? - Coca Cola",
    "What is the most consumed manufactured drink in the world? - Tea",
    "Which is the only edible food that never goes bad? - Honey",
    "Which country invented ice cream? - China",
    "What was the first toy to be advertised on television? - Mr. Potato Head",
    "Which member of the Beatles married Yoko Ono? - John Lennon",
    "What sport is dubbed the 'king of sports'? - Soccer",
    "On the farm, what is a kid? - Baby Goat"
  ]
  question = random.choice(trivia_questions)
  while question_count < question_limit:
    try: 
      await ctx.send(question)
      input1 = await client.wait_for('message', timeout=10)
      answer1 = input1.content
      question_count += 1
      if answer1 == "bark":
        point_count += 1 
        print(point_count)
        print(question_count)
    except TimeoutError:
      await ctx.send("Your time is up! Please wait for the next question.")
      asyncio.sleep(5)

My problem is that if there is TimeoutError, the program ends and does not continue asking questions, while I would like the program to continue asking questions in it's initial randomized fashion, how would I do this?

#

And bark is just a placeholder, for anyone wondering that reads the code above

#

will replace with some sort of answer that I also have to figure out soon

lyric mountain
#

also, I find brown M&Ms pretty common

earnest phoenix
lyric mountain
#

not that, the concept isn't going to work

earnest phoenix
#

do you mean the concept of a trivia game? may I why?

lyric mountain
#

well, first of all you're only accepting 1 right answer

#

"What sport is dubbed the 'king of sports", if you're british it's called football

earnest phoenix
#

yeah I guess some of the questions are a bit subjective

earnest phoenix
#

well couldn't I just make multiple answers right?

lyric mountain
#

also, coca-cola, coca cola and coke

#

all are right

#

you need to have a list of right answers for every question

earnest phoenix
#

yeah I plan on doing that eventually

lyric mountain
#
[
  "question": ["answer", "answer", "answer", "answer"],
  "question": ["answer", "answer", "answer", "answer"],
  "question": ["answer", "answer", "answer", "answer"]
]
#

like this

earnest phoenix
#

right

solemn latch
#

You'd probably want to fuzzy search your answers anyway.

earnest phoenix
solemn latch
#

Approximate string search.
If your answer is set to coca cola,
Fuzzy search would consider coca-cola or even coke cola as an answer even though you didn't set them as a specific answer.
Deals with a lot of the issues mentioned.

#

Not the football/soccer one though.

lyric mountain
#

research about levenshtein distance, it's probably the easier way to implement fuzzy search

proven lantern
#

use elasticsearch

#

uninstall all sql databases and throw them in the garbage

sudden geyser
#

yuck

proven lantern
#

yucky garbage sql

#

might want to format the hard drive for good measure

fresh verge
#

I don't understand this error.

sudden geyser
#

I don't like most of the alternatives to SQL

#

And Elasticsearch sounds overkill for this job

sudden geyser
#

There are a lot of reasons: no mutual server, blocked, privacy settings, etc.

sudden geyser
#

By catching the error ahead of time

#

And handling it

#

The stacktrace isn't very useful so it's not easy to diagnose where it's coming from specifically

#

other than you're making the api request

fresh verge
#

Add .catch after message.member.send()?

sudden geyser
#

It returns a promise, so yes.

fresh verge
sudden geyser
#

<Promise>.catch(...)

sudden geyser
#

So like context but my own variant

fresh verge
#

@sudden geyser error is not defined.

#

Same thing with err.

sudden geyser
#

May I ask how much experience you have with JavaScript?

sudden geyser
#

Hmm, let's bump that up to 8/10

#

Undefined variable errors are quite common, so you may want to spend more time learning the language.

sudden geyser
#

good job

fresh verge
# sudden geyser good job

Well, now it either doesn't send the check dms even when you do get dmed, or it sends the check dm even when the user blocks the bot/disallow messages from members.

#

Fixed.

earnest phoenix
earnest phoenix
lament rock
#

JS question;
I'm try to leverage Streams and Transformers to offer a feature where the user can limit how many lines a log file can occupy as I write to stdout/stderr where they've been replaced by a fs write stream. However, my issue is that in order to remove lines from the top of the Stream, I figured I'd need to make two passes. 1 would be a dry run where it's purely meant to stat based on the config and then a second time would be to actually transform the file. Is there a more efficient way/a way to work from the bottom up?

lyric mountain
#

Albeit longer, it's really efficient since it's all basic instructions

lament rock
lyric mountain
#

True

#

Can't u skip sections of the stream?

lament rock
#

What purpose would that serve if I meant to transform them later

west spoke
inner fulcrum
#

me when

west spoke
#

If you know the chunks you need to transform, store an int and add that to the array (you're using stdout so I'm assuming you have C operator access as well, otherwise there should be a similar method in js) and it'll have the array which you can modify?

lament rock
# west spoke If you know the chunks you need to transform, store an int and add that to the a...

Well. I don't know how long the Stream is in terms of chunks and I don't know how many chunks I'll be storing in memory. Assume a user allows for 1000 lines to be in the log file then changes their config to 30 for example. I'd have no way to know the previous max value, the current line count without loading the entire file into memory eventually and stat the current state of the log.

inner fulcrum
#

and this is the place where people talk in paragraphs

west spoke
lament rock
#

The max log size could easily exceed the max memory capacity. The goal is to be lightweight at any point in time

west spoke
#

Then you'd have to read a specific address in the file at a time

#

That's the only way to not have to load the entire thing, I think

lament rock
#

I would assume there's no way to start from a specific index based on new lines

clear marlin
#

Redundant Method: Use readline and read the amount of lines in the log file and restrict.

west spoke
#

No, you'd have to look for newlines or ^

#

Though from what I have read they don't want a file stream

lament rock
#

That was what I was gonna go for. Just ended up asking if there was a way to work from bottom up by chance

#

that would make things easier

west spoke
#

Oooooh

#

Dragging me by the tail, huh

#

Hmm

#

Reverse the file stream..?

clear marlin
#

You could use readline-async to make stuff easier

lament rock
west spoke
#

Is it an array or a string

lament rock
#

It's a ReadableStream

west spoke
#

uhhhh

lament rock
#

loads chunks of the file into memory every tick

west spoke
#

Loop over the chunks and add it to an inverted writable stream

#

ie
it = 12;
Offset = stream.size - it;

#

I don't know how js works I'm trying my best

lament rock
#

That's fine. I appreciate the help I have gotten so far. I'm looking into the suggestions

#

Apologies if I'm not doing a great job at explaining my situation to allow general concepts

west spoke
#

then
wstream.chunk[it] = stream.chunk[Offset]

#

which would invert the array after the loop is completed(?)

clear marlin
#
import fs from 'fs';
import readline from 'readline'
const fileStream = fs.createReadStream('logger.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
const linenumber = 0;
for await(const line of rl){
linenumber ++;
// get line information
if(linenumber === 1000){
//break out from your code, or do whatever you want
}
}```
lament rock
#

what's the crlfDelay property control?

clear marlin
#

it should be infinity most of the time

#

also, CRLF Means Carriage Return, Line Feed if you're confused with that

lament rock
#

I do not know much low level terminology, so I appreciate the clarification. I think I understand what the script you wrote does now. I'll try to implement

clear marlin
#

"crlfDelay <number> If the delay between \r and \n exceeds crlfDelay milliseconds, both \r and \n will be treated as separate end-of-line input. crlfDelay will be coerced to a number no less than 100. It can be set to Infinity, in which case \r followed by \n will always be considered a single newline (which may be reasonable for reading files with \r\n line delimiter). Default: 100."

lament rock
#

Was just looking at node docs. Thank you

clear marlin
earnest phoenix
#

So I have this code for a trivia game:

async def trivia(ctx, client):
  point_count = 0
  question_count = 0
  question_limit = 10
  await ctx.send("My trivia game has 10 questions that you will get to answer.")
  await asyncio.sleep(3)
  await ctx.send("You will have 10 seconds to answer each question.")
  await asyncio.sleep(3)
  await ctx.send("The game will start in 5 seconds. Get ready!")
  await asyncio.sleep(5)
  trivia_questions = [
    "How many legs does a spider have?",
    "What is the common name for dried plums?",
    "What is the name of the toy cowboy in Toy Story?",
    "Whose nose grew longer every time he lied?",
    "How many planets are in our solar system?",
    "Which state is famous for Hollywood?",
    "How many pairs of wings do bees have?",
    "What kind of cat is considered bad luck?",
    "What is the name of the pirate in Peter Pan?",
    "What is the largest mammal in the world?"

  ]
  questions_answers = {
    "How many legs does a spider have?" : "8",
    "What is the common name for dried plums?" : "prunes",
    "What is the name of the toy cowboy in Toy Story?" : "woody",
    "Whose nose grew longer every time he lied?" : "pinocchio",
    "How many planets are in our solar system?" : ["eight", "8"],
    "Which state is famous for Hollywood?" : "california",
    "How many pairs of wings do bees have?" : ["two", "2"],
    "What kind of cat is considered bad luck?" : ["black", "black cat", "black cats"],
    "What is the name of the pirate in Peter Pan?" : "captain hook",
    "What is the largest mammal in the world?" : ["whales, a whale, the whales, whale, the whale"],

  }
# some stuff in a while loop below

However for some reason my answers for the non integer or word phrases of the integers seem to be right when I answer to my bot but questions like How many planets are in our solar system? and How many legs does a spider have? come out as wrong according to the bot

#

I even printed out the answers to the questions in console to make sure they 100% match the one I say on the discord channel

#

not sure why this is happening

lethal trout
#
const client = require('../index');

client.on('ready', () => {
    const ch = client.channels.cache.find(channel => channel.id === "821972674380038166")
    const user = client.users.cache.find(u => u.id === "796279185080582185")
    if (client.user.presence.status === 'offline') {
        ch.send(`**<@${user.id}> is offline**`)
    }
})```
it is not sending the message
no errs
slender thistle
#

For questions you'd just rely on dict.keys()

#

How do you process the answers sent by users?

clear marlin
lethal trout
#

i am using a diffrent bot to check another bots status

#
    const client = require('../index');

    client.on('ready', () => {
        //const ch = client.channels.cache.find(channel => channel.id === "821972674380038166")
        let channel = client.channels.cache.get("821972674380038166")
        const user = client.users.cache.get("796279185080582185")
        if (client.user.presence.status === 'offline') {
            channel.send(`**<@${user.id}> is offline**`)
        }
    })```
clear marlin
#

client.user is literally your client instance user i.e., your bot

earnest phoenix
# slender thistle How do you process the answers sent by users?
  }

  while question_count < question_limit:
    try: 
      question = random.choice(trivia_questions)
      answer = questions_answers.get(question)
      print(answer)
      await ctx.send(question)
      input1 = await client.wait_for('message', check=lambda message: message.author == ctx.author, timeout=10)
      answer1 = input1.content
      question_count += 1
      if answer1.lower() == answer:
        point_count += 1 
        await ctx.send("You got it right!")
        await asyncio.sleep(2)
        await ctx.send("Please wait for the next question.")
        await asyncio.sleep(5)
      else:
        await ctx.send("Sorry, you missed the answer! Please wait for the next question")
        await asyncio.sleep(5)
    except asyncio.TimeoutError:
      await ctx.send("Your time is up! Please wait for the next question.")
      await asyncio.sleep(5)
#

someone suggested I use tuples instead of a dictionary, is that a better idea?

#

also sorry for late reply, was busy

#

hello any one know

#

how deploy node js bot in aws

#

cn you pls dm me

#
async def trivia(ctx, client):
  point_count = 0
  question_count = 0
  question_limit = 10
  await ctx.send("My trivia game has 10 questions that you will get to answer.")
  await asyncio.sleep(3)
  await ctx.send("You will have 10 seconds to answer each question.")
  await asyncio.sleep(3)
  await ctx.send("The game will start in 5 seconds. Get ready!")
  await asyncio.sleep(5)
  
  questions = [
      ("How many legs does a spider have?", "8"),
      ("What is the common name for dried plums?", "prunes"),
      ("What is the name of the toy cowboy in Toy Story?", "woody"),
      ("Whose nose grew longer every time he lied?", "pinocchio"),
      ("How many planets are in our solar system?", ["eight", "8"]),
      ("Which state is famous for Hollywood?", "california"),
      ("How many pairs of wings do bees have?", ["two", "2"]),
      ("What kind of cat is considered bad luck?", ["black", "black cat", "black cats"]),
      ("What is the name of the pirate in Peter Pan?", "captain Hook"),
      ("What is the largest mammal in the world?", ["whales, a whale, the whales, whale, the whale"]),
  ]
  
  while question_count < question_limit:
    a_tuple = random.choice(questions)
    question, answer = a_tuple
    question = a_tuple[0]
    answer = a_tuple[1]
    try: 
      await ctx.send(question)
      input1 = await client.wait_for('message', check=lambda message: message.author == ctx.author, timeout=10)
      answer1 = input1.content
      question_count += 1
      if answer1.lower() == answer:
        point_count += 1 
        await ctx.send("You got it right!")
        await asyncio.sleep(2)
        await ctx.send("Please wait for the next question.")
        await asyncio.sleep(5)
      else:
        await ctx.send("Sorry, you missed the answer! Please wait for the next question")
        await asyncio.sleep(5)
    except asyncio.TimeoutError:
      await ctx.send("Your time is up! Please wait for the next question.")
      await asyncio.sleep(5)
#

Well I made it less repetitive by using tuples

#

however the original problem still persists

#

integers and word versions of them don't seem to be accepted but the other ones are

rocky hearth
#

Can someone tell me what "require.main.filename" means here?
path.join(path.dirname(require.main.filename), directory)

earnest phoenix
#

hellp any one help me to deploy my disocord bot in aws

#

pls

stable eagle
earnest phoenix
#

i just pay for 12 month trial

#

i cant know how deploy

#

so i need help

stable eagle
#

Well, then create a server first.

earnest phoenix
#

pls

stable eagle
#

Why?

earnest phoenix
#

we can talk

#

iit easy

#

way for help

mint horizon
#

Howe to upload image to description?

stable eagle
mint horizon
#

Can u do for me?

stable eagle
mint horizon
earnest phoenix
stable eagle
#

Canโ€™t talk rn

earnest phoenix
#

now what i do

#

i alredy pay

#

for that

stable eagle
#

Are you going to use ssh key or a simple root password?

earnest phoenix
mint horizon
#

Idk about html

earnest phoenix
#

i just use microsoft asuz for hosting

mint horizon
earnest phoenix
#

but now i go for aws

#

so i cant know any thing

stable eagle
#

The process is identical to azure and aws

earnest phoenix
stable eagle
mint horizon
#

How
Pls hep

#

Pls help me upload image to description
I send u image ;-;

stable eagle
#

an additional alt Attribute can be added

#

To replace the image if it doesnโ€™t load

earnest phoenix
#

Hello how can I make my website link embed like this https://top.gg/

#

@stable eagle Can you tell me?

stable eagle
earnest phoenix
stable eagle
earnest phoenix
#

Thanks

#

hi

true ravine
#

Do I need the members intent to see all guild members possessing a certain role? I have seen advaiths guide but I couldn't see anything relating to this

earnest phoenix
spare badger
worn sonnet
slender thistle
#

And str == list will never be True

modest maple
slender thistle
#

I ain't fucking around with operator overloading for this ty

modest maple
#

But ctypes CRSad

earnest phoenix
#

is it bad that I don't know what operator overloading is

#

also i got it to work so its fine

earnest phoenix
slender thistle
#

Huh

earnest phoenix
#

here uh

#

ill send the full code

#

gonna have to send this in two parts

earnest phoenix
#
async def trivia(ctx, client):
  point_count = 0
  question_count = 0
  question_limit = 10
  await ctx.send("My trivia game has 10 questions that you will get to answer.")
  await asyncio.sleep(3)
  await ctx.send("You will have 10 seconds to answer each question.")
  await asyncio.sleep(3)
  await ctx.send("The game will start in 5 seconds. Get ready!")
  await asyncio.sleep(5)
  
  questions = [
      ("How many legs does a spider have?", "8"),
      ("What is the common name for dried plums?", "prunes"),
      ("What is the name of the toy cowboy in Toy Story?", "woody"),
      ("Whose nose grew longer every time he lied?", "pinocchio"),
      ("How many planets are in our solar system?", ["eight", "8"]),
      ("Which state is famous for Hollywood?", "california"),
      ("How many pairs of wings do bees have?", ["two", "2"]),
      ("What kind of cat is considered bad luck?", ["black", "black cat", "black cats"]),
      ("What is the name of the pirate in Peter Pan?", "captain hook"),
      ("What is the largest mammal in the world?", ["whales", "a whale", "the whales", "whale", "the whale"]),
  ]
#
  while question_count < question_limit:
    question, answer = random.choice(questions)
    print(question)
    print(answer)
    try: 
      await ctx.send(question)
      input1 = await client.wait_for('message', check=lambda message: message.author == ctx.author, timeout=10)
      answer1 = input1.content
      question_count += 1
      print(question_count)
      print(point_count)
      if answer1.lower() in answer:
        point_count += 1 
        await ctx.send(f"You got it right! Point Count: {point_count}")
        await asyncio.sleep(2)
        await ctx.send("Please wait for the next question.")
        await asyncio.sleep(5)
      else:
        await ctx.send("Sorry, you missed the answer! Please wait for the next question")
        await asyncio.sleep(5)
    except asyncio.TimeoutError:
      await ctx.send("Your time is up! Please wait for the next question.")
      await asyncio.sleep(5)
  await ctx.send(f"The game is over! Thank you for playing. Your final score was {point_count} points. Good job!")
#

^ this

#

it executes as I want it to, now I just have to figure out how to make it so the last msg doesn't say "Please wait for the next question" again

#

but like

#

its 3 Am for me rn so I'll probably do it tomorow

slender thistle
#

Yeah that makes sense with the in operator

earnest phoenix
#

Guys i need help

earnest phoenix
earnest phoenix
slender thistle
#

Actually, not exactly

#

Try replying with e when the answer is eight

#

or o for woody

earnest phoenix
#

oh christmasthink

slender thistle
#

Yup

earnest phoenix
#

well this is awkward KEKW

true ravine
slender thistle
pale vessel
slender thistle
#
if isinstance(answer, str):  # One answer
    condition = answer == input1
else:  # Iterable as answer, aka tuple or list
    condition = input1 in answer
true ravine
#

But can't you do GuildRole.members in djs? Or is that basically doing the same thing

#

I've always worked with the safety of a lib do idk what some of these methods actually do

hybrid scroll
#

hey anyone knows any good image gen api something like what owo does

earnest phoenix
earnest phoenix
#

and I'm not familiar with isinstance but i looked it up on the documentation and think I kind of get it

slender thistle
#

In case that an answer is of type str, meaning there's only one accepted answer for it, it will compare the user input directly to the answer, hence the == and not the in

#

Because if you used in, specific letters from the string could be considered an answer

slender thistle
#

What you use condition for is to confirm that the user entered the correct answer

#

It will be of type bool, so you can just do if condition: to do something if answer was correct

hybrid scroll
near stratus
#

You can set whatever you want
keep in mind
You have 1000 servers
every server has one rainbow role
you're changing the color every 10 seconds
1000 api requests every 10 seconds
100 api request every second
That's api abuse

rocky hearth
#

what is djs-threads is all about?

earnest phoenix
#

thanks for the elaboration

#

yeah it works correctly now, I can't type in a single letter for a right answer anymore KEKW

slender thistle
#

๐Ÿคฃ

earnest phoenix
#

I'm using node-canvas's Image class and I want to generate a solid colour image. How can I do that?

rocky hearth
#

for slash commands. Should I register the commands on client ready or before it gets ready??

earnest phoenix
#

actually why would you register commands on every run

rocky hearth
#

as the guild is not available in the cache. client.guilds.cache

earnest phoenix
#

in that case do it in the ready event

rocky hearth
#

global commands too?

jovial nexus
#
npm ERR! code 127
npm ERR! path /root/KiroBot/node_modules/canvas
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build
npm ERR! sh: 1: node-pre-gyp: Permission denied

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-06-30T08_56_00_087Z-debug.log```
im getting this when trying to install canvas and discordjs/opus
slender thistle
#

Rust, egui
Is there any way to take up ALL of possible window width in a Widget? Ui::available_size() returns a Vec2 which has a small margin from the corners of the window.

cinder patio
#

Not sure what the Image class has to do with anything tho

#

it's for loading images

jovial nexus
earnest phoenix
#

@cinder patio i wanted a literal image because i was going to use it in ctx.drawImage

#

Anywas I figured it out

#

Just set image.src to canvas.toDataURL()

cinder patio
#

you said you wanted to generate a solid colour image though thonkku

#

also why not just draw the color yourself

earnest phoenix
#

i just made a 1px ร— 1px canvas and colored it

#

then drew the image to whatever size i want

pale vessel
#

Why not just directly draw it?

cinder patio
#

yeah why

bitter bramble
#

Why does my bot dont get any role in its name when its added to any server?

bitter bramble
#

And pls ping me when answering to my question

rocky hearth
#

what is a. staged channel. and whether a bot can join it or not?

vivid fulcrum
#

stage channel*

rocky hearth
#

hmm ok. So I guess bots can join it, right?

eternal elbow
#

TypeError: serverQueue.connection.dispatcher.seek is not a function
Wasn't there such a function in discord.js?
connection.dispatcher.seek(ms)

cinder onyx
#

Hey can you tell about that vote message ?

#

User vote for yourbot

#

That thing

lyric mountain
cinder onyx
lyric mountain
#

no

#

discord webhook isn't a webhook

#

it's just a "remote messenger"

#

webhooks are reverse-apis

cinder onyx
#

Can you tell me more about it how can I make one for my bot ?

#

Like any docs

#

Something

lyric mountain
#

what language?

cinder onyx
#

js or py okay

lyric mountain
#

which one is the one you made your bot in?

cinder onyx
#

Js

lyric mountain
#

all the docs you need are included there

cinder onyx
#

Thanks

cinder onyx
lyric mountain
#

yep, it's the official wrapper for top.gg

cinder onyx
#

Ty

signal estuary
#

How can I send a message into a channel when I invoke the event 'on GuildCreate' with hte object 'guild'?

quartz kindle
#

you need to get a channel from the guild object by some criteria

earnest phoenix
#

Does somebody knows how can i do v12 this code ?

#

It works on v11 but not on v12

lyric mountain
#

did you just use รง on code?

signal estuary
#

I want to delete a certain number of messages from a certain user.
So I need to fetch a certain number of messages from a user. How can I do this

vivid fulcrum
#

keep fetching messages in batches

#

filter the fetched messages

#

repeat if the count doesn't match the n elements desired

#

you should probably put a limit on that though

#

i.e. 10 fetches of 100 messages

#

i didnt mean to send that ok ๐Ÿ’…๐Ÿป

#

and i cant delete it

#

perfect

lyric mountain
#

r/AwfulEverything

smoky kestrel
#
        !client.setups.get(message.guild.id, 'aichatsystem.enabled')
                       ^

TypeError: Cannot read property 'get' of undefined
    at AiCommand.run (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\src\commands\fun\AiCommand.js:26:24)
    at MessageEvent.run (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\src\events\message\MessageEvent.js:21:17)
    at Client.emit (node:events:394:28)
    at MessageCreateAction.handle (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (node:events:394:28)
    at Receiver.receiverOnMessage (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\websocket.js:833:20)      
    at Receiver.emit (node:events:394:28)
    at Receiver.dataMessage (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\receiver.js:517:14)
    at Receiver.getData (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\receiver.js:435:17)
    at Receiver.startLoop (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\receiver.js:143:22)
    at Receiver._write (C:\Users\TAHIR ISLAM\Desktop\venomous\Venomous\node_modules\ws\lib\receiver.js:78:10)
[nodemon] app crashed - waiting for file changes before starting...
#

how to solve

tulip ledge
smoky kestrel
tulip ledge
#

client.setups is undefined

#

@smoky kestrel

smoky kestrel
#

how to solve

#

client is bot :/

#

and why setups need declaration

#

:/

tulip ledge
#

Cant do much without codz

#

Are u sure its not setup instead of setups?

smoky kestrel
#

ok lemme see

solar cave
#

guys

#

my bot is running on 1gb RAM and 1 core cpu (only 50% usable)

#

what should i increase ?

solemn latch
#

well, are you hitting any limits?

digital swan
#

is it possible to get user banners on discord.js yet?

sly sierra
#

No

digital swan
#

rip

signal estuary
#

Hey, I am trying to delete messages buy a certain user. But the bot doesnt filter the messages. Here is the code:

userToDelete = await msg.mentions.users.first() || await client.users.fetch(args[1]).catch(() => { })
let numberMessages = args[0];
        await msg.channel.messages.fetch({ limit: numberMessages }).then(messages => {
    
            const messagesToDelete = messages.filter(msg => msg.author.id === userToDelete.id)
            messagesToDelete.forEach(msg => {
                console.log(msg.content)
            });
        })

userToDelete is the user I mention (works fine)
numberMessages is fine, too (if (isNaN(numberMessages)) return)
console.log(msg.content) returns the latest <number> messages (by all users)
So I dont know what the problem is. Can anyone help me?

stiff lynx
#

This is a Date.now() output : 1625066662626
How can I input a date for 00:00:00?

#

Because I want to set a cooldown until 00:00:00 and after the command set it again at 00:00:00

opal plank
#

use cron jobs for that

lusty quest
#

or use redis TTLs

opal plank
#

that'd work too, but if u dont use redis, go for cron's

lusty quest
#

depending on what you do

#

if you have a cooldown on commands i would use Redis

stiff lynx
lusty quest
#

(like a 24 hour cooldown)

opal plank
#

look one up

stiff lynx
#

but these are packages?

opal plank
#

look

#

it

#

up

stiff lynx
#

what does mean look it up?

opal plank
lusty quest
#

you could make it yourself, but if you have to ask if its a package you probably wont manage to do so

opal plank
stiff lynx
#

thank you

opal plank
#

np

opal plank
#

cuz i 100% know you coming back to ask how to do it

stiff lynx
#

0 0 * * *

#

should be this

opal plank
#

correct

stiff lynx
#

40 packages are looking for funding
run npm fund for details

4 high severity vulnerabilities

What is this?

opal plank
#

should be able to do audit fix or just ignore it

#

if u installed a big package, that is

#

wouldnt trust small packages with those

stiff lynx
#

I have another question, help about installing ffmpeg on a vps (Centos 8.3 x64), guides on internet doesnt work, idk why

stiff lynx
#

In europe timezones are kinda trash

lusty quest
#

lol how are they trash? like you get some relatively easy to calculate ones

worn sonnet
#
@command(name="addrole", help="Add a new server role, with optional color and hoist.")
    @has_permissions(manage_roles=True)
    async def add_role(self, ctx, name: str, color: Optional, hoist: Optional[bool]):
        try:
            role = await ctx.guild.create_role(name=name, color=int(color, 0), hoist=hoist)
            await ctx.send(embed=Embed(description=f":white_check_mark: Created a role {role.name}"))
        except (Forbidden, HTTPException):
            await ctx.send("It seems I don't have permission to create roles")
#

Everytime i wanna create some function with optional parameters more than one

#

i stuck at it

latent heron
#

do.. you know exactly what you're even doing?

worn sonnet
#

yep

#

I'm creating a cmd to create roles

latent heron
#

no, i mean, with the optional arguments

#

do you know how you're supposed to be writing them?

worn sonnet
#

an ideal formal would be something like this
!addrole role_name 7890 true

#

but i wanna make the other two params optional

#

that color and hoist

#

where as hoist is bool

#

so if I type cmd something like this
!addrole role_name true

#

it should ignore color parameter

stiff lynx
worn sonnet
#

or should i just make a group cmd?

opal plank
stiff lynx
lusty quest
opal plank
stiff lynx
#

so it isnt my timezone

opal plank
#

ask later

#

offset will tell you how far from UTC time you are

stiff lynx
#

I can get the vps timezone in a console log and then add at gmt?

opal plank
#

UTC*

stiff lynx
#

('August 19, 1975 23:15:30 GMT+07:00');

#

gmt cool_cat

opal plank
stiff lynx
#

('August 19, 1975 23:15:30 UTC + difference between console.log and my actual hour');

#

right?

opal plank
#

or -

#

but yes

stiff lynx
opal plank
#

The getTimezoneOffset() method returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.

#

in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.

#

in minutes

#

why u dividing 480/8?

#

480 is the amount of minutes between a timezone in UTC-8 to UTC-0

#

so its foward 480

#

if u have 2 timezones

#

you need to know hwo many minutes/hours are between eachother

#

if one is at UTC-5, and your target in UTC-8, you'd get a difference of 3h(60*3)

slender thistle
#

Ho dear

slender thistle
opal plank
crimson vapor
#

I donโ€™t know too much about python but I donโ€™t think it looks like that

autumn rampart
opal plank
#

the keyboard color, macbook, tiny screen, having an externcal keybaord when the point of a laptop is being compact

#

i've spotted a few things already, but idk, they suddenly jumped at me the moment i looked at it, but i couldnt figure out why i disliked it

crimson vapor
#

The water bottle

#

Metal > plastic

opal plank
#

HACK in the bottle, as a dev, is a sin

#

clearly not a dev mmulu

opal plank
autumn rampart
#

so what would i change

opal plank
#

read that

crimson vapor
earnest phoenix
#

you can just reply to the interaction itself

#

interaction.reply(options)

opal plank
#

i use detritus, not that shit

earnest phoenix
opal plank
#

it should work as is

earnest phoenix
#

bro just donโ€™t share that document in the first place

earnest phoenix
opal plank
#

literally the first result

#

and by one of the most active guys in ddevs

#

and with 110 stars

earnest phoenix
#

itโ€™s old

opal plank
earnest phoenix
#

pretty sure it was before v13 dev came out

opal plank
earnest phoenix
#

oh yours is for v12

opal plank
#

did u bother reading it?

earnest phoenix
#

the one i sent is the proper way of doing it on v13

opal plank
#

its the same link

earnest phoenix
#

yes so send something that doesnโ€™t use that then???????????

opal plank
#

FUCKING READ IT?

earnest phoenix
#

just shush fam honestly

opal plank
#

it says to use v13

#

in the fucking docs

#

are you tripping bals

earnest phoenix
#

your weird man

opal plank
#

If you are using client.api you should switch over to official support. The following legacy information is not recommended or supported for use.

#

learn how to read brother

earnest phoenix
modest maple
#

CoffeeSip Suddenly remembers why I avoid this channel

signal estuary
#

Hey, I am trying to delete messages buy a certain user. But the bot doesnt filter the messages. Here is the code:

userToDelete = await msg.mentions.users.first() || await client.users.fetch(args[1]).catch(() => { })
let numberMessages = args[0];
        await msg.channel.messages.fetch({ limit: numberMessages }).then(messages => {
    
            const messagesToDelete = messages.filter(msg => msg.author.id === userToDelete.id)
            messagesToDelete.forEach(msg => {
                console.log(msg.content)
            });
        })

userToDelete is the user I mention (works fine)
numberMessages is fine, too (if (isNaN(numberMessages)) return)
console.log(msg.content) returns the latest <number> messages (by all users)
So I dont know what the problem is. Can anyone help me?

opal plank
signal estuary
opal plank
#

first() doesnt return a promise

#

no need to await it

#

one thing that you should absolutely do is use await OR then

#

preferably await, dont mix them

#

await msg.channel.messages.fetch({ limit: numberMessages }).then( => bad

#

let messages = await msg.channels.....fetch(); => good

opal plank
signal estuary
#

the problem is it works but the messages wont be filtered

opal plank
#

exactly what i said

#

you have a catch() block in the end

#

and its not returning anything

#

if u dont mention anyone, and the fetch() fails, the userToDelete is undefined

#

hence ur filter functions searches for message with user.id = undefined

signal estuary
opal plank
#

then use this

signal estuary
#

I am logging

#

I know how to debug

#

its not a debugging problem

opal plank
#

hmmm lets see

#

also console.log isnt debugging

opal plank
#

as userToDelete

signal estuary
# opal plank what does it show in console?

I just got it. I had to loop over both messages:

            messages.forEach(msg => {
                console.log(msg.content)
                const messagesToDelete = messages.filter(msg => msg.author.id === userToDelete.id)
                messagesToDelete.forEach(msg =>{
                    console.log(msg.content)
                })
            });
#

Works now

earnest phoenix
#

because you will pretty much always run into the two event loop same thread issue
@modest maple why would it run into 2 event loops if it only makes one when there's no running event loop?

modest maple
#

because asyncio.run is being pushed as becoming the standard and that always makes a new event loop

#

so get_event_loop makes a new loop if one isnt running

#

so if you have say the current client setup

#
bot = discord.Client()

#

doing asyncio.run() will break your expected behaviour because bot.loop no longer becomes the current running loop.

#

so in your traditional:


client = discord.Client()
topgeegee = topgg.ClientThing(client)

@client.event
async def foo():
  ...


async def main():
    await client.start()

asyncio.run(main())
#

would run into the two event loops issue as it currently stands

#

hence why discord.py in v2 is planning to move away from the tradition client.run and will likely need to adjust how the client.loop behaves or just remove it entirely / make it a property for getting get_running_loop

#

and this is where it would require either re-designing the top.gg py sdk for supporting v2 and v1 together or require another setup for v2 entirely

earnest phoenix
#

Ah, so it should be "get" only?

modest maple
#

eh?

earnest phoenix
#

How should it behave when there's no running event loop?

earnest phoenix
modest maple
#

TL;DR of how asyncio is moving: get_event_loop going, get_running_loop should be used everywhere (which is correct but people always abuse get_event_loop hence why it's not used as much as it should be)

#

the old asyncio.get_event_loo().run_until_complete() should be replaced by asyncio.run() which handles cleanup as well

earnest phoenix
#

I see, so it's just gonna be a crash if the user hasn't started a loop?

modest maple
#

basically trying to remove the things that people always hang themselves on

#

well crash if it's not in a async context

#

which is better than the current; fail with undefined behaviour by just not working how you expect vs explicitly

#

take asyncio.Event for example

#

if you dont do that in a async context

#

it wont work correctly at all because it uses get_event_loop internally (which is being moved to get_running_loop in future versions)

earnest phoenix
#

I see, that makes sense. But I don't see why it's bad to get a running loop or make one inside the run method, considering it's a high-level method so that users don't need to clean up the ws connection

modest maple
#

its just a ecosystem thing

#

in the same way you generally expect code to be formatted according to PEP8 or web frameworks to follow something like PEP333(3)

#

the idea is the developer controls starting and initiate the main function

#

this arguably make the code more explicit about what you're doing

#

if you think about how many people come in here using repl.it or some web framework and wondering why their code under client.run doesnt run

earnest phoenix
#

Aha

#

Yeah, that's a thing

west spoke
true ravine
#

Could anyone point me to any 'model' (i.e the kind of thing people should copy) open source projects on github so I can try and pick up some best practices?

lyric mountain
#

if you're copying it's already a bad practice

#

basically keep 5 things in mind:
1 - If you're repeating something too much, it's time to use a variable/function
2 - You write for humans to read, not for computers
3 - Use proper casing for the situation
4 - If you open, you close
5 - Always prefer while/for or switch over repeated ifs

solemn latch
#

also, many "rules" of programming are language specific and learned over time.
just giving a code base to look at really isnt helpful in most cases.

boreal iron
#

Just an advanced question about RewriteRules

https://api.domain.com/3646119?api-key=test

My current RewriteRules don't accept query arguments starting with a ? (instead of a &)

    RewriteEngine On
    RewriteRule ^/?(.*) /index.php?lookup=$1 [PT,L]

As you can see the requests will be redirected (as passthrough) to /index.php?lookup=3646119

I wanna provide the api key as "first" query argument which doesn't work at the moment.
Any other query argument starting with a ? will be cut off of course.

How should the RewriteCond be like to transform the request example (mentioned above) to:

https://api.domain.com/index.php?lookup=3646119&api-key=test

jovial nexus
#

How can i add the in-built minigames in discord to my bot?

solemn latch
#

like activities?

#

it depends on the language and library

jovial nexus
#

yes, in Discord.js

jovial nexus
sudden geyser
#

Those aren't built in to Discord, unless I'm confusing something

jovial nexus
#

I saw a bot that sends you an invite ,and you can play it in any vc

solemn latch
#

yeah, dont think discordjs supports that yet

jovial nexus
#

i can add other language modules if need them

solemn latch
#

well, you can make something custom to add that support to djs. detritus might support it

jovial nexus
#

mhmmmm...

earnest phoenix
latent heron
#

I really wouldn't call them rules

#

they're merely practices

#

bad practices will eventually lead to underperforming code

jovial nexus
earnest phoenix
lyric mountain
boreal iron
#

@woeful pike Do you may have an idea?

#

(few lines above)

opal plank
#

?

solemn latch
#

yeah