#development
1 messages ยท Page 949 of 1
okay
This for example
oh in the API it's called news, I'm sorry
No problem
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)
Thanks
No problem
For how much time should I keep a prefix in the cache?
@balmy knoll you meant reacting with an emoji?
For how much time should I keep a prefix in the cache?
I thought about 5 mins
@opaque seal forever, as long as it remains unchanged
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
if someone changes the prefix, then you remove it so it can update
Dosen't that make the ram go crazy?
I'm trusting you then
so you can slap it with 5 million guilds and it will still use only 20mb of ram
@nocturne grove I mean publish a message in a news channel
so you can slap it with 5 million guilds and it will still use only 20mb of ram
dope
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 ?
you're only ever gonna have 1 prefix per guilds right?
so you dont need a collection
'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?
a simple string
Because I need the guild ID and the prefix
@earnest phoenix do u know what u need to do?
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)
oh I thought you meant the prefixes variable to not be a collection
client.prefixes can stay a collection, since it holds multiple items
yeah yeah I got it
but client.prefixes.set(guildID) doesnt need to be a collection
@earnest phoenix do u know what u need to do?
@digital ibex no
I mean how do I get the guild count across all shards
also I use eris-sharder for shards
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 "$"
@opaque seal see updated message
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;
}```
the prefix is not always in the db
unless you add it immediately on the guildCreate event
alright then yes
Is that bad practice?
no, not really, but it can be waste of cpu since a a guild can be joined and left without being used once
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
happens more often than you think, because people are stupid
but its not a problem
lol
that wont make or break your bot
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
my database only contains custom prefixes, not defaults
so its only ever saved if they change the default, otherwise it doesnt save anything
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?
depends on how you set it
prefixes.set(guildID, prefix);
and prefix is already the string, right?
yes
oh
there is no guildPrefix.prefix
const guildPrefix = prefixes.get(guildID); if (guildPrefix) prefix = guildPrefix;
should be good
yes
Nice, thank you for your help
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?
how do i get specific items from a dir file?
@nocturne grove actually i dont
i dont even delete it when the bot leaves the guild lmao
i should tbh
oh lmao
I even delete the whole guild row when the prefix is set to default and nothing else is in it
yeah im probably gonna do the same
i just hate updating the bot and having to restart it lmao
I delete all guild related info from the database when the bot leaves
i was alrady meaning to do that before, but i forgot

@pure lion you mean you want to read files from a directory?
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
is it bad that i dont?
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
ohhhhhhhhhhhhh
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)
java
you can mention a user by sending <@USERIDHERE> in any language
idk how to interpret this for ytdl
show the ytdl response
well
const songInfo = await ytdl.getInfo(results);
results is the dir
but idk how to access
console.log(results)
in js
access the dir object thing (brb)
js is javascript, not java
method: 'get',
url: 'https://www.googleapis.com/youtube/v3/search?q=bloodbath&part=snippet&maxResults=1&key=AIzaSyCKC-2EQzfCqU63ZfVN1wxYOLj4z3nTtKU'
js used in BOTS
thats in the console
Java is used in Discord bots too
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. :/
yes
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 ?
yes.
@pure lion where did you get results from? that doesnt look like a ytdl response
brb
also, you should reset your youtube key
@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
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
how to make bots in c++
learn c++
then learn c# and forget c++
why
any reason you're using console.dir and not console.log?
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))
try using console.log
me?
no, elisdia
great
perfect
w o n d e r f u l
SyntaxError: await is only valid in async function
async (err, results) => {
@opaque seal it should work
you can check if halls got any smaller afterwards
uhm
how can I do that? I mean the variable already changed I can't check its earlier status
record its length before and after
you dont even need to make a variable, you can just console.log it
i know why it doesnt do console.log
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:
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?
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
you're trying to get an array of users?
h
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
guild.moderations seems to contain several references to the same user, so if you use .filter(), you'll get all of them
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
everything works as expected, just not the https://discordapp.com/channels/264445053596991498/272764566411149314/716243827286867979 bit btw
so you want to get the mod and do what with it?
get their username
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];
}
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
@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"
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
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"))
oh
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?
import traceback
@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
main or cog?
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
Both
you will need a for loop inside a for loop
oh
because the filtered kick and ban can still contain multiple references
im lost
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)```
i'd prefer not to use the second one tbh, but if its easier i'm gonna use it lol
combined = [...guild.moderations.filter(filter for kick), ...guild.moderations.filter(filter for ban)]
and then loop over combined
@slender thistle ^
are you sure that cog is actually loaded?
cog is not loaded idk why
idk how to dir, send help
did you console.log?
@slender thistle can u guide me with the problem
lemme check if it works (again)
Can you remove the except branch from your cog-loading part?
what does the console.log show?
what does the console.log show?
@quartz kindle me?
no, elisdia
@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?
@earnest phoenix the error says catch not cache
tim console.log works now
and what does it show?
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
the same as before but not nestled, all the same level
@earnest phoenix show the full error
@pure lion show it
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?
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
}
rate limits are queued, so they wont fire errors, they will just sit in the queue and wait
you'll need the rateLimit event
i just want the url
so my bot will wait 10 minutes to update a channel name, as long as it is online?
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)
@pure lion the data you need is this
not the url
so you're doing something wrong
how do i access the stuff tho
also, no clue what im doing wrong, all i want is the URL and nothing else
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
@earnest phoenix yeah
the results should contain a big list of videos, their ids, authors, channels urls, etc...
restart the bot, I mean
ok
@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?
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
you need to track limits yourself
if you wait for the rateLimit event, there will be an item queued there already
@slender thistle is this normal if i type : console.log(serverdispatcher.player) ?
okay thank you. Will make a whole thing for that
now I have to find out what that "thing" should be
what is member?
In discord.js, how can I take the last message sent by the bot in a specific channel?
I think you should fetch messages and check for the first one you will come across that's sent by the bot
can't you send it using some markdown or hastebin?
Huh?
you sent a file
if the api returns only image data without a file name, you need to define your own file name
No lol i mean like this:
So the image in the embed is the pixelated version of my avatar... But when i download it... It comes out as this
(was talking to memmo)
files: [imagedata] -> files:[{attachment:imagedata,name:"myfile.png"}]
oh I'm sorry I thought your file was a piece of code ๐คฆ
Lol... But can i define it's name in the .setImage() as I'm using? @quartz kindle
you define it in the attachment
then on the setImage you use the new name
attachment://myname.png
Oh ok
<dying noises>
(thanks btw @quartz kindle)
What is better/faster? A collection or an object? Or are there no performance differences?
objects will probably be slightly faster because its a less complex structure
okay thank you
but the difference should be irrelevant
I prefer objects in this case so will go for that one
Hey
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
because async forEach is a bad idea
it is?
yes
oke that might be the issue then
async forEach spawns several copies of async functions, which are not controllable
ofc yes thank you
you need a for loop
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
what would a for loop in this case look like
@earnest phoenix Is the error fixed yet?
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
and how should i handle the rror
you can handle it with a try catch or with a .catch(), doesnt really matter in this case
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
Show the code around the error
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
Does anyone know why it gives me an error of "Cannot read property 'members' of undefined"?
@river wing replace .find by .get
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?
you'll use find if you want to find a channel by name, description, type etc.
@river wing replace
.findby.get
but i still get the same error message
@earnest phoenix Show your main file
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
@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)```
isnt the guild id the server id that i copy?
yes that's right
@river wing yes
is your bot in there, @river wing?
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?
yes my bot is in there
that's weird
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
that's weird
@nocturne grove now it worked. but why does it always have a tendency to fail?
@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```
someone know why hosting lavalink on heroku always off in 1 or 2 hours ?
this prob again
why would you use lavalink on heroku lmao
What does your for extension in initial_extensions: loop like rn
that will never work lol
until yt bans your IP lol
xd
@river wing it doesn't have a tendency to fail for something like that. Idk what you did wrong
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?
Assuming I know JavaScript :p
well frick
@wet iron where does it say Won't kick? Do you mean Can't find user! :angry:?
or an error?
@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 ?
let kReason = args.join(" ").slice(22); valid in code v12 ?
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 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.
Just post as many details as possible and someone who can will help you eventuallyโข๏ธ
@river wing oh wtf that's strange
yes @jagged haven. thats got nothing to do with the library
UnhandledPromiseRejectionWarning: DiscordApiError: Missing permissions
@digital ibex me too error giving
then its cuz ur bot doesn't have permissions
UnhandledPromiseRejectionWarning: DiscordApiError: Missing permissions
@wet iron who are u kicking
a friend that doesnt have a rank
you have to compare more than what you did. Position of highest role, bot perms, kuser perms
oh yes what @digital ibex said
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)
oh i fixed it
args is undefined @jagged haven
maybe define it
what is member
@digital ibex how can i define ?
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
did he tho?
yeah. cuz then it would say 'reason is not defined' wouldn't it?
a properly configured args will be an empty array if no arguments are provided
empty arrays can still be joined
Where could i post my problem too, to get more help ?
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?
I don't think so, as a MessageAttachment could also be other files than images
https://discord.js.org/#/docs/main/stable/class/MessageAttachment?scrollTo=url @earnest phoenix does this help you maybe?
So what can i do to name an attachment that can be set to .setImage() ?
(an image attachment)
try attachFile() or something
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...
I want the image inside the embed not outside of it lol @pale vessel
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)
@nocturne grove hmm lemme see
no, you use attachFile so that you can use attachment://
to my understanding he has a MessageAttachment and wants to set that as an image to an embed (assuming the attachment is an image)
(Literally getting the image from the api but i want to name that and set it as the .setImage() of the embed)
because you want to hide the key?
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?
Nah i want it downloadable as an image extension not this @pale vessel
you should add an extension
they do
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
Which one you want?
lol
use round/floor
hi.
Could not extract html5player key: https://www.youtube.com/s/player/de455b1a/player_ias.vflset/en_US/base.js
I have this problem, how can I solve it?
You don't solve it
is there a problem on youtube?
Hey guys.
I have a big question:
How do I get the datas (Name, ID etc) the user, who used the OAuth2
Yes, but this shouldn't affect the play song function
I already have a server
See what the oauth2 retusn you and use it
My friend has a bot coded with Javascript I am my friend were thinking about how to make it so it says its streaming?
See what the oauth2 retusn you and use it
How can I do this with JavaScript?
But we were wondering what the code is for it.
@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
@tight plinth sry for the ping. And how can I connect my code with the oauth2?
Read discord docs
Could not extract html5player key: https://www.youtube.com/s/player/de455b1a/player_ias.vflset/en_US/base.js
@lofty grove change the api key , make a new one from a new id
And Google can help you
Okay. What should I search? I am new, so i don't know what would be the best
Just search what you need
member.roles.array().slice(1).sort
how do i make this to work in v12
Okay, thank you
@slender wagon member.roles.cache...
It's not only the role managet
It's also like every manager (members, users, channels and I probably forget others)
they have the cache right?
Yed
it confuses me ngl
Someone
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 change the api key , make a new one from a new id
@earnest phoenix it didn't work, are you available?
@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
do you have the same error in your bot?
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
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)
STRING.includes('%0')
@tight plinth returns false if someone uses %0A (created massive issues wich caused pm2 to panic)
No
i already tested it and it returned false while the argument was %0A
(not with regex)
@earnest phoenix I did thank you I made a few adjustments.

It works smoothly now
Thank you buddy.
When you use the g flag, you need to reset the lastIndex to 0
@lofty grove no problem buddy
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
My mind isn't functioning atm but how do I clear up a whole json file and make it only say {} again?
just jsonfile = {} and then save it?
or that
Wiping file content sounds better than re-creating a file ngl
What is the diffrence between findone and find in mongoose?
find finds multiple documents whereas findOne returns only one document
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
what lib are you using?
Using Python and Pillow
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
@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
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
nw
const member = msg.mentions.users.first() || bot.users.fetch(args[0]);
return msg.guild.ban(member)
msg.guild.ban is not a function
in v12 its guild.members.ban(id) or member.ban()
use then/await
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?
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?
@digital ibex restart ur computor
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
Is that normal when i type console.log(dispatcher) ?
Yes?
I mean speaking: false
Anyone knows how to implement levenshtein distance to find the closest match and not what the difference is?
actually yeah, i do
How?
what lang
Javascript
there's an npm module for it
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
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)
}```
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
you made your own implementation? awesome
<0.7 being my own filter
i just copied the npm module's source code over to my projects so i dont need to add it as a dependency lmao
no, you can modify the code
So I'll havbe to map it first
i think it actually transforms the map into an object
or array
idfk
just read the code and figure it out lmao
So I suppose the mostSimilar is used in the file where u wanna use it and the levenshtein is a diff file?
Right
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
lmao
you modify it to fit your needs
But I put it in the file I need right
why am i getting this again, i just restarted my pc
or export it from another file, whatever floats your boat
i already installed vue btw
is it added to path
yes
I've never done something like this before lol
Having it in my util ius ok right?
modify the second one to do whatever you want it to
I'm gonna change it
i just done vue init and i get that
To be able to work with a json
yeah its perfectly fine as long as you are importing it from there
yes
yes of me being braindead or?
@mossy vine u kno how i can initialise the project?
So like this should work
I'll just add it to my client object then so I can use it in my commads and stuff
however you want
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
i'm trying out d.js and commando
i follow the first example from the first steps page of commando
when i try to import client, i get this error
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
https://discord.js.org/#/docs/commando/master/general/first-steps (im following the first example on this page)
help?
you need to install commando from their github
the version on npm is outdated afaik
how do i do that?
npm install discordjs/commando
https://hastebin.com/ugajitavoy.js
entry2.toLowerCase is not a function
hi
Tim u know my problem?
@tulip ledge entry2 is not a string
npx vue
did you restart your pc?
Wait what
yeah
Probably due to not being installed globally
did you install vue globally?
Using -g flag.
uhh, i didn't
pretty sure its vue-cli or something
@mossy vine (sorry for tag)
yeah. i just done npm install vue-cli
Help pls
you need -g
oh, ok
I verry confused
Do npx vue-cli.
nvm, thats for npx
Why is entry2 not a string tho
Using module doesn't throw an error?
Entry2 equals 1
toString it?
I'll try
Oh I'm so-
Wtf
TypeError: client.levenshtein is not a function
Like wth
What's in that file?
// 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)
}
You need to use client.levenshtein.levenshteinRation
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
are there any examples on how to define commands other than digging through the example bot code?
if content == command {}
No?
pain to scale
Right. What language are you using?
Okay.
Files are typically laid out like
module.exports = {
run: function() {}
}
// or
module.exports = class {
method() {}
}```
called like require('file').method
or new method()
can i get a link to documentation for this?
There is no docs?
Can somebody help me?
One sec
Cuz I'm losing braincells
i can't find anything on https://discord.js.org/#/docs/commando/master/general/first-steps
Commando
It's not dep?
what
deprecated
neither on docs nor on repo
can someone help me?
@tulip ledge what is the error?
Otherthan 1
that is api refernece
not documentation on how to use it for someone who has never used it before
Idk, I've never used commando as pretty sure it was deprecated.
if it is deprecated then why do they not say it anywhere
anyone here familiar with vue?
Do you have a sloution or not?
I'm reading your code.
Idk if that's of any use.
i like how you unironically called them weebsimp
That's his displayname.
yep
their*
ah yes, it's dangerous these days
๐ very
commando ew
which one should i follow?
commando bad
^
what else to use?
what comamnds framework to use?
i ain't writing my own
legit
it's not hard
eris has a command client too
@tulip ledge x => x = x?
but i never used it
its a pain to deal with + more code to maintain
same
Yeah I'm bad at mapping
it's actually less for me
And u needed to pass a function
but idk
Check file is an array
idk
and then it's just an array of strings?
Maybe checkfile = itemstosearch.map(x => itemfile[x]);
I'll try
if commando is bad (other than making my own) what should i use?
Still logs 0
scalability
Basically when I type dimond it should "correct" it to diamond
Use regex?
im sorry i dont wanna write my own converter system, checks system, concurrency system and list goes on
And it needs to correct it to the closest
Most common other than writing yourself is DJS.
discord.js itself is an api wrapper, not a command framework
commando is command framwork
commando then
no its not an api wrapper
No, You just write that yourself.
it is
Takes like 20 lines max
barely
You have a solution of mine?
why does vue take so long to install
Internet?
just use a simple command handler
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()
wdym if statement?
Ah.
@mossy vine made it
Did you change client.levenshtein to client.levenshtein.levenshteinRatio()
does djs not have a default error handler? (once that just logs to console)
yup
djs requires a little more setting up.
What's skyblock/items.json diamonds equal to?
Mhh
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 
Any errors?
for me?
no. Console is clean
yes. I had ffmpeg installed manually. And then i installed ffmpeg-static. I use js
i used node-opus before. And then i updated to @discordjs/opus after that issue
That is my issue xd
yes
Idk, Nothing in the code looks too much of an issue.
Might seem stupid but does ServerMusicQueue actually store a value?
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
playStream?
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
From what I saw, return message.say('content');
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.
Idk.
I've never used commando.
Just try returning 0 if you don't want to return a message
u have a solution for me?
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
@tulip ledge module returns a function.
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
Nah your PC won't be causing the problem.
what do i do wwith the function?
yup
But if i remove mine ytdl-core starts playing and instantly leaves the channel without sound
@clever tree what do you mean by this
@fluid basin If i remove my manually installed ytdl-core dependencies with older versions the bot joins and instantly leaves the channel.
why would you do that though
@tulip ledge replace searchItem with item.
because of exactly the join, instant leave issue i donwloaded older versions which have not that issue. @fluid basin
I dont see how that will change
But i did not change them in this 2 weeks. Thats not the issue. They worked well.
Just try it.
Cuz where I define the cuntion it's just a parameter
you should be using the latest version
Nvm
Still 0
dimond
?
@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. :/
I dont get what u mean with that Dillon
I'm testing.
It's something todo with your array.
Change keys to equal
let keys = Object.keys(itemfile).filter(x => itemstosearch.includes(x));
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
Lol.
I register my commands as
client.registry
.registerGroups([
['first', 'Your First Command Group'],
])
.registerDefaults()
.registerCommandsIn(path.join(__dirname, 'commands'))
change entry1 with entry2 and entry2 with entry1.
@fluid basin So it get the video, the url and the id. So i think everything he needs to play xd
where test.ts is https://pastify-app.web.app/show/nqdIxhxvOWkGkyGXpavV.ts
and it isn't picking up the test command
Still does the same thing
Maybe it's looking for files in that dir only and not recursive.
idk
Try putting test.ts in /commands and not /tests
does anyone know why it isn't working?
first*
Dillon
Anyone having problems with bot getting started?
It still corredcts everything to redstoneยต
Error: Group "first" is not registered.
where test.ts is https://pastify-app.web.app/show/nqdIxhxvOWkGkyGXpavV.ts
@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);
})
@tulip ledge
?
const resp = keys.sort((key1, key2) => {
return ratio(key2, test) - ratio(key1, test);
})[0];
Wait
const keys = Object.keys(file)
.filter(key => words.includes(key));```
Yeah
weeb simp, I don't know did you follow what it said in the guide?
file -> itemfile Chickendev.
the error should show automatically in the console
Alright.
@fluid basin It has no error at all. And console.log(dispatcher) works too