#development

1 messages ยท Page 949 of 1

balmy knoll
#

Yes

nocturne grove
#

okay

balmy knoll
nocturne grove
#

oh in the API it's called news, I'm sorry

balmy knoll
#

No problem

nocturne grove
#

https://discord.js.org/#/docs/main/stable/class/NewsChannel there's a send() method here, so yes, you can (as long as it has perms of course)

balmy knoll
#

Thanks

nocturne grove
#

No problem

balmy knoll
#

Wait

#

Send is to send message in this channel

opaque seal
#

For how much time should I keep a prefix in the cache?

nocturne grove
#

@balmy knoll you meant reacting with an emoji?

opaque seal
#

For how much time should I keep a prefix in the cache?
I thought about 5 mins

quartz kindle
#

@opaque seal forever, as long as it remains unchanged

nocturne grove
#

I guess that's possible, I see no reason why it shouldn't work if a bot can send a message in such a channel

quartz kindle
#

if someone changes the prefix, then you remove it so it can update

opaque seal
#

Dosen't that make the ram go crazy?

quartz kindle
#

no

#

as i said before, it will use about 1-2kb of ram per 500 guilds

opaque seal
#

I'm trusting you then

quartz kindle
#

so you can slap it with 5 million guilds and it will still use only 20mb of ram

balmy knoll
#

@nocturne grove I mean publish a message in a news channel

opaque seal
#

so you can slap it with 5 million guilds and it will still use only 20mb of ram
dope

nocturne grove
#

@balmy knoll that's the send() method

#
newsChannel.send('Hey!');```
opaque seal
#
let guildID = message.guild.id;
    let prefix='$';
    let data;
    // Prefixes
    let prefixes = client.prefixes;

    if (!prefixes.has(guildID)) {
        prefixes.set(guildID, new Discord.Collection());
    }
    const guildPrefix = prefixes.get(guildID);
    if (guildPrefix) {
        prefix = guildPrefix.prefix;
    }else{
        await client.guildSchema.findOne({guildID: guildID}, (_,res) =>{
            data = res;
        })
        if(data) prefix = data.prefix;
        else return;
    }
    guildPrefix.set(prefix);```
I've tried that so far, how does it look @quartz kindle ?
quartz kindle
#

you're only ever gonna have 1 prefix per guilds right?

#

so you dont need a collection

opaque seal
#

yeah

#

Is using Discord collection a bad idea?

quartz kindle
#

yes

#

collections are for storing lists of items, you're only storing 1 item

opaque seal
#

'cause I remodeled the cooldown stuff that the discord.js guide gives

#

collections are for storing lists of items, you're only storing 1 item
So...uhm, what's the best variable for that?

quartz kindle
#

a simple string

opaque seal
#

Because I need the guild ID and the prefix

digital ibex
#

@earnest phoenix do u know what u need to do?

quartz kindle
#
if(!client.prefixes.has(guildID)) {
  let prefixInDB = await client.guildSchema.FindOne(guildID) // or however you use this
  if(!prefixInDB) {
      client.guildsChema.SaveOne(,guildID,"$") // or whatevr you use to store
      client.prefixes.set(guildID,"$");
  } else {
      client.prefixes.set(guildID,prefixInDB);
  }
}
let prefix = client.prefixes.get(guildID)
opaque seal
#

oh I thought you meant the prefixes variable to not be a collection

quartz kindle
#

client.prefixes can stay a collection, since it holds multiple items

opaque seal
#

yeah yeah I got it

quartz kindle
#

but client.prefixes.set(guildID) doesnt need to be a collection

earnest phoenix
#

@earnest phoenix do u know what u need to do?
@digital ibex no

opaque seal
#

yeuah

#

So it's like an object with GuildID and prefix, guildID and prefix and so on

digital ibex
#

for sharding, u just change ur clients options

#

thats all

earnest phoenix
#

I mean how do I get the guild count across all shards

#

also I use eris-sharder for shards

opaque seal
#
if(!client.prefixes.has(guildID)) {
  client.prefixes.set(guildID,"$");
  client.guildsChema.SaveOne() // or whatevr you use to store
}
let prefix = client.prefixes.get(guildID)

If the prefix is not in the collection I need to get it from the database thought

#

not just set it as "$"

quartz kindle
#

@opaque seal see updated message

opaque seal
#

The prefix is always in the DB thought.
I've done that

// Prefixes cache (not cash lol)
    let prefixes = client.prefixes;

    if (!prefixes.has(guildID)) {
        await client.guildSchema.findOne({guildID: guildID}, (_,res) =>{
            data = res;
        })
        if(data) prefix = data.prefix;
        else return;
        prefixes.set(guildID, prefix);
    }
    const guildPrefix = prefixes.get(guildID);
    if (guildPrefix) {
        prefix = guildPrefix.prefix;
    }```
quartz kindle
#

the prefix is not always in the db

#

unless you add it immediately on the guildCreate event

opaque seal
#

It is in my Database

#

Yeah I do that

quartz kindle
#

alright then yes

opaque seal
#

Is that bad practice?

quartz kindle
#

no, not really, but it can be waste of cpu since a a guild can be joined and left without being used once

opaque seal
#

Usually who invites the bot wants to use it I think

#

There would not be many cases where that guild in the Database would not be used

quartz kindle
#

happens more often than you think, because people are stupid

#

but its not a problem

opaque seal
#

lol

quartz kindle
#

that wont make or break your bot

opaque seal
#

I'll keep it like that for the moment

#

I could do that each time a command is used it checks for the database and sees if it's set up for that guild

quartz kindle
#

my database only contains custom prefixes, not defaults

#

so its only ever saved if they change the default, otherwise it doesnt save anything

opaque seal
#

could be an idea

#
const guildPrefix = prefixes.get(guildID);
if (guildPrefix) {
        prefix = guildPrefix.prefix;
}```
How do I get the prefix of the guildPrexif?
#

Is it right like that?

quartz kindle
#

depends on how you set it

opaque seal
#

prefixes.set(guildID, prefix);

quartz kindle
#

and prefix is already the string, right?

opaque seal
#

yes

quartz kindle
#

then .get() already returns it

#

so guildPrefix is already the prefix

opaque seal
#

oh

quartz kindle
#

there is no guildPrefix.prefix

opaque seal
#

const guildPrefix = prefixes.get(guildID); if (guildPrefix) prefix = guildPrefix;

#

should be good

quartz kindle
#

yes

opaque seal
#

Nice, thank you for your help

nocturne grove
#

my database only contains custom prefixes, not defaults
@quartz kindle I got that too. Do you also delete the prefix from the database when they change it back to the default?

pure lion
#

how do i get specific items from a dir file?

quartz kindle
#

@nocturne grove actually i dont

#

i dont even delete it when the bot leaves the guild lmao

#

i should tbh

nocturne grove
#

oh lmao

#

I even delete the whole guild row when the prefix is set to default and nothing else is in it

quartz kindle
#

yeah im probably gonna do the same

#

i just hate updating the bot and having to restart it lmao

opaque seal
#

I delete all guild related info from the database when the bot leaves

nocturne grove
#

hahaha

#

never thought I'd inspire you xd

quartz kindle
#

i was alrady meaning to do that before, but i forgot

nocturne grove
quartz kindle
#

@pure lion you mean you want to read files from a directory?

pure lion
#

wait hold on

#

im not entirely sure

#

lemme get details

#

and try to make sense

#

so, say im using youtube-search for my music bot. i plug in args 1, and it console logs the entire dir. i want to access the url, but i have found no way of doing this (the url, in the console, is situated next to "url:") no idea if this is enough info or helps me in any way

quartz kindle
#

the structure is probably a json file

#

do you know how json works?

pure lion
#

is it bad that i dont?

quartz kindle
#

its a fairly essential thing to learn

#

for example

#
thisIsAnObject = {
  a:10,
  b:20,
  c: {
    c1:50,
    c2:60
  }
}
#

if you want to get 20, you do thisIsAnObject.b

#

if you want to get 60, you do thisIsAnObject.c.c2

pure lion
#

ohhhhhhhhhhhhh

quartz kindle
#

json follows the same rules

#

however, you need to pay attention to possible arrays mixed in

#

for example: ```js
thisIsAnObject = {
a:10,
b:[
{
c:10
},
{
c:20
}
]
}

#

you see that b starts with [ which means its an array

#

arrays use index numbers instead of keys

#

so to get the value 20, you would need to do thisIsAnObject.b[1].c

#

where [1] is the second item (because indexes start with 0)

pure lion
#

<writing noises>

#

ok

#

hmmmmm

terse lynx
#

how to mention user in java

#

like this @terse lynx

pure lion
#

hmm

#

java or java_script_

#

?

terse lynx
#

java

pure lion
#

ok

#

hmmmmmmmmmmmm

quartz kindle
#

you can mention a user by sending <@USERIDHERE> in any language

pure lion
#

idk how to interpret this for ytdl

quartz kindle
#

show the ytdl response

pure lion
#

well

#

const songInfo = await ytdl.getInfo(results);

#

results is the dir

#

but idk how to access

quartz kindle
#

console.log(results)

terse lynx
#

in js

pure lion
#

access the dir object thing (brb)

quartz kindle
#

js is javascript, not java

pure lion
#
method: 'get',
    url: 'https://www.googleapis.com/youtube/v3/search?q=bloodbath&part=snippet&maxResults=1&key=AIzaSyCKC-2EQzfCqU63ZfVN1wxYOLj4z3nTtKU'
terse lynx
#

js used in BOTS

pure lion
#

thats in the console

slender thistle
#

Java is used in Discord bots too

clever tree
#

I installed the original ffmpeg in my systempaths. My bot still joins the channel but has no audio playing. He stays in for the song duration but has no sound. :/

terse lynx
#

yes

pure lion
#

I installed the original ffmpeg in my systempaths. My bot still joins the channel but has no audio playing. He stays in for the song duration but has no sound. :/
did you npm i ffmpeg-static ?

clever tree
#

yes.

pure lion
#

hmmmmmm

#

opus?

quartz kindle
#

@pure lion where did you get results from? that doesnt look like a ytdl response

pure lion
#

brb

quartz kindle
#

also, you should reset your youtube key

clever tree
#

@pure lion Yeah. I have node-opus and all build tools. The Bot worked fine for 2 weeks since yesterday he doesnt play audio anymore xd

pure lion
#
var search = require('youtube-search')

  var opts = {
    maxResults: 1,
    key: '(my key)'
  };

  search(args[1], opts, function(err, results) {
    if(err) return console.log(err);
   
    console.dir(results);
  
  const songInfo = await ytdl.getInfo(results);
  const song = {
    title: songInfo.title,
    url: songInfo.video_url
  };
#

blep

terse lynx
#

how to make bots in c++

pure lion
#

learn c++

terse lynx
#

i know

#

i have learned

pure lion
#

then learn c# and forget c++

terse lynx
#

why

summer torrent
quartz kindle
#

any reason you're using console.dir and not console.log?

opaque seal
#

How can I check if this filter did something or if the variable remained the same, do I necessary have to create another variable for comparison?
halls = halls.filter(element => message.guild.channels.cache.get(element.hall))

pure lion
#

any reason you're using console.dir and not console.log?
no idea

#

let me check why

quartz kindle
#

try using console.log

terse lynx
#

me?

quartz kindle
#

no, elisdia

pure lion
#

great

#

perfect

#

w o n d e r f u l

#

SyntaxError: await is only valid in async function

quartz kindle
#

async (err, results) => {

#

@opaque seal it should work

#

you can check if halls got any smaller afterwards

opaque seal
#

uhm

#

how can I do that? I mean the variable already changed I can't check its earlier status

quartz kindle
#

record its length before and after

opaque seal
#

ok

#

thx

quartz kindle
#

you dont even need to make a variable, you can just console.log it

pure lion
#

i know why it doesnt do console.log

digital ibex
#

hi, i'm getting this error: user_id: Value "475371795185139712,475371795185139712,475371795185139712" is not snowflake. i know what the error means and why i'm getting it, but i don't know how to fix it. the code:

pure lion
#

well, i dont

#

hi, i'm getting this error: user_id: Value "475371795185139712,475371795185139712,475371795185139712" is not snowflake. i know what the error means and why i'm getting it, but i don't know how to fix it. the code:
@digital ibex what are your intentions?

digital ibex
#
await client.getRESTUser(guild.moderations.filter((e) => e.kick.user === member.id).map((e) => e.kick.mod));
#

wut

#

i'm just trying to get the username of a user

#

using eris

quartz kindle
#

you're trying to get an array of users?

pure lion
#

h

digital ibex
#

no like, i got this, js [ kick: { user: 'id', mod: 'id', /* other data */ } ] and i'm trying to get the mod for each moderation action on a user, i'm getting the moderator

quartz kindle
#

guild.moderations seems to contain several references to the same user, so if you use .filter(), you'll get all of them

digital ibex
#

yeah, i got this, js const kick = guild.moderations.filter((e) => e.kick.user === member.id).map((e) =>`__**Kick:**__\n**Mod:** ${e.kick.mod}\n**Reason:** ${e.kick.reason}\n**Case:** #${e.kick.case}`).join('\n-\n'); but i trying to get the mod only from the mods id

quartz kindle
#

so you want to get the mod and do what with it?

digital ibex
#

get their username

quartz kindle
#

ok, so you have several moderations with the same user, and each of those moderations can have the same mod

#

first you need to separate unique mods into a set or object, then you need to fetch each separate mod individually

#

then join the data together again

#

for example

#
let modUsernames = {};
let filtered = guild.moderations.filter(...);
for(let moderation of filtered) {
  if(!modUsernames[moderation.kick.mod]) { modUsernames[moderation.kick.mod] = (await getRESTUser(moderation.kick.mod)).username }
  let username = modUsernames[moderation.kick.mod];
}
still merlin
#

I'm trying to make a say command and I don't want to do {args[*number*]} for 998 charecters is there something similar to: {args[past_1]} that would work, to get the first argument and everything after that

digital ibex
#

oh

#

slice the args amazrisf

#

imma try it, thank u tim

quartz kindle
#

@still merlin ```js
a = [1,2,3,4,5]
a[0] = 1
a.slice(1) = [2,3,4,5]
a.slice(1).join(" ") = "2 3 4 5"

digital ibex
#

i tried using a for loop before, but then i was confused on how i can like send it to the channel

#

so i just used map, and now i'm confused again, how i would send it to the channel

quartz kindle
#

use the for loop to build your kick string

#

then send it after the loop ends

#

ie: ```js
kick = ""
for(bla) {
kick += "some complicated string"
}
.send(kick)

#

or you can use the array version like you were doing

#
kick = []
for(bla) {
  kick.push("some complicated string")
}
.send(kick.join("\n-\n"))
digital ibex
#

oh

earnest phoenix
#
  for extension in initial_extensions:
    try:
      bot.load_extension(extension)
    except Exception as e:
      print(f'Failed to load extension {extension}', file=sys.stderr)
      traceback.print_exc()```
```Traceback (most recent call last):
  File "main.py", line 23, in <module>
    traceback.print_exc()
NameError: name 'traceback' is not defined```
can someone help?
slender thistle
#

import traceback

earnest phoenix
#

@slender thistle 1 more thing i get this error everytime when using cogs can u tell me the reason
discord.ext.commands.errors.CommandNotFound: Command "purge" is not found

#

i do have the command

#

it worked well in main file

slender thistle
#

You're not handling that exception

#

Ah

#

Show your code

earnest phoenix
#

main or cog?

digital ibex
#

quick question, do i have to do that for each moderation action, like, kick, ban mute etc? or can i can i do something like ```js
let moderations = [];
for (moderation of moderations) {
const kick = guild.moderations.filter((e) => e.user === member.id).map((e) => e.kick);
const ban = guild.moderations.filter((e) => e.user === member.id).map((e) => e.ban);
/* and so on */

moderations.push(__**Kick:**__\n**Mod:** ${kick.mod}); /* and other data for kick /
moderations.push(__**Ban:**__\n**Mod:** ${ban.mod}); /
and other data for ban */
}
message.channel.createMessage(moderations)

#

so can i do something like ^^ @quartz kindle ?

#

instead of creating a loop for each moderation action

slender thistle
#

Both

quartz kindle
#

you will need a for loop inside a for loop

digital ibex
#

oh

quartz kindle
#

because the filtered kick and ban can still contain multiple references

pure lion
#

im lost

quartz kindle
#

or you can merge them

#

for example

earnest phoenix
#
from discord.ext import commands

class Moderation(commands.Cog):
  def __init__(self.bot):
    self.bot = bot

  @commands.Cog.listener()
  async def on_ready(self):
    print(f'{self.__class_.__name__}Cog has been loaded\n-----')

  @commands.command()
  @commands.guild_only()
  @commands.has_guild_permissions(manage_messages=True)
  async def purge(self, ctx, amount=1):
    await ctx.channel.purge(limit=amount+1)
    embed = discord.Embed(title=f'{ctx.author.name} purged {ctx.channel.name}', description=f'{amount}messages')
    await ctx.send(embed=embed)

  @commands.command()
  @commands.guild_only()
  @commands.has_guild_permissions(kick_members=True)
  async def kick(self, ctx, member: discord.Member, *, reason=None):
    await ctx.guild.kick(user=member, reason=reason)
    embed = discord.Embed(title=f'{ctx.author.name} kicked {member.name}', description=reason)
    await ctx.send(embed=embed)

  @commands.command()
  @commands.guild_only()
  @commands.has_guild_permissions(ban_members=True)
  async def ban(self, ctx, member: discord.Member, *, reason=None):
    await ctx.guild.ban(user=member, reason=reason)
    embed = discord.Embed(title=f'{ctx.author.name} banned {member.name}', description=reason)
    await ctx.send(embed=embed)

  @commands.command()
  @commands.guild_only()
  @commands.has_guild_permissions(unban_members=True)
  async def unban(self, ctx, member, *, reason=None):
    await ctx.guild.ban(user=member, reason=reason)
    embed = discord.Embed(title=f'{ctx.author.name} unbanned {member.name}', description=reason)
    await ctx.send(embed=embed)

def setup(bot):
  bot.add_cog(Moderation(bot))
  print('Moderation is loaded.')```
#
import discord
from discord.ext import commands
import os
import sys
import traceback
from webserver import keep_alive

client = commands.Bot(command_prefix = ".")

@client.event
async def on_ready():
  print("Bot is online!")
  return await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='for commands. Prefix: .'))

initial_extensions = ['cogs.Moderation']

if __name__ == '__main__':
  for extension in initial_extensions:
    try:
      bot.load_extension(extension)
    except Exception as e:
      print(f'Failed to load extension {extension}', file=sys.stderr)
      traceback.print_exc()

#.ping
@client.command()
async def ping(ctx):
  await ctx.send(f'Ping: {round(client.latency * 1000)}ms')

keep_alive()
Token = os.environ.get('Token')
client.run(Token)```
digital ibex
#

i'd prefer not to use the second one tbh, but if its easier i'm gonna use it lol

quartz kindle
#

combined = [...guild.moderations.filter(filter for kick), ...guild.moderations.filter(filter for ban)]

#

and then loop over combined

earnest phoenix
#

@slender thistle ^

digital ibex
#

kk, i'll try and see what happens :)

#

thanks again

slender thistle
#

are you sure that cog is actually loaded?

earnest phoenix
#

cog is not loaded idk why

pure lion
#

idk how to dir, send help

quartz kindle
#

did you console.log?

earnest phoenix
#

@slender thistle can u guide me with the problem

pure lion
#

lemme check if it works (again)

earnest phoenix
#

its not loading

#

im using cogs for first time

slender thistle
#

Can you remove the except branch from your cog-loading part?

quartz kindle
#

what does the console.log show?

earnest phoenix
#

what does the console.log show?
@quartz kindle me?

quartz kindle
#

no, elisdia

earnest phoenix
#

@slender thistle 1 sec

#
msg.guild.channels.cache.forEach(async (channel, id) => {

TypeError: Cannot read property 'catch' of undefined

#

@slender thistle should i run and try after removing that?

quartz kindle
#

@earnest phoenix the error says catch not cache

pure lion
#

tim console.log works now

quartz kindle
#

and what does it show?

earnest phoenix
#
 try{

        msg.guild.channels.cache.forEach(async (channel, id) => {
            
        await channel.overwritePermissions([
            {
                id: muterole.id,
                deny: ['SEND_MESSAGES', 'ADD_REACTIONS', 'SPEAK']
            }
        ])
        })

    } catch (e){
        return console.log(e)
// rest of code
pure lion
#

the same as before but not nestled, all the same level

quartz kindle
#

@earnest phoenix show the full error

earnest phoenix
#

nvm I am flipping stupid

#

I fixed it

#

thank though ๐Ÿ˜„

quartz kindle
#

@pure lion show it

nocturne grove
#

Is there some way to catch a rate limit? Or should I use client.on('rateLimit' for that, as ... .catch() doesn't catch a ratelimit?

pure lion
#

config: {
adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, /',
'User-Agent': 'axios/0.18.1'
},
method: 'get',
url: '(there was a url here)',
data: undefined
}

quartz kindle
#

rate limits are queued, so they wont fire errors, they will just sit in the queue and wait

#

you'll need the rateLimit event

pure lion
#

i just want the url

nocturne grove
#

so my bot will wait 10 minutes to update a channel name, as long as it is online?

earnest phoenix
#

How's it possible to make an embed let you download the image extension of an attached image on the embed instead of this?
(It's a generated image by an api)

quartz kindle
#

not the url

#

so you're doing something wrong

pure lion
#

how do i access the stuff tho

#

also, no clue what im doing wrong, all i want is the URL and nothing else

quartz kindle
#

that url is not the url you want

#

thats the url that was used to search

#

you want the search results, not the search itself

slender thistle
#

@earnest phoenix yeah

quartz kindle
#

the results should contain a big list of videos, their ids, authors, channels urls, etc...

slender thistle
#

restart the bot, I mean

earnest phoenix
#

ok

pure lion
#

how do

#

i looked through the docs, i guess i stupid

earnest phoenix
#

@slender thistle

async def ping(ctx):
  await ctx.send(f'Ping: {round(client.latency * 1000)}ms')```
``` File "main.py", line 23
    @client.command()
    ^
IndentationError: unexpected unindent```
what is even wrong here?
nocturne grove
#

oh but @quartz kindle, I actually want to know if it can rename a channel, if it's gonna queue them it will heap up multiple setName things, which is not what you want of course. You can just rename everything in one time instead if you know when it will ratelimit. I mean:

channel with name channel
t = 0: renamed 2 times
t = 60: renamed to channel60
t = 120: renamed to channel120
t = 180: renamed to channel180
after 10 minutes:
t = 600: renaming to channel60
renaming to channel120
t = 1200: renaming to channel180
I hope you get what I mean

quartz kindle
#

you need to track limits yourself

#

if you wait for the rateLimit event, there will be an item queued there already

clever tree
nocturne grove
#

okay thank you. Will make a whole thing for that

#

now I have to find out what that "thing" should be

high geode
#

TypeError: member.send is not a function

#

help pls

nocturne grove
#

what is member?

balmy knoll
#

In discord.js, how can I take the last message sent by the bot in a specific channel?

nocturne grove
#

I think you should fetch messages and check for the first one you will come across that's sent by the bot

earnest phoenix
#

Any ideas about my issue?

#

(Scroll up if you didn't see it)

nocturne grove
#

can't you send it using some markdown or hastebin?

earnest phoenix
#

Huh?

nocturne grove
#

you sent a file

quartz kindle
#

if the api returns only image data without a file name, you need to define your own file name

earnest phoenix
#

(was talking to memmo)

quartz kindle
#

files: [imagedata] -> files:[{attachment:imagedata,name:"myfile.png"}]

nocturne grove
#

oh I'm sorry I thought your file was a piece of code ๐Ÿคฆ

earnest phoenix
#

Lol... But can i define it's name in the .setImage() as I'm using? @quartz kindle

quartz kindle
#

you define it in the attachment

#

then on the setImage you use the new name

#

attachment://myname.png

earnest phoenix
#

Oh ok

pure lion
#

<dying noises>

earnest phoenix
#

(thanks btw @quartz kindle)

nocturne grove
#

What is better/faster? A collection or an object? Or are there no performance differences?

quartz kindle
#

objects will probably be slightly faster because its a less complex structure

nocturne grove
#

okay thank you

quartz kindle
#

but the difference should be irrelevant

nocturne grove
#

I prefer objects in this case so will go for that one

gentle minnow
#

Hey

earnest phoenix
#
msg.guild.channels.cache.forEach(async (channel, id) => {
        
await channel.overwritePermissions([
{
id: muterole.id,
deny: ['SEND_MESSAGES', 'ADD_REACTIONS', 'SPEAK']
}
])
});

I'm trying to catch an error if something goes wrong while running this piece of code, but nothing seems to work - I tried try catch and also making a variable function but nothing worked

quartz kindle
#

because async forEach is a bad idea

earnest phoenix
#

it is?

quartz kindle
#

yes

earnest phoenix
#

oke that might be the issue then

quartz kindle
#

async forEach spawns several copies of async functions, which are not controllable

earnest phoenix
#

ofc yes thank you

quartz kindle
#

you need a for loop

earnest phoenix
#

or remove async

#

i dont need it

quartz kindle
#

you do

#

you're using an async function

earnest phoenix
#

yes but I can make it a non aysnc one

#

without "await"

quartz kindle
#

channel.overwritePermissions is an async function, it returns a promise
if you use a forEach, you will be executing them all at the same time concurrently

#

with no respect for rate limits

earnest phoenix
#

what would a for loop in this case look like

slender thistle
#

@earnest phoenix Is the error fixed yet?

quartz kindle
#
for(let [id,channel] of msg.guild.channels.cache) {
  await channel.overwritePermissions(...)
}
#

as long as the parent scope is an async function, the for loop will respect the await keyword and make sure all requests are done sequentially and not concurrently

earnest phoenix
#

and how should i handle the rror

quartz kindle
#

you can handle it with a try catch or with a .catch(), doesnt really matter in this case

earnest phoenix
#

thanks man

#

imma try that

#

hopefully that works and fixes the problem ๐Ÿ™

#

@quartz kindle thx, i will use it too..

#

@slender thistle nope i think the cog didnt load properly and dont think its bcos of the except

slender thistle
#

Show the code around the error

earnest phoenix
#

it worked @quartz kindle thanks

#

99% sure

#

after i remove except it shows @slender thistle

async def ping(ctx):
  await ctx.send(f'Ping: {round(client.latency * 1000)}ms')```
``` File "main.py", line 23
    @client.command()
    ^
IndentationError: unexpected unindent```
and if i add it back it tell the bot is online but the command in cog does not work
river wing
#

Does anyone know why it gives me an error of "Cannot read property 'members' of undefined"?

nocturne grove
#

@river wing replace .find by .get

wet iron
#
    if(!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);

    let kUser = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]));
    if(!kUser) return msg.channel.send("Can't find user! :angry:");
    if(kUser.hasPermission("KICK_MEMBERS")) return msg.channel.send(staffEmbed) 
    let kReason = args.join(" ").slice(22);

    const kickEmbed = new Discord.MessageEmbed()
    .setColor("#FF0000")
    .setDescription("~Kick~")
    .addField("Kicked User:", `${kUser} with ID ${kUser.id}`)
    .addField("Kicked By:", `<@${msg.author.id}> with ID ${msg.author.id}`)
    .addField("Reason:", `${kReason}`)

    if (!logChannel) return msg.channel.send('There is no `#mari0-log` channel! :slight_frown:')

    kUser.kick(kReason);
    logChannel.send(kickEmbed);

    return;``` This is my code for the kick command but it will just log it wont kick, can someone help me?
nocturne grove
#

you'll use find if you want to find a channel by name, description, type etc.

river wing
#

@river wing replace .find by .get
but i still get the same error message

slender thistle
#

@earnest phoenix Show your main file

nocturne grove
#

you could also do this, but Idk why you want that:

bot.guilds.cache.find(g => g.id == 'yourID');```
#

then there's no guild with that id

earnest phoenix
#

@slender thistle

import discord
from discord.ext import commands
import os
import sys
import traceback
from webserver import keep_alive

client = commands.Bot(command_prefix = ".")

@client.event
async def on_ready():
  print("Bot is online!")
  return await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='for commands. Prefix: .'))  

initial_extensions = ['cogs.Moderation']

if __name__ == '__main__':
  for extension in initial_extensions:
    try:
      bot.load_extension(extension)
    except:
      pass

@client.command()
async def ping(ctx):
  await ctx.send(f'Ping: {round(client.latency * 1000)}ms')

keep_alive()
Token = os.environ.get('Token')
client.run(Token)```
river wing
#

isnt the guild id the server id that i copy?

nocturne grove
#

yes that's right

earnest phoenix
#

@river wing yes

nocturne grove
#

is your bot in there, @river wing?

wet iron
#
    if(!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);

    let kUser = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]));
    if(!kUser) return msg.channel.send("Can't find user! :angry:");
    if(kUser.hasPermission("KICK_MEMBERS")) return msg.channel.send(staffEmbed) 
    let kReason = args.join(" ").slice(22);

    const kickEmbed = new Discord.MessageEmbed()
    .setColor("#FF0000")
    .setDescription("~Kick~")
    .addField("Kicked User:", `${kUser} with ID ${kUser.id}`)
    .addField("Kicked By:", `<@${msg.author.id}> with ID ${msg.author.id}`)
    .addField("Reason:", `${kReason}`)

    if (!logChannel) return msg.channel.send('There is no `#mari0-log` channel! :slight_frown:')

    kUser.kick(kReason);
    logChannel.send(kickEmbed);

    return;``` This is my code for the kick command but it will just log it wont kick, can someone help me?

Anyone help?

river wing
#

yes my bot is in there

nocturne grove
#

that's weird

slender thistle
#

A little hint for you: editing a mention in doesn't actually mention me so please mention me from the very start

#

Maybe remove the try-except completely and just load the extension

river wing
#

that's weird
@nocturne grove now it worked. but why does it always have a tendency to fail?

earnest phoenix
#

@slender thistle

async def ping(ctx):
  await ctx.send(f'Ping: {round(client.latency * 1000)}ms')

 File "main.py", line 23
    @client.command()
    ^
IndentationError: unexpected unindent```
wild mist
#

someone know why hosting lavalink on heroku always off in 1 or 2 hours ?

earnest phoenix
#

this prob again

modest maple
#

why would you use lavalink on heroku lmao

slender thistle
#

What does your for extension in initial_extensions: loop like rn

modest maple
#

that will never work lol

wild mist
#

It work for me

#

the prob just off in 1 hour

#

then i need to deploy again

modest maple
#

until yt bans your IP lol

wild mist
#

xd

nocturne grove
#

@river wing it doesn't have a tendency to fail for something like that. Idk what you did wrong

wet iron
#
    if(!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);

    let kUser = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]));
    if(!kUser) return msg.channel.send("Can't find user! :angry:");
    if(kUser.hasPermission("KICK_MEMBERS")) return msg.channel.send(staffEmbed) 
    let kReason = args.join(" ").slice(22);

    const kickEmbed = new Discord.MessageEmbed()
    .setColor("#FF0000")
    .setDescription("~Kick~")
    .addField("Kicked User:", `${kUser} with ID ${kUser.id}`)
    .addField("Kicked By:", `<@${msg.author.id}> with ID ${msg.author.id}`)
    .addField("Reason:", `${kReason}`)

    if (!logChannel) return msg.channel.send('There is no `#mari0-log` channel! :slight_frown:')

    kUser.kick(kReason);
    logChannel.send(kickEmbed);

    return;``` This is my code for the kick command but it will just log it wont kick, can someone help me?

@slender thistle can you help?

slender thistle
#

Assuming I know JavaScript :p

wet iron
#

well frick

nocturne grove
#

@wet iron where does it say Won't kick? Do you mean Can't find user! :angry:?

wet iron
#

no

#

it logs

nocturne grove
#

or an error?

wet iron
#

that user

#

no error

#

just wont kick

clever tree
#

@slender thistle Could you help me please ? Maybe u figure out my problem. My bot played music sice yesterday. Since yesterday the bot joins the channel, light up green but does not have any sound. I could get the nowplaying song and everything else. But the dispatcher didnt even end after the song must be finished. I updated everything. loaded new ffmpeg. nothing helped. Now i tried console.log(serverdispatcher.player) and it gave me at one line : speaking: false; is that the problem. If so, how could i fix this ?

jagged haven
#

let kReason = args.join(" ").slice(22); valid in code v12 ?

wet iron
#

no errors

#

i get no errors

nocturne grove
#

your bot can't say wont kick if you never wrote that somewhere in your code

#

sorry I don't understand what you mean

river wing
#

@river wing it doesn't have a tendency to fail for something like that. Idk what you did wrong
@nocturne grove sometimes when i restart my bot, it just gives me that error that members of undefined.

slender thistle
#

Just post as many details as possible and someone who can will help you eventuallyโ„ข๏ธ

wet iron
#

it just logs what it did

#

but the user i tried to kick

#

is still there

nocturne grove
#

@river wing oh wtf that's strange

digital ibex
#

yes @jagged haven. thats got nothing to do with the library

nocturne grove
#

okay so it doesn't kick but you also didn't receive an error

#

strange

wet iron
#

ok

#

now it has an error

digital ibex
#

maybe its ur member resolver, log kuser and shwo what it shows @wet iron

#

o ok

wet iron
#

UnhandledPromiseRejectionWarning: DiscordApiError: Missing permissions

jagged haven
#

@digital ibex me too error giving

digital ibex
#

then its cuz ur bot doesn't have permissions

river wing
#

UnhandledPromiseRejectionWarning: DiscordApiError: Missing permissions
@wet iron who are u kicking

wet iron
#

a friend that doesnt have a rank

digital ibex
#

i think d.js has Member.kickable

#

you can use that

nocturne grove
#

you have to compare more than what you did. Position of highest role, bot perms, kuser perms

#

oh yes what @digital ibex said

jagged haven
#
 let kReason = args.join(" ").slice(22);
                       ^
TypeError: Cannot read property 'join' of undefined
at Client.<anonymous> (/app/server.js:46:24)
    at Client.emit (events.js:196:13)
    at MessageCreateAction.handle (/rbd/pnpm-volume/575fb840-0633-4beb-b954-fc4c053394a8/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/575fb840-0633-4beb-b954-fc4c053394a8/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
wet iron
#

oh i fixed it

digital ibex
#

args is undefined @jagged haven

nocturne grove
#

maybe define it

high geode
#

TypeError: member.send is not a function

#

pls help

digital ibex
#

what is member

nocturne grove
#

@high geode log member

#

I asked before but okay

jagged haven
#

@digital ibex how can i define ?

digital ibex
#

it doesn't always mean you need to define it if you get that error, in scroppers case, it means that the mod hasn't provided a reason.

#

you don't need to

#

you've already defined it

#

you need to check if reason doesn't exist, and if it doesn't, then do something

quartz kindle
#

did he tho?

digital ibex
#

yeah. cuz then it would say 'reason is not defined' wouldn't it?

quartz kindle
#

a properly configured args will be an empty array if no arguments are provided

#

empty arrays can still be joined

clever tree
#

Where could i post my problem too, to get more help ?

earnest phoenix
#

How's possible to set an image that has defined as a new Discord.MessageAttachment() on .setImage() on an embed?
(Not just it's url but it's name also)

#

For example
let file = new Discord.MessageAttachment("Some url", "Example.png") is possible to set that into .setImage() on an embed?

nocturne grove
#

I don't think so, as a MessageAttachment could also be other files than images

earnest phoenix
#

So what can i do to name an attachment that can be set to .setImage() ?

#

(an image attachment)

pale vessel
#

try attachFile() or something

wet iron
#
    if (!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);
    if (!args[0]) return msg.channel.send("oof.")
    if (args[0] > 50) return msg.channel.send("My limit for deleting messages is `50`.")
    const clearEmbed = new Discord.MessageEmbed()
    .setColor("#53d636")
    .setTitle(`${msg.author.username} Deleted ${args[0]} message(s)!`)
    .setThumbnail(msg.author.displayAvatarURL())
    msg.channel.bulkDelete(args[0]).then(() => {
        msg.channel.send(clearEmbed);
    })``` i need help, i use this code for clear command and it clears more than i want it to clear...
earnest phoenix
#

I want the image inside the embed not outside of it lol @pale vessel

nocturne grove
#

For example
let file = new Discord.MessageAttachment("Some url", "Example.png") is possible to set that into .setImage() on an embed?
@earnest phoenix if you got that you can just do .setImage(file.url)

earnest phoenix
#

@nocturne grove hmm lemme see

pale vessel
#

no, you use attachFile so that you can use attachment://

nocturne grove
#

to my understanding he has a MessageAttachment and wants to set that as an image to an embed (assuming the attachment is an image)

pale vessel
#

then attach the image

#

and use attachment://name.ext

earnest phoenix
#

(Literally getting the image from the api but i want to name that and set it as the .setImage() of the embed)

pale vessel
#

because you want to hide the key?

wet iron
#
    if (!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);
    if (!args[0]) return msg.channel.send("oof.")
    if (args[0] > 50) return msg.channel.send("My limit for deleting messages is `50`.")
    const clearEmbed = new Discord.MessageEmbed()
    .setColor("#53d636")
    .setTitle(`${msg.author.username} Deleted ${args[0]} message(s)!`)
    .setThumbnail(msg.author.displayAvatarURL())
    msg.channel.bulkDelete(args[0]).then(() => {
        msg.channel.send(clearEmbed);
    })``` i need help, i use this code for clear command and it clears more than i want it to clear...

anyone?

earnest phoenix
pale vessel
#

you should add an extension

nocturne grove
#

afaik images in embeds don't have a name

#

I tried

pale vessel
#

they do

earnest phoenix
#

Yea they do

#

@pale vessel i tried to add an extension... Nothing

pale vessel
#

i can definitely help you with this but i'm eating a pizza rn

#

give me a minute

#

all right boi

#

@earnest phoenix DMs or here

earnest phoenix
#

Which one you want?

pale vessel
#

dms

#

ig

earnest phoenix
#

K

#

How to drop ping?

coral stirrup
#

lol

pale vessel
#

use round/floor

lofty grove
#

hi.

#

I have this problem, how can I solve it?

tight plinth
#

You don't solve it

lofty grove
#

is there a problem on youtube?

radiant estuary
#

Hey guys.
I have a big question:

How do I get the datas (Name, ID etc) the user, who used the OAuth2

tight plinth
#

Yes, but this shouldn't affect the play song function

radiant estuary
#

I already have a server

tight plinth
#

See what the oauth2 retusn you and use it

worthy kindle
#

My friend has a bot coded with Javascript I am my friend were thinking about how to make it so it says its streaming?

tight plinth
#

Yes you can do that

#

Just read the docs to find the right function and use it

radiant estuary
#

See what the oauth2 retusn you and use it
How can I do this with JavaScript?

worthy kindle
#

But we were wondering what the code is for it.

tight plinth
#

@radiant estuary if you request oauth for user details, it should returns you user details

#

@worthy kindle were not gonna give you code. Find it yourself

earnest phoenix
#

@wet iron hey bro

#

i want some help

radiant estuary
#

@tight plinth sry for the ping. And how can I connect my code with the oauth2?

tight plinth
#

Read discord docs

earnest phoenix
tight plinth
#

And Google can help you

radiant estuary
#

Okay. What should I search? I am new, so i don't know what would be the best

tight plinth
#

Just search what you need

slender wagon
#

member.roles.array().slice(1).sort
how do i make this to work in v12

radiant estuary
#

Okay, thank you

tight plinth
#

@slender wagon member.roles.cache...

slender wagon
#

oh yeah that cache thing smh

#

ty

#

it is the role manager i'm not used to it yet

tight plinth
#

It's not only the role managet

#

It's also like every manager (members, users, channels and I probably forget others)

slender wagon
#

they have the cache right?

tight plinth
#

Yed

slender wagon
#

it confuses me ngl

wet iron
#

who pinged me?

#

@wet iron hey bro
@earnest phoenix yes?

tight plinth
#

Someone

wet iron
#
    if (!msg.member.roles.cache.find(r => r.name === "Staff")) return msg.channel.send(PermEmbed);
    if (!args[0]) return msg.channel.send("oof.")
    if (args[0] > 50) return msg.channel.send("My limit for deleting messages is `50`.")
    const clearEmbed = new Discord.MessageEmbed()
    .setColor("#53d636")
    .setTitle(`${msg.author.username} Deleted ${args[0]} message(s)!`)
    .setThumbnail(msg.author.displayAvatarURL())
    msg.channel.bulkDelete(args[0]).then(() => {
        msg.channel.send(clearEmbed);
    })
``` can someone help me? This is my clear command but it clears more than i type it to clear
lofty grove
#

@lofty grove change the api key , make a new one from a new id
@earnest phoenix it didn't work, are you available?

earnest phoenix
#

@lofty grove the same thing happened with my music bot

#

might be u have exceded the daily quota limit

#

so

#

the quota refreshes every midnight

#

so wait till midnight

#

if it doesnt helps

lofty grove
#

do you have the same error in your bot?

earnest phoenix
#

create a new api key or ask one of ur friend to create an API

#

@lofty grove yea i had the same error

#

but its sorted out now

#

create a new api key or ask one of ur friend to create an API
this will surely help u out

lusty quest
#

anyone here who understands regex? want to find %0 if it is used as an argument (causes an API to return an stupid amount of stuff if spammed with certain variants)

tight plinth
#

STRING.includes('%0')

neat ingot
#

/([\%0])/g

lusty quest
#

@tight plinth returns false if someone uses %0A (created massive issues wich caused pm2 to panic)

tight plinth
#

No

neat ingot
lusty quest
#

i already tested it and it returned false while the argument was %0A

#

(not with regex)

tight plinth
lusty quest
#

hmm

#

strange

#

now it works

#

but thanks

lofty grove
#

@earnest phoenix I did thank you I made a few adjustments.

#

It works smoothly now
Thank you buddy.

amber fractal
earnest phoenix
#

@lofty grove no problem buddy

hardy vector
#
client.on('message', async message => {
    const args = message.content.slice(prefix.length).split(' ');
    if (message.content.startsWith("!fortnite")) {
        let username = args[1]
        let platform = args[2]
    let data = fortnite.user(username, platform)
        let embed = new Discord.MessageEmbed()
        .setTitle(`${username}'s Lifetime Stats`)
        .setColor("RANDOM")
        .addField("Matches Played",data.stats.lifetime.matches)
        message.channel.send(embed)
    }
})```(node:2289) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'lifetime' of undefined,  this the data logged frm the player https://hastebin.com/lepudisepi.cs
twin marsh
#

My mind isn't functioning atm but how do I clear up a whole json file and make it only say {} again?

hardy vector
#
for (var key in jsonfile) {
    delete jsonfile[key];
}```
#

i think

nocturne grove
#

just jsonfile = {} and then save it?

hardy vector
#

or that

marble juniper
#

just

#

delete the file

#

and make the file again

#

but with {} inside

slender thistle
#

Wiping file content sounds better than re-creating a file ngl

earnest phoenix
#

What is the diffrence between findone and find in mongoose?

slender thistle
#

find finds multiple documents whereas findOne returns only one document

whole knot
#

Is someone here familiar with a command to turn moduls on or off?
I have implimented a leveling system into my bot and I would like to give the opportunity to turn it off or on with a command. Something like this has never been done before by myself, that's why I ask

brave rover
#

what lib are you using?

whole knot
#

Using Python and Pillow

brave rover
#

you can use bot.unload_extension() to unload a specific cog

whole knot
#

Oh yes, implimented that but I wanted to make it user friendly. People sometimes do not want to have the level system in their server

#

Unloading the whole thing would mean it does not work on all the servers

nocturne grove
#

@hardy vector My eslint says that object is not right. I guess you can't use like Solo: Mode, instead of that use Solo Mode:.
But that doesn't seem to fix the entire problem

brave rover
#

I suppose you could store guild IDs that don't want levelling enabled, and then when you're running your checks, you could check the message's guild against that list

whole knot
#

Sounds good, will have a look into that

#

Thanks! :)

brave rover
#

nw

hardy vector
#

oh

#

so what do i do then lol

earnest phoenix
#
const member = msg.mentions.users.first() || bot.users.fetch(args[0]);
return msg.guild.ban(member)

msg.guild.ban is not a function

quartz kindle
#

in v12 its guild.members.ban(id) or member.ban()

earnest phoenix
#

oke

#

how can I get the user ID when using bot.users.fetch(args[0])

pale vessel
#

use then/await

earnest phoenix
#
let user = msg.mentions.users.first();
if (!user && !isNaN(args[0])) user = bot.users.fetch(args[0]);

How can I prevent that this happens: UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown User?

digital ibex
#

i just installed vue

tulip ledge
#

Is there a way to compare a strring with a file and select the one thats the closest? For example:
If I type papr it'll look into a file and find Paper being the closest?

mossy vine
#

@digital ibex restart ur computor

digital ibex
#

oh

#

thats annoying

#

thank u

earnest phoenix
#
client.guilds.cache.forEach(g => {
        g.fetchInvites()
            .then(invites => guildInvites.set(g.id, invites))
            .catch(err => console.log(err));
    });

    const cachedInvites = guildInvites.get(member.guild.id)
    const newInvites = await member.guild.fetchInvites();
    const usedInvite = newInvites.find(inv => cachedInvites.get(inv.uses < inv.uses));

This works if a user only has a code joint for example "WYD" but not if he has a discord/WYDC joint.
What do I have to change to make it work with both things.
Because otherwise usedInvite is undefined

clever tree
earnest phoenix
#

Yes?

clever tree
#

I mean speaking: false

tulip ledge
#

Anyone knows how to implement levenshtein distance to find the closest match and not what the difference is?

mossy vine
#

actually yeah, i do

tulip ledge
#

How?

mossy vine
#

what lang

tulip ledge
#

Javascript

quartz kindle
#

there's an npm module for it

tulip ledge
#

I was thinking of running a for each on the file checking wich one was the closest but then u have the problem if tehere's 2 items with a difference of 1

mossy vine
#

here is my levenshtein distance implementation

exports.levenshteinRatio = (target, source) => {
    if (source == null || target == null) return 0.0
    if (source.length == 0 || target.length == 0) return 0.0
    if (source === target) return 1.0

    let sourceWordCount = source.length
    let targetWordCount = target.length

    let distance = new Array(sourceWordCount + 1)
    for (let i = 0; i < distance.length; i++) {
        distance[i] = new Array(targetWordCount + 1)
    }

    for (let i = 0; i <= sourceWordCount; distance[i][0] = i++);
    for (let j = 0; j <= targetWordCount; distance[0][j] = j++);

    for (let i = 1; i <= sourceWordCount; i++) {
        for (let j = 1; j <= targetWordCount; j++) {
            let cost = ((target.charAt(j - 1) === source.charAt(i - 1)) ? 0 : 1)

            distance[i][j] = Math.min(Math.min(distance[i - 1][j] + 1, distance[i][j - 1] + 1), distance[i - 1][j - 1] + cost)
        }
    }

    return 1.0 - distance[sourceWordCount][targetWordCount] / Math.max(source.length, target.length)
}```
tulip ledge
#

For real?

#

Can I use it?

mossy vine
#
function mostSimilarModule(searchItem) {
    let keys = Array.from(ktaneModules.keys())
    let module = keys.sort((entry1, entry2) =>
        levenshteinRatio(entry2.toLowerCase(), searchItem) - levenshteinRatio(entry1.toLowerCase(), searchItem)
    )[0]
    if (levenshteinRatio(module.toLowerCase(), searchItem) < 0.7) return null
    return module
}```
#

ktaneModules being the map of ur stuff

quartz kindle
#

you made your own implementation? awesome

mossy vine
#

<0.7 being my own filter

tulip ledge
#

wait u need a map?

#

I was thinking of using a json file

quartz kindle
#

i just copied the npm module's source code over to my projects so i dont need to add it as a dependency lmao

mossy vine
#

no, you can modify the code

tulip ledge
#

So I'll havbe to map it first

mossy vine
#

i think it actually transforms the map into an object

#

or array

#

idfk

#

just read the code and figure it out lmao

tulip ledge
#

So I suppose the mostSimilar is used in the file where u wanna use it and the levenshtein is a diff file?

#

Right

mossy vine
#

levenshtein is a diff file for clarity yea

#

but you can do whatever

#

i just realized the second function is changing the value of module

#

ew

#

im sorry

quartz kindle
#

lmao

tulip ledge
#

Wait

#

So what do I do with the second function?

mossy vine
#

you modify it to fit your needs

tulip ledge
#

But I put it in the file I need right

digital ibex
mossy vine
#

or export it from another file, whatever floats your boat

digital ibex
#

i already installed vue btw

mossy vine
#

is it added to path

digital ibex
#

yes

tulip ledge
#

I've never done something like this before lol

mossy vine
#

dont just copy my code

#

well you can copy the first function

#

but not the second one

digital ibex
#

wait

#

how do i add it to the path?

tulip ledge
mossy vine
#

modify the second one to do whatever you want it to

tulip ledge
#

I'm gonna change it

digital ibex
#

i just done vue init and i get that

tulip ledge
#

To be able to work with a json

mossy vine
#

yeah its perfectly fine as long as you are importing it from there

tulip ledge
#

So I should import it using a require

#

Or am I being brainded

mossy vine
#

yes

tulip ledge
#

yes of me being braindead or?

digital ibex
#

@mossy vine u kno how i can initialise the project?

mossy vine
#

import using require

#

@digital ibex nope, sry

digital ibex
#

o ok

#

thanks anyways :)

tulip ledge
#

I'll just add it to my client object then so I can use it in my commads and stuff

grizzled raven
#

however you want

tulip ledge
#

Ok I'm a bit lost

#

Idk how to make it work with the array

#

Cuz I need to get the keys and u can't map a json

#

Nvm I think I might have a solution

next remnant
#

i'm trying out d.js and commando

#

i follow the first example from the first steps page of commando

#

using the import * as Commando from 'discord.js-commando' syntax results in this when i try to create an instance of Client

#

i'm using typescript here

#

help?

quartz kindle
#

you need to install commando from their github

#

the version on npm is outdated afaik

next remnant
#

how do i do that?

quartz kindle
#

npm install discordjs/commando

tulip ledge
mossy raft
#

hi

next remnant
#

are docs outdated too?

#

the npm version sure is

quartz kindle
#

not sure

#

is it working now?

tulip ledge
#

Tim u know my problem?

next remnant
#

yeah

#

seems to be

quartz kindle
#

@tulip ledge entry2 is not a string

digital ibex
#

i just installed vue

warm marsh
#

npx vue

quartz kindle
#

did you restart your pc?

tulip ledge
#

Wait what

digital ibex
#

yeah

warm marsh
#

Probably due to not being installed globally

quartz kindle
#

did you install vue globally?

warm marsh
#

Using -g flag.

digital ibex
#

uhh, i didn't

next remnant
#

pretty sure its vue-cli or something

tulip ledge
#

@mossy vine (sorry for tag)

digital ibex
#

yeah. i just done npm install vue-cli

tulip ledge
#

Help pls

quartz kindle
#

you need -g

digital ibex
#

oh, ok

tulip ledge
#

I verry confused

warm marsh
#

Do npx vue-cli.

next remnant
#

nvm, thats for npx

tulip ledge
#

Why is entry2 not a string tho

warm marsh
#

Using module doesn't throw an error?

tulip ledge
#

Entry2 equals 1

warm marsh
#

toString it?

tulip ledge
#

I'll try

#

Oh I'm so-

#

Wtf

#

TypeError: client.levenshtein is not a function

#

Like wth

warm marsh
#

What's in that file?

warm marsh
#

module.exports = function

#

?

tulip ledge
#
// Levenshtein Distance function made by Cyber28#2864

exports.levenshteinRatio = (target, source) => {
    if (source == null || target == null) return 0.0
    if (source.length == 0 || target.length == 0) return 0.0
    if (source === target) return 1.0

    let sourceWordCount = source.length
    let targetWordCount = target.length

    let distance = new Array(sourceWordCount + 1)
    for (let i = 0; i < distance.length; i++) {
        distance[i] = new Array(targetWordCount + 1)
    }

    for (let i = 0; i <= sourceWordCount; distance[i][0] = i++);
    for (let j = 0; j <= targetWordCount; distance[0][j] = j++);

    for (let i = 1; i <= sourceWordCount; i++) {
        for (let j = 1; j <= targetWordCount; j++) {
            let cost = ((target.charAt(j - 1) === source.charAt(i - 1)) ? 0 : 1)

            distance[i][j] = Math.min(Math.min(distance[i - 1][j] + 1, distance[i][j - 1] + 1), distance[i - 1][j - 1] + cost)
        }
    }

    return 1.0 - distance[sourceWordCount][targetWordCount] / Math.max(source.length, target.length)
}
warm marsh
#

You need to use client.levenshtein.levenshteinRation

tulip ledge
#

Oh

#

Lol

#

I just realised

#

Xd

#

Ty

#

I feel like I'm doing it wrong

#

First of all module.toLowerCase() isnt a function (but I can fix that)
It returns 0 and not the closest match

next remnant
#

are there any examples on how to define commands other than digging through the example bot code?

warm marsh
#

if content == command {}

next remnant
#

nope

#

thats bad

warm marsh
#

No?

next remnant
#

pain to scale

warm marsh
#

Right. What language are you using?

next remnant
#

trying out discord.js

warm marsh
#

External files are easy to implement.

#

What kind of OS are you on?

next remnant
#

where can I find examples?

#

im on linux

warm marsh
#

Okay.

tulip ledge
#

Oh

#

Wait

#

I'm stupid

warm marsh
#

Files are typically laid out like

module.exports = {
  run: function() {}
}

// or
module.exports = class {
  method() {}
}```
#

called like require('file').method

#

or new method()

next remnant
#

uhh thats commonjs

#

im using ts with es modules

warm marsh
#

Ah

#

Okay then export run = function

next remnant
#

can i get a link to documentation for this?

warm marsh
#

There is no docs?

tulip ledge
#

Can somebody help me?

warm marsh
#

One sec

tulip ledge
#

Cuz I'm losing braincells

next remnant
warm marsh
#

Commando

next remnant
#

yes

#

im looking at commando docs

warm marsh
#

It's not dep?

next remnant
#

what

warm marsh
#

deprecated

next remnant
#

its on the docs site

#

nothing says it is

warm marsh
#

Idk, Does commando not have some function like commando.command('name')

#

or something

next remnant
#

neither on docs nor on repo

tulip ledge
#

can someone help me?

warm marsh
#

@tulip ledge what is the error?

#

Otherthan 1

tulip ledge
#

No error

#

It returns 0

#

And not the closest match

next remnant
#

that is api refernece

#

not documentation on how to use it for someone who has never used it before

warm marsh
#

Idk, I've never used commando as pretty sure it was deprecated.

next remnant
#

if it is deprecated then why do they not say it anywhere

warm marsh
#

"pretty sure"

#

Didn't mean it was.

next remnant
#

oh

#

missed that

digital ibex
#

anyone here familiar with vue?

tulip ledge
#

Do you have a sloution or not?

warm marsh
#

I'm reading your code.

#

Idk if that's of any use.

pale vessel
#

i like how you unironically called them weebsimp

warm marsh
#

That's his displayname.

pale vessel
#

yep

warm marsh
#

their*

pale vessel
#

ah yes, it's dangerous these days

warm marsh
#

๐Ÿ‘€ very

next remnant
pale vessel
#

commando ew

next remnant
#

which one should i follow?

digital ibex
#

commando bad

pale vessel
#

^

next remnant
#

what else to use?

warm marsh
#

discord.js

#

without the - commando

next remnant
#

what comamnds framework to use?

pale vessel
#

your own

#

xd

next remnant
#

i ain't writing my own

pale vessel
#

legit

digital ibex
#

why

#

its not that hard

pale vessel
#

it's not hard

warm marsh
#

For JS; Eris, DJS, DJSCommando

#

maybe some others.

pale vessel
#

eris has a command client too

warm marsh
#

@tulip ledge x => x = x?

pale vessel
#

but i never used it

next remnant
#

its a pain to deal with + more code to maintain

digital ibex
#

same

tulip ledge
#

Yeah I'm bad at mapping

pale vessel
#

it's actually less for me

tulip ledge
#

And u needed to pass a function

pale vessel
#

but idk

warm marsh
#

Check file is an array

tulip ledge
#

idk

warm marsh
#

and then it's just an array of strings?

tulip ledge
#

Wait

#

I'm getting confused

#

checkfile is a map

warm marsh
#

Maybe checkfile = itemstosearch.map(x => itemfile[x]);

tulip ledge
#

I'll try

warm marsh
#

So returns the object named 'diamond' etc.

#

If that's what the plan of it was.

next remnant
#

if commando is bad (other than making my own) what should i use?

tulip ledge
#

Still logs 0

digital ibex
#

ur own, its not hard at all

#

oh

next remnant
#

scalability

tulip ledge
#

Basically when I type dimond it should "correct" it to diamond

digital ibex
#

i don't think there r any

#

i'm not sure tho

warm marsh
#

Use regex?

tulip ledge
#

But how

#

Cuz I have multiple

#

Like a good 80 different

next remnant
#

im sorry i dont wanna write my own converter system, checks system, concurrency system and list goes on

tulip ledge
#

And it needs to correct it to the closest

warm marsh
#

Most common other than writing yourself is DJS.

next remnant
#

discord.js itself is an api wrapper, not a command framework

#

commando is command framwork

pale vessel
#

commando then

digital ibex
#

no its not an api wrapper

warm marsh
#

No, You just write that yourself.

pale vessel
#

it is

warm marsh
#

Takes like 20 lines max

digital ibex
#

barely

tulip ledge
#

You have a solution of mine?

digital ibex
#

why does vue take so long to install

warm marsh
#

Internet?

pale vessel
#

just use a simple command handler

warm marsh
#

Not yet.

#

Using something like a map and if statement is decent enough.

#

Using some other way of storing into map.

#

Idk why you need checkfile.keys()

tulip ledge
#

wdym if statement?

warm marsh
#

Not you.

#

For a command loader.

tulip ledge
#

oh ok

#

Well this code was given to me

#

I'm just tryna implement my code into it

warm marsh
#

Ah.

tulip ledge
#

@mossy vine made it

warm marsh
#

Did you change client.levenshtein to client.levenshtein.levenshteinRatio()

next remnant
#

does djs not have a default error handler? (once that just logs to console)

tulip ledge
#

yup

warm marsh
#

djs requires a little more setting up.

tulip ledge
warm marsh
#

What's skyblock/items.json diamonds equal to?

tulip ledge
warm marsh
#

Mhh

clever tree
#

I had the issue where my bot joins, finds the video and mp3, lights green but has no sound after 2 weeks working well. I made a new folder. Build everything again from 0 but the error is still the same. I reinstalled everything, again the same issue xd. Could someone help me pleease. I cant imagine the problem tears

warm marsh
#

Any errors?

tulip ledge
#

for me?

clever tree
#

no. Console is clean

warm marsh
#

No.

#

Do you have ffmpeg installed?

#

Dependent on language ofc.

clever tree
#

yes. I had ffmpeg installed manually. And then i installed ffmpeg-static. I use js

warm marsh
#

node-opus?

#

Do you have any code to show?

clever tree
#

i used node-opus before. And then i updated to @discordjs/opus after that issue

#

That is my issue xd

warm marsh
#

What version of djs?

#

11.6.4

clever tree
#

yes

warm marsh
#

Idk, Nothing in the code looks too much of an issue.

#

Might seem stupid but does ServerMusicQueue actually store a value?

clever tree
#

I think that could be a problem, but if u look at the last line there is simple function with a given ytlink for ytdl. But that doesnt work neither

warm marsh
#

playStream?

next remnant
#

okay so i got as far as creating a command subclass. in the run method

    // ...
}```
what do i return? it won't compile i don't return anything or remove the return type
warm marsh
#

From what I saw, return message.say('content');

clever tree
#

Thats the problem. I used the same code for 3 weeks. Everything worked. Yesterday I changed a timeout from 10000ms to 8000ms. After that I got this error (only an example. It was in Index.js). I turned of my pc, turned on after a day again and then got this the music error.

next remnant
#

why do i need to even return a message?

#

what purpose does it serve

warm marsh
#

Idk.

#

I've never used commando.

#

Just try returning 0 if you don't want to return a message

tulip ledge
#

u have a solution for me?

warm marsh
#

Working on it.

#

FeX have you tried reinstalling ytdl idk if you said.

clever tree
#

Reinstalled it like 3 times or sth. Thats not fixing the issue. Idk i changed nothing about the packages. The only thing I know is that the version of the dependencies for ytdl-core i use are older then the dependencies ytdl-core with that version actually has. I installed them manually. But if i remove mine ytdl-core starts playing and instantly leaves the channel without sound. So idk whats wrong with ytdl, ffmpeg and node-opus together xd

warm marsh
#

@tulip ledge module returns a function.

clever tree
#

But if nothing is wrong, should I buy a new pc or sth xd
I dont know. Noone knows this issues or even no a solution. Its creepy xd

warm marsh
#

Nah your PC won't be causing the problem.

tulip ledge
#

what do i do wwith the function?

warm marsh
#

oh nvm.

#

You get 0 from console.logging module?

tulip ledge
#

yup

fluid basin
#

But if i remove mine ytdl-core starts playing and instantly leaves the channel without sound
@clever tree what do you mean by this

clever tree
#

@fluid basin If i remove my manually installed ytdl-core dependencies with older versions the bot joins and instantly leaves the channel.

fluid basin
#

why would you do that though

warm marsh
#

@tulip ledge replace searchItem with item.

clever tree
#

because of exactly the join, instant leave issue i donwloaded older versions which have not that issue. @fluid basin

tulip ledge
#

I dont see how that will change

clever tree
#

But i did not change them in this 2 weeks. Thats not the issue. They worked well.

warm marsh
#

Just try it.

tulip ledge
#

Cuz where I define the cuntion it's just a parameter

fluid basin
#

you should be using the latest version

warm marsh
#

Nvm

tulip ledge
#

Still 0

warm marsh
#

I just saw that.

#

Would do you pass as args?

tulip ledge
#

dimond

warm marsh
#

I think the ratio function is the problem.

#

nvm

#

Changed the wrong value.

tulip ledge
#

?

warm marsh
clever tree
#

@fluid basin If i use the newest version of ytdl-core (2.1.5) the bot joins the channel has no sound and instantly leaves the channel again. :/

tulip ledge
#

I dont get what u mean with that Dillon

warm marsh
#

I'm testing.

#

It's something todo with your array.

#

Change keys to equal

let keys = Object.keys(itemfile).filter(x => itemstosearch.includes(x));
fluid basin
#

you should try to print the error you are getting from ytdl @clever tree

#

if the bot joins and leaves it means that it has nothing to play

tulip ledge
#

Euh lol

#

Now it said dimond equals redstone

warm marsh
#

Lol.

next remnant
#

I register my commands as

client.registry
    .registerGroups([
        ['first', 'Your First Command Group'],
    ])
    .registerDefaults()
    .registerCommandsIn(path.join(__dirname, 'commands'))
warm marsh
#

change entry1 with entry2 and entry2 with entry1.

tulip ledge
#

Oh

#

It things that everything is redstone

clever tree
#

@fluid basin So it get the video, the url and the id. So i think everything he needs to play xd

next remnant
#

and it isn't picking up the test command

tulip ledge
#

Still does the same thing

next remnant
#

whenever i run {prefix} test

#

i get unknown command

warm marsh
#

Maybe it's looking for files in that dir only and not recursive.

next remnant
#

idk

warm marsh
#

Try putting test.ts in /commands and not /tests

next remnant
#

does anyone know why it isn't working?

warm marsh
#

first*

tulip ledge
#

Dillon

earnest phoenix
#

Anyone having problems with bot getting started?

tulip ledge
#

It still corredcts everything to redstoneยต

next remnant
#

Error: Group "first" is not registered.

warm marsh
#

Oh groups.

#

What does the file contain?

next remnant
clever tree
#

@fluid basin I used to test. Same issue. What should I do ?

async function testing(connection, message) {

                const serverdispatcher2 = connection.playStream(ytdl("https://www.youtube.com/watch?v=G9ffM4EJPVs", { filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1 << 25 }))
                    .on("end", () => {        
                            connection.disconnect(10000);
                    })
                    .on("error", error => {        
                        console.log(error)
                    })

                }

                message.member.voiceChannel.join().then(function (connection) {
                        testing(connection, message);
                    })
warm marsh
tulip ledge
#

?

warm marsh
#
const resp = keys.sort((key1, key2) => {
  return ratio(key2, test) - ratio(key1, test);
})[0];
tulip ledge
#

Wait

warm marsh
#
const keys = Object.keys(file)
  .filter(key => words.includes(key));```
tulip ledge
#

Ok

#

So I replace module with resp?

warm marsh
#

Yeah

#

I just used resp as module is a keyword.

tulip ledge
#

I change module to resp aswell?

warm marsh
#

Yeah

#

weeb simp, I don't know did you follow what it said in the guide?

#

file -> itemfile Chickendev.

fluid basin
#

the error should show automatically in the console

next remnant
#

im following the guide

#

it says to create it in first folder

warm marsh
#

Alright.

tulip ledge
#

Alight it works now

#

Its just

clever tree
#

@fluid basin It has no error at all. And console.log(dispatcher) works too