#development

1 messages · Page 660 of 1

tight heath
#

well you cache in either RAM (implement in your program), or a dedicated cache (I use redis)

steel cloak
#

and is that completely separate from the database?

maiden mauve
#

so that scope should work in theory?

inner jewel
#

or you could do no caching at all

tight heath
#

since mongo is pretty damn fast on its own

maiden mauve
#

"heal":

inner jewel
#

any real db can easily handle a discord bot (unless it has millions of guilds)

tight heath
#

groovyman

hushed berry
#

henlo

#

its i

steel cloak
#

ahh okay thanks a lot from you all uwu

scenic vapor
#

who dis new phone

hushed berry
#

woo boy do i love mongodb

tight heath
#

mango de bee

hushed berry
#

it totally doesnt force me to retry transactiosn 3+ times everytime i do them

#

for some reason

tight heath
scenic vapor
#

ravy when are you making mongo-bongo

maiden mauve
#

I started loving mongodb when I wrote this

inner jewel
#

mangodeebee is webscale

maiden mauve
#

ravy with the better structure for it

#

but its just so damns imple

#

range of what to find

#

everything to find

#

sort the find by a property

tight heath
#

@scenic vapor whenever I need a mongo wrapper

maiden mauve
#

filter it by a limit

tight heath
#

currently I don't

maiden mauve
#

then call back

inner jewel
#

select * from players where serverId = ? order by level desc limit ?

tight heath
#

because it's handled by a framework for me

scenic vapor
#

go yoink it

maiden mauve
#

Natan is that SQL?

scenic vapor
#

from somewhere

inner jewel
#

yes

tight heath
#

@scenic vapor I would use a custom thing for my bot but it's open source and I want people to actually understand and be able to contribute so I use well-known stuff

earnest phoenix
#

How to define rank in SQL

maiden mauve
#

my usage of Mongo is caveman style, but it was quick to learn

tight heath
maiden mauve
#

I just needed a db that had a json-type structure for player rpg stats

scenic vapor
#

you're very smart sire

#

my leige, my lord

#

kneels

tight heath
#

lord eh

earnest phoenix
#

quick.db

#

?

tight heath
#

no please

scenic vapor
#

my king!

tight heath
#

do not

#

ever use quick.db

hollow saddle
#

Never ever use quick.db

#

I would die

inner jewel
#

brb making fast.db

tight heath
#

the db that advertises upon every error™

#

@inner jewel I double dare you

scenic vapor
#

my emperor?

tight heath
#

*your highness

#

:)

earnest phoenix
#

@tight heath yea. Also it has many bugs

scenic vapor
#

your bad

tight heath
#

it's princess ravy

scenic vapor
#

oh

#

Grill?

#

epic

tight heath
#

charcoal

scenic vapor
#

your highness

tight heath
#

it's 6am

#

I need to wake up at 8

#

mfw

mild glade
#

^ yes it indeed is

#

big oof

scenic vapor
#

You're already awake!

#

Good job!

#

You did it ahead of time!

tight heath
#

I'm kinda more in a caffeine wake-ish state

maiden mauve
#

player name casts spell on theirself

#

player name casts spell on themself

tight heath
#

themselves

scenic vapor
maiden mauve
#

a plural?

tight heath
scenic vapor
#

you've a problem

#

it's what it's

maiden mauve
#

I truly pity anyone trying to learn ESOL

tight heath
#

I mean

#

I am

#

:p

maiden mauve
#

hahaha I consider myself to have a good vocabulary, but I've never really gone into the intricacies of grammar

tight heath
maiden mauve
#

👍

#

to on-topic ill change it

#

for whatever reason I had an issue with abbreviated conditionals in the past

tight heath
#

you mean the ternary operator

maiden mauve
#

yes

#

? ternary

#

but it should work fine with strings right?

tight heath
#

it works fine with everything tbh

#

just don't put a semi before the :

opaque eagle
#

Is it possible to have an asynchronous [Symbol.iterator]

#

JavaScript of course

inner jewel
#

tl;dr Symbol.asyncIterator + for await(x of y)

scenic vapor
#

hey its ya boi amature programmer here, how do i pass a variable from a function to another or make it global?
For example,

if(x === "20"){
    const y = "50";
}
console.log(y)

only an example to help another issue any help appreciated thanks

opaque eagle
#

huh

maiden mauve
#

function? return

scenic vapor
#

odd wasn't working for me

opaque eagle
#

That exact codeblock won't work @scenic vapor

maiden mauve
#

your example is just a conditional that outputs correctly

#

except y can be undefined

opaque eagle
#

y won't be defined at all

inner jewel
#

it'll be a ReferenceError

opaque eagle
#

as far as javascript is concerned, y doesn't exist outside that if statement

inner jewel
#
let y = some default value;
if(x === "20"){
    y = "50";
}
console.log(y)```
tight heath
#

let y;

scenic vapor
#

Okay, thank you. Ill try that out, was doing that before but maybe something else was undefined.

opaque eagle
scenic vapor
#

@opaque eagle Thank you, will do -- I just realized why it was returning undefined, annd thanks for the help

maiden mauve
#

haha

#

never seen that kind of syntax kick

#

const similar but different

inner jewel
#

because that'd make no sense

opaque eagle
#

You're forgetting the {}

#

Also what r u trying to do anyways... 1 === 1 would be true at all times

tight heath
#

{} are not required for one-liners

opaque eagle
#

Yeah but you can't define variables using a one-liner if statement

inner jewel
#

but it's good practice to always use {}

opaque eagle
#

That too ^

tight heath
#

if you multiline

#

that is

inner jewel
#

see: CVE-2014-1266

opaque eagle
#

I only use a one-liner if when I'm returning some value

tight heath
#

if (true) throw 'natan nerd';

inner jewel
#

that's probably the most famous case of lack of {} leading to issues

#

in that case, ssl being completely broken

maiden mauve
#

1 === 1 just to create a conditional declaration

opaque eagle
#

oh nvm

tight heath
#

if(1)

maiden mauve
#

shush

tight heath
#

if(!0)

maiden mauve
#

I am a hobbyist of the hobbyist order

inner jewel
#

if(true)

tight heath
#

if(!false)

#

if(!'')

maiden mauve
#

dog = "sAiNt BerNaRd";
if(dog.toLowerCase() === "saint bernard")

tight heath
#

if(__dirname !== dog)

scenic vapor
#

if(0===0){zero=0}

earnest phoenix
#

I want to get this Store { id: 4835, name: 'Spectre', rarity: 'Sturdy', category: 'BRDailyStorefront', vbucks: 800, image: 'https://cdn.thetrackernetwork.com/cdn/fortnite/ECF94835_large.png' },
i used let imagine = shop.filter(s=> s.id == 'image')[0]; => undefined

but isn't working

Details

0:Store {id: 11583, name: "Dream", rarity: "Sturdy", …}
1:Store {id: 11584, name: "Astral Axe", rarity: "Quality", …}
2:Store {id: 11582, name: "Arcana", rarity: "Quality", …}
3:Store {id: 868, name: "Shadow Ops", rarity: "Quality", …}
4:Store {id: 11585, name: "Shard Break", rarity: "Sturdy", …}
5:Store {id: 11581, name: "Luminos", rarity: "Quality", …}
6:Store {id: 5340, name: "Waterworks", rarity: "Handmade", …}
7:Store {id: 354, name: "Stealth", rarity: "Handmade", …}
8:Store {id: 11019, name: "Slap Happy", rarity: "Sturdy", …}
9:Store {id: 10897, name: "Munitions Major", rarity: "Handmade", …}
10:Store {id: 4835, name: "Spectre", rarity: "Sturdy", …}
11:Store {id: 5400, name: "Noir", rarity: "Quality", …}```
inner jewel
#

none of the ids are equal to image

earnest phoenix
#

i just want to get the images from all 12 array

sinful cairn
#

Hi guys

earnest phoenix
#

Can someone explain to me what does ? do in JS?

sinful cairn
#

When is the release date for rule bot

earnest phoenix
#

?

#

wdym

pale marsh
#

]]wrongserver @sinful cairn

covert turtleBOT
#

This server is NOT the support server for ANY bot. You need to click on the "Support Server" button on the bot's page, not the "Join Discord" button at the top of DBL.

pale marsh
#

Also wrong channel

#

@earnest phoenix wdym by ?

#

Show us an example code?

earnest phoenix
#

something ? something : something

pale marsh
#

Ah conditional operators

#

It's like condition ? value_1 : value_2

#

If condition is true then value_1 is returned

#

If false value_2 is returned

earnest phoenix
#

oh thanks

pale marsh
#

At least that's how it is in C#. Not quite sure about JS

earnest phoenix
#

i think they are the same

#

i think

pale marsh
#

You can try and confirm I guess

inner jewel
#

it is

pale marsh
hushed berry
#

also known as the ternary operator 😃

inner jewel
#

(technically a ternary operator is one that has 3 operands, it just happens that it's the only operator with 3 operands in most C-based languages)

hushed berry
#

pfff

#

get out of here with your technicalities natan

inner jewel
#

i only know that because i had to define a ternary operator type

earnest phoenix
#

how can i make owner buttons square (in my bot page)

#

please mentions me when you answer

icy glen
#

Ah, the best way to ensure no one can access these permission levels ;)

  if (message.author.id === undefined) permlvl = 7; // Reserved
  if (message.author.id === Infinity) permlvl = 8; // Reserved
  if (message.author.id === false) permlvl = 9; // Reserved
  if (message.author.id === "230880116035551233") permlvl = 10; // Developer
  if (1 === 2) permlvl = 11; // secret```
spare goblet
bitter sundial
#

but why

indigo geyser
#

i am trying to muse commands with python and i did this:

@client.command()
async def test(ctx):
  await ctx.send('Toast')

i put the client = commands.Bot(command_prefix='"') but nothing appears and there are no errors

#

pls help

past charm
earnest phoenix
#

syntax highlighting

past charm
#
if(null == null) continue;
#

?

earnest phoenix
#

for c# it's cs

past charm
#

oh

#

tnx

indigo geyser
#

pls help :(

earnest phoenix
#

be patient, you aren't contributing anything but just being annoying by doing that, if someone who does python and know how to resolve the issue comes across it, they will probably help you

indigo geyser
slender thistle
#

@indigo geyser send whole code

indigo geyser
#

ok

#
from keep_alive import keep_alive
import discord
import os
from discord.ext import commands
import asyncio
import random


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


@client.event
async def on_ready():
  print ('I am', client.user)
  time = 0
  while time == 0:
    await client.change_presence(activity=discord.Game(name='Tanto siamo anti Raid'))
    await asyncio.sleep(5)
    await client.change_presence(activity=discord.Game(name='"help'))
    await asyncio.sleep(5)

@client.command()
async def test(ctx):
  await ctx.send('Toast')

@client.event
async def on_message(message):
    if message.content.lower().startswith('"ping'):
        emb = discord.Embed(title='*~~{}~~ PONG*'.format(message.author), colour = 0x846a15)
        emb.set_image(url = 'https://cdn.discordapp.com/attachments/552786907424358401/587360986458226739/pong.gif')
        await message.channel.send(content=None, embed=emb)

token = os.environ.get("secret")
client.run(token)

keep_alive()
token = os.environ.get("secret")
client.run(token)
#

@slender thistle

slender thistle
#

What the fuck

indigo geyser
#

whole

slender thistle
#

Why keep_alive and multiple .runs

#

When it's literally blocking and the docs say so

indigo geyser
#

because i was trying if it works with two difference runs

slender thistle
#

Yeah that ain't happening. Use only ONE client OR Bot instance

indigo geyser
#

fixed

slender thistle
#

Also, you assign the test command to bot but client runs first

#

So either use bot or client, not both

indigo geyser
#

i edited the message

slim heart
#

working
trying something to see if it works
no longer working
pikaOh

twilit rapids
#

CTRL + Z the fuck out of your file

indigo geyser
#

but do you know why the async def test doesn't work?

#

it tells no errors

sudden geyser
#

@indigo geyser I don't have an answer to your question, but wouldn't that status change abuse the api

earnest phoenix
#

^ there should only be 5 status change maximum every minute

#

or else its counted as an API abuse

slender thistle
#

Legit said why it doesn't work

earnest phoenix
#

is there an if to check if the user's DMs are closed?

slender thistle
#

Negative

earnest phoenix
#

oof

slender thistle
#

You'll have to send a message and then see if it errors out with a Forbidden

earnest phoenix
#
(node:3908) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user
    at item.request.gen.end (C:\Users\Dany\Desktop\DiscordBot\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
    at then (C:\Users\Dany\Desktop\DiscordBot\node_modules\snekfetch\src\index.js:215:21)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:3908) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
#

not surprised at all

#

i'd just like the bot to return instead of sending this

indigo geyser
#

@sudden geyser it's a private bot

#

my bot that is here (@keen talon) wait 25 secs

#

@slender thistle i understood that if there is the on_message the commands doesn't work

#

i don't understand why

old geyser
#

seems
client.users.get('IDHERE").username
only seems to work when the bot is in the same server as that user, otherwise it throws a "username undefined" what am i doing wrong?

slender thistle
#

Obviously because you don't use bot.process_commands(message) when using on_message

indigo geyser
#

ok

warm marsh
#

@old geyser are you joking?

old geyser
#

@warm marsh nuh mate, learning, hence why i asked for help

warm marsh
#

The bot can only access users it shares guilds with.

old geyser
#

Thats all i needed to know

warm marsh
#

Alright. Good luck.

tight heath
#

@earnest phoenix send(...).catch(() => null)

sick cloud
#

@warm marsh wrong

#

@old geyser are you using discord.js

#

if so try client.fetchUser(id)

#

it fetches from the api

old geyser
#

thanks @sick cloud

pallid zinc
#

err at ```"scripts": {
"start": "node index.js"
},
{
"name": "god",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"abbrev": "^1.1.1",
"abort-controller": "^3.0.0",
"agent-base": "^4.3.0",
"ajv": "^6.10.0",
"ansi-regex": "^2.1.1",
"ansi-styles": "^3.2.1",
"aproba": "^1.2.0",
"are-we-there-yet": "^1.1.5",
"arrify": "^2.0.1",
"ascli": "^1.0.1",
"asn1": "^0.2.4",
"assert-plus": "^1.0.0",
"async": "^0.2.10",
"async-limiter": "^1.0.0",
"asynckit": "^0.4.0",
"aws-sign2": "^0.7.0",
"aws4": "^1.8.0",
"balanced-match": "^1.0.0",
"base64-js": "^1.3.0",
"bcrypt-pbkdf": "^1.0.2",
"better-sqlite3": "^5.4.0",
"bignumber.js": "^7.2.1",
"bindings": "^1.2.1",
"brace-expansion": "^1.1.11",
"buffer-equal-constant-time": "^1.0.1",
"bytebuffer": "^5.0.1",
"cacheable-request": "^6.1.0",
"camelcase": "^2.1.1",
"canvas": "^2.5.0",
"node": "^12.6.0"
},
"devDependencies": {},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/927gaming/godtypecode4.git"
},
"author": "GOD",
"license": "ISC",
"bugs": {
"url": "https://github.com/927gaming/godtypecode4/issues"
},
"homepage": "https://github.com/927gaming/godtypecode4#readme"
}

earnest phoenix
#

@tight heath thanks it worked

pallid zinc
#

err = `jq: error (at package.json:1): Cannot index string with string "engines"

parse error: Expected string key before ':' at line 1, column 10`

#

idk why err at package.json

inner jewel
#

because that's not valid json

pallid zinc
#

??

inner jewel
pallid zinc
#

what should it be??

#

scripts should be at top i think

inner jewel
#

...

#

json objects have no ordering

#

and you can't just randomly paste stuff in the file and expect it to work

pallid zinc
#

ok

west spoke
#

ye

#

though i like to keep my josn in order

#

json

pallid zinc
#

done

#

thanks

earnest phoenix
#

Anyone care to help me with this ping command that is just making me want to yeet myself out a window

import discord, random, asyncio
from discord.ext import commands as client
from Cogs.config import conf
#Imports


class Ping(client.Cog):

    def __init__(self, bot):
         self.b = bot #Please no touchy thx

    @client.command()
async def ping(ctx):
    embed = discord.Embed(
        colour = discord.Colour.pink()
    )
    
    embed.add_field(name='Pong!', value=f'`{round(client.latency * 1000)}ms`', inline=False)
    
    await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Ping(bot))

west spoke
#

whats the problem

#

@earnest phoenix

earnest phoenix
#

I change things slightly

#

let me get the error log

mossy vine
#

i dont think python decorators work like that

#

try indenting your ping function

earnest phoenix
#
  File "maid.py", line 42, in <module>
    client.load_extension(f"Cogs.{name}")
  File "/usr/local/lib/python3.6/dist-packages/discord/ext/commands/bot.py", line 617, in load_extension
    lib = importlib.import_module(name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 674, in exec_module
  File "<frozen importlib._bootstrap_external>", line 781, in get_code
  File "<frozen importlib._bootstrap_external>", line 741, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/root/alt-bots/sayonika/Cogs/ping.py", line 20
    await ctx.send(embed=embed)
            ^
SyntaxError: invalid syntax
#

I know its probably obvious, but i'm new to this stuff

#
import discord, random, asyncio
from discord.ext import commands as client
from Cogs.config import conf
#Imports


class Ping(client.Cog):

    def __init__(self, bot):
         self.b = bot #Please no touchy thx

    @client.command()
    async def ping(ctx):
        embed = discord.Embed(
        colour = discord.Colour.pink()
    )
    
    embed.add_field(name='Pong!', value=f'`{round(client.latency * 1000)}ms`', inline=False)
    
await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Ping(bot))

#

updated file

inner jewel
#

your indentation is completely wrong

earnest phoenix
#

figures

#

though why is ctx being a pain

topaz fjord
#

because your indentation is wrong

#

you're ctx.send is out of the function scope

earnest phoenix
#

I'm fixing the indenting

#

out of function scope?

slender thistle
#
  1. I suggest importing commands as it is
  2. Functions in a class must have an argument that refers to the class of the command, which is usually either cls or self
  3. FiX yOuR iNdEnTs
#

@earnest phoenix if the issue is still up

earnest phoenix
#

still existing

warm marsh
#

So, Can you remove bots from client.guilds.reduce((prev, next) => prev + next.memberCount, 0);?

#

or would I have to change memberCount to members.filter(member => !member.user.bot).size?

opaque eagle
#

This should do the same thingjs client.users.filter(user => !user.bot).size

#

No need to reduce

warm marsh
#

That only gets cached users.

opaque eagle
#

same with Guild.members iirc

warm marsh
#

Idk, It was discussed a few days ago.

opaque eagle
#

nvm

smoky spire
#

users are rarely not cached

opaque eagle
smoky spire
#

memberCount doesn't rely on cache, members.size does

opaque eagle
#

Yeah, i know now

warm marsh
#

But memberCount includes bots.

opaque eagle
#

Yep

smoky spire
#

so does members

warm marsh
#

So this is why I asked.

#

not if they're filtered.

#

members.filter(member => !member.user.bot).size

opaque eagle
#

That's why I suggested filtering

smoky spire
#

well that doesn't modify members itself but yes it returns a new collection

opaque eagle
#

If you're gonna iterate through client.guilds and filter members, you might as well just iterate through client.users

warm marsh
#

As I said, It doesn't get all the users.

#

There was another guy that also had this question and the response was to reduce guilds

#

with memberCount

quartz kindle
#

the only way to count members without bots is to fetch all members

#

afaik, guilds provide a method to fetch all members without caching them

warm marsh
#

<Guild>.fetchMembers('', size)

swift topaz
#

how do I call a function from my index.js to my command handler?

hollow saddle
#

Attach it to your client or module.export it

swift topaz
#

oh wait I can just make the function inside the module.export.run

swift topaz
#

I need help. My program won't go inside bot.on('ready)

mossy vine
#

whats your full code

earnest phoenix
#

adding to routing files to the same index

swift topaz
#
bot.on('message', async msg =>{
    
    if(msg.author.bot) return undefined;
    if(!msg.content.startsWith(PREFIX)) return undefined;
    var cont = msg.content.slice(PREFIX.length).split(" ");
    var args = cont.slice(1);
    if(msg.content.startsWith(`${PREFIX}play`))
    {
        const voiceChannel = msg.member.voiceChannel;

        if (!voiceChannel) return msg.channel.send("Puff! (I need to be in a voice channel to sing!)");
        
        const songInfo = await ytdl.getInfo(args[0]);
        const song = {
            title: songInfo.title,
            url: songInfo.url
        };

        if(!serverQueue) {
            const queueConstruct = {
                textChannel: msg.channel,
                voiceChannel: voiceChannel,
                connection: null,
                songs: [],
                volume: 5,
                playing: true
            };
            queue.set(msg.guild.id, queueConstruct);

            queueConstruct.songs.push(song);

            try{
                var connection = await voiceChannel.join();
                queueConstruct.connection = connection;
                play(msg.guild, queueConstruct.songs[0]);

            }   catch (error) {
                queue.delete(msg.guild.id);
                msg.channel.send(`I could not join the voice channel.`)
            }
        } else {
            serverQueue.songs.push(song);
            console.log(serverQueue.songs);
            return msg.channel.send(`${song.title} has been added to the queue!`);
        }

        return undefined;
        }```
earnest phoenix
#

tis does

mossy vine
#

nice token leak

swift topaz
#
function play(guild, song){
    const serverQueue = queue.get(guild.id);

    if(!song){
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
    }

    console.log(serverQueue.songs);

    const dispatcher = connection.playStream(ytdl(song.url, {filter : 'audioonly'}))
    .on('end', () => {
        console.log('Song ended');
        serverQueue.songs.shift();
        play(guild, serverQueue.songs[0])
    })
    .on('error', error =>{
        console.error(error);
    });

    
dispatcher.setVolumeLogarithmic(5 /5);

msg.channel.send(`Puff, puff puff! (Now playing: ${songInfo.title}!)`);

}
bot.login(token);


})
#

I'll just change it then

#

anyway yeah

earnest phoenix
#

straitup leakin your token in db

#

l

swift topaz
#
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const bot = new Discord.Client();
const fs = require('fs');

const queue = new Map();

bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) =>{
    if(err) console.error(err);

    var jsfiles = files.filter(f => f.split('.').pop() === 'js');
    if (jsfiles.length <= 0) {return console.log('No commands found.')}
    else {console.log(jsfiles.length + ' commands found.')}

    jsfiles.forEach((f, i) => {
        var cmds = require(`./commands/${f}`);
        console.log(`Command ${f} loading...`);
        bot.commands.set(cmds.config.command, cmds);
    })
})

const PREFIX = 'puff.'
const token = 'token-here';
var version = '1.0.0'
var servers = {};


bot.on('ready', msg =>{
    console.log('Jigglypuff is online.');
    bot.user.setActivity('Super Smash Bros. Ultimate', {type: "PLAYING"});
})

bot.on('message', msg =>{
    var cont = msg.content.slice(PREFIX.length).split(" ");
    var args = cont.slice(1);
    const serverQueue = queue.get(msg.guild.id);
    if(!msg.content.startsWith(PREFIX)) return;

    var cmd = bot.commands.get(cont[0])
    if(cmd) cmd.run(bot, msg, args);
    

    }

)```
#

there fixed

earnest phoenix
#

i'm trying to make a windows forms, visual studio 2017, c# text editor and i need to know if a file was opened with the program or the program got opened normally

swift topaz
#

i think it happened when i renamed one of my command handles and automatically updated stuff, but I already deleted that. I also checked my package.json if the main file has been changed but it hasn't

#

I really have no idea how to fix it this time

hollow saddle
#

That code makes me wanna die

swift topaz
#

same

earnest phoenix
hollow saddle
#

Why are you logging in with your play function

swift topaz
#

but I'm gonna refactor once I get my bot running again

hollow saddle
#

And do you have a message event in every file

swift topaz
#

yes I do

hollow saddle
#

Ok no

high lava
#

@earnest phoenix That's literally nothing

hollow saddle
#

you don't need a message event in every file

#

Just call the message object from your run function

#

what even is the problem viciou

#

you never said it lol

swift topaz
#

oh yeah I accidentllay removed it

#

accidentally*

#

anyway my main problem is it won't go through the bot.on('ready)

earnest phoenix
#

@high lava i know

#

how do i make it something

swift topaz
#

@hollow saddle

high lava
earnest phoenix
#

thank you

hollow saddle
#

How is it not going through

#

Errors?

high lava
#

ye

swift topaz
#

No errors actually

#

It just won't

#
4 commands found.
Command greet.js loading...
Command info.js loading...
Command skip.js loading...
Command stop.js loading...
PS C:\Users\Viciou\Downloads\Files\_Discord Bots\Smash PH Music Bot>```
#

that's it

#

I just console.logged if the .js files in my commands folder are read

hollow saddle
#
bot.on('ready', msg =>{
    console.log('Jigglypuff is online.');
    bot.user.setActivity('Super Smash Bros. Ultimate', {type: "PLAYING"});
})
``` why are you using msg
#

ready doesn't take any params iirc

high lava
#

What the

swift topaz
#

well, before I deleted my play.js, it worked

high lava
#

You don't need to use Type

hollow saddle
#

Playing is default yeah

#

It's because you have the client login in your play function

#

That literally gives me an anerism

#

If I could spell

swift topaz
#
function play(guild, song){
    const serverQueue = queue.get(guild.id);

    if(!song){
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
    }

    console.log(serverQueue.songs);

    const dispatcher = connection.playStream(ytdl(song.url, {filter : 'audioonly'}))
    .on('end', () => {
        console.log('Song ended');
        serverQueue.songs.shift();
        play(guild, serverQueue.songs[0])
    })
    .on('error', error =>{
        console.error(error);
    });

    
dispatcher.setVolumeLogarithmic(5 /5);

msg.channel.send(`Puff, puff puff! (Now playing: ${songInfo.title}!)`);

}```
#

it's not, though. this is my play function

hollow saddle
#

I saw it up above

#

Just hastebin your while index.js

#

*whole

swift topaz
hollow saddle
#

Your login is inside your second message event

#

You don't need 2 message events

#
48: bot.on('message', async msg =>{

133: bot.login(token)

136: )}
#

Take bot.login out of that messag eevnt

#

And if you have a command handler why aren't you using it

high lava
swift topaz
#

@hollow saddle still kind of confused with parameter passing from the index.js' function if I call it to my command handler

high lava
#

you have that

#

so

#

One sec

#
        run: async (bot, msg, args) => {
                ...
        },
};```
#

your actual code will look like that in your command file

#

And whatever you run goes in the brackets

hollow saddle
#

You can either bind the function to the client

bot.play = (params) => {

Or export it then require the file

// index.js
module.exports = play(params);

// play.js
const play = require('../index.js')

If my logic serves me right

#

Yes

#

Not 50 million message events

#

Only one is needed to capture the message object

swift topaz
#

All right I fixed that part now thanks!

#

and on another hand,

#
const ytdl = require('ytdl-core')
const index = require('../index.js')
module.exports.run = async (bot, msg, args, queue, serverQueue) => {
    const voiceChannel = msg.member.voiceChannel;

        if (!voiceChannel) return msg.channel.send("Puff! (I need to be in a voice channel to sing!)");
        
        const songInfo = await ytdl.getInfo(args[0]);
        const song = {
            title: songInfo.title,
            url: songInfo.url
        };

        if(!serverQueue) {
            const queueConstruct = {
                textChannel: msg.channel,
                voiceChannel: voiceChannel,
                connection: null,
                songs: [],
                volume: 5,
                playing: true
            };
            queue.set(msg.guild.id, queueConstruct);

            queueConstruct.songs.push(song);

            try{
                var connection = await voiceChannel.join();
                queueConstruct.connection = connection;
                index.play(msg.guild, queueConstruct.songs[0]);

            }   catch (error) {
                queue.delete(msg.guild.id);
                msg.channel.send(`I could not join the voice channel.`)
            }
        } else {
            serverQueue.songs.push(song);
            console.log(serverQueue.songs);
            return msg.channel.send(`${song.title} has been added to the queue!`);
        }
        }


module.exports.config = {
    command: 'play'
}```
#

msg.channel.send(`I could not join the voice channel.`) it always goes inside this catch block

hollow saddle
#

The catch block catches any error from the try block

#

I'm guessing it originates from your play function again since I saw that you used msg in there

#

So add a new param called msg

#

so

function play(msg, guild, song)

Or just

since you can grab the guild from the message object with msg.guild

#

Not to mention that you call the play function inside of itself

#

Which would definietly throw an error

#

Which is why it's throwing the catch block

swift topaz
#

I think I got it only with one problem

#

if I do this index.play(params), it gives me TypeError: index.play is not a function

while if I only use play(params) it gives me ReferenceError: play is not defined

#

note that I imported my index.js const index = require('../index.js')

#

@hollow saddle

earnest phoenix
#

maybe play isn't an exported function in index.js

#

Try adding it to module.exports

swift topaz
#

module.exports inside the index.js? or my .js file inside my commands folder?

earnest phoenix
#

in ur index.js

hollow saddle
#

You have to export it from index.js using module.exports

#

In index.js yeah

earnest phoenix
#

Thank you for repeating that

hollow saddle
#

I was agreeing with you saying that's what viciou needs to do bloblul

swift topaz
#

and then put this in my whatevercommand.js
const index = require('../index.js')(guild, song)? or shall I remove the parameters of the play functions beside the index.js?

hollow saddle
#

Remove the params

#

And then use index.play(params)

#

And you need to add an msg param since you call msg.channel.send in your play function

#

Replace it with guild since you can get the guild with msg.guild

swift topaz
#

replace what param with guild?

hollow saddle
#

msg

swift topaz
#

yeah that's what I did

hollow saddle
#

Replace guild with msg

#

Not the other way around

#

Use msg, not guild

#

For the param

swift topaz
#

ohhhh

hollow saddle
#

Yeah lol

#

Then if you need the guild use msg.guild

swift topaz
#

I get this though ReferenceError: msg is not defined

#
function play(msg, song){
    const serverQueue = queue.get(msg.guild.id);
    
    if(!song){
        serverQueue.voiceChannel.leave();
        queue.delete(msg.guild.id);
        return;
    }

    console.log(serverQueue.songs);

    const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
        .on('end', () => {
            console.log('song ended');
            serverQueue.songs.shift();
            play(guild, serverQueue.songs[0]);
        })
        .on('error', () => {
            console.error(error);
        });
    dispatcher.setVolumeLogarithmic(5 / 5);
}``` here's the function in my `index.js`
hollow saddle
#

Wait so msg wasn't in the play command bloblul

swift topaz
#

yeah...

hollow saddle
#

God I guess your indentation fucked me up in the pastebin

swift topaz
#

yup sorry

hollow saddle
#

Alright fine keep guild but don't call the play function inside of itself

#

lol no probkem

swift topaz
#

well this is where I use the play function, inside my play.js

module.exports.run = async (bot, msg, args, queue, serverQueue) => {
    const voiceChannel = msg.member.voiceChannel;
    if(!voiceChannel) return msg.channel.send(`not vc`);

    const songInfo = await ytdl.getInfo(args[0]);
    const song = {
        title: songInfo.title,
        url: songInfo.video_url
    };

    if(!serverQueue) {
        const queueConstruct = {
            textChannel: msg.channel,
            voiceChannel: voiceChannel,
            connection: null,
            songs: [],
            volume: 5,
            playing: true
        };
    queue.set(msg.guild.id, queueConstruct);

    queueConstruct.songs.push(song);
    try {
        var connection = await voiceChannel.join();
        queueConstruct.connection = connection;
        index.play(msg.guild, queueConstruct.songs[0]); //<--------
    } catch (error) {
        console.error(error);
        queue.delete(msg.guild.id);
        return msg.channel.send(`${error}`);
        }
    
    } else {
        serverQueue.songs.push(song);
        console.log(serverQueue.songs);
        msg.channel.send(`${song.title} added to queue.`);

    }

    return undefined;```
hollow saddle
#

Which is fine (apart from returning undefined. You should just use return; instead of retruning undefined) but I was talking about this

// in play function
    const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
        .on('end', () => {
            console.log('song ended');
            serverQueue.songs.shift();
            play(guild, serverQueue.songs[0]); <==========================
#

You call the play function inside of itself

swift topaz
#

but won't I need to recursive if I want the next song to play again after the current song is playing has ended?

hollow saddle
#

Sure but you can put it in a loop

#

Calling a function inside of itself doesn't work as far as I know

swift topaz
#

well it worked on the tutorial I was trying to follow, our only difference is I'm using command handlers, while he's not. that's why I'm having problems

#

I'm practicing command handlers too

#

and for another reason, `const serverQueue = queue.get(msg.guild.id);
^

TypeError: Cannot read property 'guild' of undefined`

hollow saddle
#

Did you replace guild with msg or flipped it back

swift topaz
#

yeah I did

hollow saddle
#

So only use guild.id there then since msg is no longer passed as a param

swift topaz
#

if I also add a parameter to my module.exports, it goes like this:``` module.exports = exports = play(msg, song);
^

ReferenceError: msg is not defined```

hollow saddle
#

uhhh that's not how you export a function

swift topaz
#

damn stackoverflow baited me

hollow saddle
#
module.exports = play(guild, song)
#

That's what you want

inner jewel
#

what is that even supposed to do

swift topaz
#

so shall I use (msg, song) instead?

inner jewel
#

a module per guild and song?

swift topaz
#

nope those are params for the play() function

inner jewel
#

then why are you calling it

swift topaz
#

so it must only be module.exports = play()?

inner jewel
#

no

#

you're still calling the function

swift topaz
#

yes I want to pass that function into my other .js file

inner jewel
#

then pass the function

#

don't call it

#

you're passing the value returned by the play function if called without arguments

swift topaz
#

they said I should do module.exports inside my index.js file, where the play function resides, and use index.play(params) inside my play.js (command) file

hollow saddle
#

Well uhh I just realized how much of a massive idiot i am and how big of a brainfart I had

tranquil drum
#

are embeds sent the same way as raw text?

swift topaz
#

nah dude I'm the idiot one for not knowing how to use these shits

hollow saddle
#

In index.js you can do

module.exports.play = play;

which exports the function

And in play.js you can do

const index = require('../index.js')

index.play(guild, song)

Or you can just put the entire play function in your play.js file and not have to worry about exporting it if you only need it for that file

#

My brain forgot how node works bloblul

peak quail
#
const Discord = require("discord.js");
const botconfig = require("../../config.json")


module.exports = {
  config: {
      name: "addrole-*",
      Description: "Fügt jeden User eine rolle hinzu",
      accessableby: "ADMIN",
      aliases: ["addrole*"]
      
  },
  run: async (bot, message, args) => {

    var guild = message.guild;
  
    // Get role ID
 const match = /(?:\s+([\s\S]+))/.exec(message.content);
 if (!match) return message.reply("Invalid role given");
 
 // Retrieve role 
 let role;
 role = message.guild.roles.get(match[1]);
 if (!role) role = message.guild.roles.find(r => r.name === match[1]);
 if (!role) return message.reply(`No role found with a name or ID matching the input: \`${match[1]}\``);
 
   var members = await guild.fetchMembers();
   let i = 1;
       
   // _______________________________HERE I NEED HELP________________________________________________________
   for (let m of guild.members.values()) {
     console.log("Doing", i++, "/", guild.members.size);
     if (m.roles.has(role)) continue;
     await m.removeRole(role);
    
     if (i % 5 == 0) {
      const wait = t => new Promise(r => setTimeout(r, t));
       if(i == 1) message.channel.send(`_ _`).then( msg =>{
        setTimeout(() => {
            msg.edit(`rolle hinzugefügt an ${i} von ${guild.members.size}`);
          }, 4400);
        } )
      await wait(5550) // 5 second of waiting

       }
     
   }

  }} 
//__________________________________________________________________________________________

can you guys pls help me ... i m trying to send a message and then edit it every 4,5s too the var i or i++ i don´t now if its difficult
😒

hollow saddle
#

That would be API spam bro

peak quail
#

await wait(5550) // 5 second of waiting

hollow saddle
#

Still spamming the api to edit a message every 5 seconds

peak quail
#

hmmm

tranquil drum
#

why not wait(5000)

peak quail
#

ok

#

then that

tranquil drum
#

i mean still api abuse lol

peak quail
#

lol

#

1000000000000000000ms?

#

xd

swift topaz
#

@hollow saddle yeahh... about that I still get ReferenceError: guild is not defined

hollow saddle
#

Are you using msg as a param or guild

swift topaz
#

uhhh guild

#

same happens when I use msg

tranquil drum
#

anyone know if i can send the embed payload on the sendmessage action with JDA?

hollow saddle
#

Ok but you need to get the guild object which can be done using msg.guild so

// in play.js
index.play(msg.guild, song)
tranquil drum
#

nvm got it

swift topaz
#

yep it's currently that index.play(msg.guild, queueConstruct.songs[0]);

hollow saddle
#

Where is the error being thrown from

swift topaz
#

for some reason it won't join the voice channel so I dunno where to even start anymore

#

holy fucking crap

#

even the error is getting an error

#

what monstrosity is this

marsh oar
#

Hello I made a command to be able to send random images with a random image link and unfortunately the code does not work

west spoke
#

then fix it

#

]]ask2ask

marsh oar
#

I do not know how to see that I know nothing in development

west spoke
#

then learn the language.

marsh oar
#

Discord.js

west spoke
#

I said learn the language

#

Image api isnt that hard

#

As long as you use the right one (eg, mine for anime/nekos) you will be fine

marsh oar
#

I tried and I can not do it

west spoke
#

Then keep trying

#

We dont know the api you are using to draw the image

#

Or any errors

#

So we can't help you

earnest phoenix
maiden mauve
#

question: if I update Heroku server via Git am I exposing my token?

#

(git repository)

west spoke
#

Only if the repo is public

late hill
#

Heroku's repositories are private

maiden mauve
#

maybe use config vars on heroku just to be safe?

swift topaz
#

@hollow saddle ok so it works. thanks! only problem is that it won't queue another song and whenever I tried to command play another song, the bot disconnects

#

ReferenceError: songInfo is not defined

west spoke
#

Define songInfo

swift topaz
#
    const song = {
        title: songInfo.title,
        url: songInfo.video_url
    };```
#

it plays though

earnest phoenix
#

@west spoke it is is it not

#

wait it is

#

:C

west spoke
#

What you are trying to do is await.title?

swift topaz
#

more like something like this msg.channel.send(${song.title} added to queue.);

#

msg.channel.send(`${song.title} added to queue.`); *

wheat jolt
#

@swift topaz then do directly songInfo.title

swift topaz
#

@wheat jolt i still get it ReferenceError: songInfo is not defined

wheat jolt
#

can you give me a screenshot of your code?

#

or just

sometext
swift topaz
#
bot.on('message', async msg =>{
    
    if(msg.author.bot) return undefined;
    if(!msg.content.startsWith(PREFIX)) return undefined;
    const args = msg.content.split(' ')
    const serverQueue = queue.get(msg.guild.id);
    if(msg.content.startsWith(`${PREFIX}play`))
    {
        const voiceChannel = msg.member.voiceChannel;
    if(!voiceChannel) return msg.channel.send(`not vc`);

    const songInfo = await ytdl.getInfo(args[1]);
    const song = {
        title: songInfo.title,
        url: songInfo.video_url
    };

    if(!serverQueue) {
        const queueConstruct = {
            textChannel: msg.channel,
            voiceChannel: voiceChannel,
            connection: null,
            songs: [],
            volume: 5,
            playing: true
        };
    queue.set(msg.guild.id, queueConstruct);

    queueConstruct.songs.push(song);
    try {
        var connection = await voiceChannel.join();
        queueConstruct.connection = connection;
        play(msg.guild, queueConstruct.songs[0]);
    } catch (error) {
        console.error(error);
        queue.delete(msg.guild.id);
        return msg.channel.send(`${error}`);
        }
    
    } else {
        serverQueue.songs.push(song);
        console.log(serverQueue.songs);
        msg.channel.send(`${songInfo.title} added to queue.`);

    }

    return;
}``` and...
#

function play(guild, song){
    const serverQueue = queue.get(guild.id);

    if(!song){
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
    }

    console.log(serverQueue.songs);

    const dispatcher = connection.playStream(ytdl(song.url, {filter : 'audioonly'}))
    .on('end', () => {
        console.log('Song ended');
        serverQueue.songs.shift();
        play(guild, serverQueue.songs[0])
    })
    .on('error', error =>{
        console.error(error);
    });

    
dispatcher.setVolumeLogarithmic(5 /5);

msg.channel.send(` (Now playing: ${songInfo.title}!)`);

}```
twilit rapids
#

@wheat jolt there is more info provided than that. Look at the line which the error occurred

#

From looking at your code I can already see which line it is

swift topaz
#

It doesn't also go inside the queue

#

where is it?

twilit rapids
#

msg.channel.send(` (Now playing: ${songInfo.title}!)`);

#

Nearly the last line

#

Oh lmao sorry for the wrong ping Alex

swift topaz
#

any insights what's wrong with that part?

twilit rapids
#

You defined songInfo outside of the function, and then didn't re-defined it in your function

wheat jolt
#

before if(msg.content.startsWith(`${PREFIX}play`)) you need to put: let songInfo and change change const songInfo = await ytdl.getInfo(args[1]); to songInfo = await ytdl.getInfo(args[1])

twilit rapids
#

You did push it to your song array as song.title

#

so use song.title instead of songInfo.title

swift topaz
#

when I did both of your changes, the bot won't even join the voice channel anymore

wheat jolt
#

what

swift topaz
#

my other problem that I luckily saw was, I had 2 play functions

#

one inside the bot.on, one outside

#

I removed the one inside the bot.on

#

then retained the one outside

#

I guess that's what caused the bot to not run

#

yeah nope

#

what I said was stupid

wheat jolt
swift topaz
#

msg.channel.send((Now playing: ${song.title}!));

#

I changed it now

#

I don't know where's the incorrect part anymore

#

nvm it works now

earnest phoenix
#

@swift topaz send the error

#

How do I solve the problem that when my bot is playing music and I get kicked out of the call it happens that I have to relinquish it as I solve it?

swift topaz
#

it's working as intended now actually. all I'm debugging right now is it won't play the next song in the queue @earnest phoenix

earnest phoenix
#

for the reason that no command works after i do that

#

@swift topaz Okay didn't see the message after.

swift topaz
#

andyeah I don

#

't get why it won't play the next song

earnest phoenix
#

Send code.

#

Can someone help me?

#

@earnest phoenix I don't understand what you're asking

swift topaz
#
const ytdl = require('ytdl-core')
const index = require('../index.js')

module.exports.run = async (bot, msg, args, queue, serverQueue) => {
    const voiceChannel = msg.member.voiceChannel;
    if(!voiceChannel) return msg.channel.send(`not vc`);

    const songInfo = await ytdl.getInfo(args[0]);
    const song = {
        title: songInfo.title,
        url: songInfo.video_url
    };

    if(!serverQueue) {
        const queueConstruct = {
            textChannel: msg.channel,
            voiceChannel: voiceChannel,
            connection: null,
            songs: [],
            volume: 5,
            playing: true
        };
    queue.set(msg.guild.id, queueConstruct);

    queueConstruct.songs.push(song);
    try {
        var connection = await voiceChannel.join();
        queueConstruct.connection = connection;
        index.play(msg, msg.guild, queueConstruct.songs[0]);
    } catch (error) {
        console.error(error);
        queue.delete(msg.guild.id);
        return msg.channel.send(`${error}`);
        }
    
    } else {
        serverQueue.songs.push(song);
        console.log(serverQueue.songs);
        msg.channel.send(`${song.title} added to queue.`);

    }

    return;
//current problem: won't play the next song
    
}

module.exports.config = {
    command: 'play23'
}    ```

filename: play.js
#
function play(msg, guild, song){
    const serverQueue = queue.get(guild.id);
    
    if(!song){
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id);
        return;
    }

    console.log(serverQueue.songs);

    const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
        .on('end', () => {
            console.log('song ended');
            serverQueue.songs.shift();
            play(msg, guild, serverQueue.songs[0]);
        })
        .on('error', () => {
            console.error(error);
        });
    dispatcher.setVolumeLogarithmic(5 / 5);
    msg.channel.send(`(Now playing: ${song.title}!)`);
}

this is inside my index.js

earnest phoenix
#

like I have a music command later I put a song when I kick the call bot without the command to leave the api it doesn't work and I have to resign it like he doesn't give more command

#

Can you use proper grammar

#

Where is queue defined the function?

swift topaz
#

queue is a Map

#

it's inside my index.js too

#

the queue works

#

but it won't play

earnest phoenix
#

Oh

#

Let me get on laptop to have better look

swift topaz
#

sure sure

#

oh wait lemme update my code above

earnest phoenix
#

where are you calling play?

swift topaz
#

I call it inside the play.js

earnest phoenix
#

Okay i see, play takes the 3 params

swift topaz
#

yes

#

here, it adds the second music to the queue, and states that it's playing it, but it doesn't have sound

robust quiver
#

hello guys i need help
how the bot can read a msg in DM
i made my own bot but i don't know the location of the DM how it calls
i know that general chat in sublime called message.channel but i don't know the DM what called

swift topaz
#

it's either it has no sound or is not playing

#

but there is green outline around my bot

pale marsh
#

@robust quiver DM's are treated like channels as well

#

But the channel type is DM. Check the docs of the library you're using for channel type

earnest phoenix
#
[client].on("message", async message => {
    if(message.channel.type === "dm"){
        //code
    }
})
robust quiver
#

message.channel ??? @pale marsh

swift topaz
#

yep there isn't any sounds is the problem, cuz in my console log, it said that the song has ended

pale marsh
#

Yes

robust quiver
#

okey thanks

swift topaz
#

oh it works now @earnest phoenix

#

for some reason, changing setVolumeLogarithmic to setVolume fixed it

#

I still am confused with what setVolumeLogarithmic does

gray epoch
#

@earnest phoenix hey how can i set awaitmessage from dm

earnest phoenix
#

?

#

@swift topaz So it was playing just no volume ?

swift topaz
#

yes it is

gray epoch
#

@earnest phoenix like i wanna make a ban command that the bot get confirmation from server owner in dm and this is where i stoped

await bot.users.get(serverowner).send(`<@${message.author.id}> want to ban <@${target}>.\nDo you accept this?\`\`(y/n)\`\``);
     message.channel.send(`Waiting for confirmation from the server owner (<@${serverowner}>).`);
      const msgs = await .awaitMessages(res => res.author.id === serverowner, {
      max: 1,
      time: 86400000
      });
earnest phoenix
#

Um...

gray epoch
#

i was blocked

earnest phoenix
#

?

unique nimbus
#

why do you want the server owner to accept?

#

like most bots allows people who is admins to use ban

#

or ban members

gray epoch
#

its only for me for my server i don't wanna anyone to get banned only when i confirm that

#

@earnest phoenix
msgs = await ?.awaitmessages....

earnest phoenix
#

Hold up

opaque eagle
#

What's the point of trusting admins with BAN_MEMBERS perms if they need to go through you

earnest phoenix
#

@gray epoch I don't know exactly how but maybe

let owner = client.users.get('ownerid');
    owner.createDM().then(async dm => {
        console.log(dm)
        dm.send('Hey')
    }).catch(err => console.log(err))
opaque eagle
#

If it's a message, you could just do message.guild.owner.send("Do u want to ban x?")

gray epoch
#

@opaque eagle its personal

#

@earnest phoenix thank you for your help

earnest phoenix
#

👍

opaque eagle
#

Uhh

#

why make the .then() function async if ur not using async/await @earnest phoenix

earnest phoenix
#

awaitMessages()

opaque eagle
#

oh ok

shy rose
#

as a general question to anyone who has a multilingual bot
how do you actually determine use x language on x server
or is it a manual (in bots native language) first step in order to set it up for the server owner

warm marsh
#

You have to code it yourself.

#

People probably store the data inside a database with the guild id that has a chosen language.

shy rose
#

i mean know how to make it

but whats the onboard method normally look like is more the issue

valid frigate
#

internationalization

#

basically make a dir full of json files that translate each string, and in your code you would use something like
translate(StringNameHere, guild/user language)

shy rose
#

i know how to make it thats not the issue ive done it plenty before for web sites

@valid frigate question is how do they set it up

#

like how can you tell a server owner change the language to german if your bot is in english and they dont know it

valid frigate
#

ohhh

#

uh

shy rose
#

hence whats the onboarding normally look like

valid frigate
#

make the help command respond to help in multiple languages, and at the bottom maybe put in every language you provide "to change bot language, type lang something

#

since a lot of people type help first

shy rose
#

so have the word "help" in each language and go from that?

valid frigate
#

if you have like command aliases

#

yeah

shy rose
#

makes sense thanks
seems a really clean way of onboarding

valid frigate
#

gl mmulu

shy rose
#

internalisation usually isnt that bad done it plenty
normally people have a request language tag though in web

tranquil drum
#

you could also default to the guild region @shy rose

earnest phoenix
#

voice regions aren't country specific

fading wigeon
#

they are

earnest phoenix
#

they're located in a country

fading wigeon
#

yes

earnest phoenix
#

however they don't define which language the guild will use

fading wigeon
#

bruh its english

#

everywhere

earnest phoenix
#

i hope you're aware a region has multiple countries which have their own language

fading wigeon
#

yeah EU west is hosted in frankfurt

#

just like everything else

valid frigate
#

imagine being in the uk and having your bot speak german

fading wigeon
#

Lmao

#

Its happening again

earnest phoenix
#

@earnest phoenix , no, it doesn't

fading wigeon
#

yes

#

text gets routed thru the voice servers to the main server

earnest phoenix
#

what you're thinking about is all client, the server doesn't do anything, dragon

#

the method of checking the language in channel names is very unreliable

#

tldr don't automatically switch the language for your bot

#

i went over this, you can't use regions to set the language automatically

#

that ^

#

or set default to english and note it can be changed

shy rose
#

if they dont speak the language then they wouldnt understand its saying set the language and discard it as some welcome message

also choosing a channel to send that in is a whole nother problem in it self

#

think the Multilanguage help command as suggested above is the most seemless way in

earnest phoenix
#

if they're on an english page with a bot description that's in english, they're aware the bot is in english when they invite it

#

ergo they can read comprehensible english

shy rose
#

chrome auto translate pages
or just being sent the direct invite link by a friend

earnest phoenix
#

at that point it's not your problem

#

user's fault

shy rose
#

the user is the fault for most issues tbh

like unticking all the permissions you ask for then instantly complaining it cant do the features listed

snow urchin
#

Why does a value of something in quick.db, show as object promise, when in an embed

warm marsh
#

await db.fetch()

#

it's a promise meaning you have to use .then or await

snow urchin
#

oh ok

#

thanks

warm marsh
#

Np.

#
db.fetch('..').then(data => //do somethin');

async function run(){
    let data = await db.fetch('..');
}```
#

Just incase

snow urchin
#

right, got another oofing problem owo

warm marsh
#

Alright, Fire away.

snow urchin
#

code:

const discord = require("discord.js");
const db = require("quick.db");
const fs = require("fs");

module.exports.run = async (client, message, args) => {
  const lb = new discord.RichEmbed();
  let lb2 = new discord.RichEmbed();
  let jso = JSON.parse(fs.readFileSync(__dirname + "/djinfo.json", "utf8"));
  let ba;
  let djs = jso.djs1;
  let djs2 = jso.djs2;
  let boked = jso.bookedaway;
  lb.setAuthor("This weeks booked slots.");
  message.channel.send("**Loading...** This will take some time!");
  djs.some(async dj => {
    let ba;

    boked.some(d => {
      if (dj === d) {
        ba = " - BA";
      } else {
        ba = "";
      }
    });

    let bookedtt = await db.fetch(`bookedshit_${dj}`);
    let slota;
    message.channel.send(bookedtt);
    if (bookedtt === "null") {
      slota = "0";
    } else {
      slota = bookedtt;
    }
    lb.addField(client.users.get(dj).tag + ba, slota);
  });

  djs2.some(async dj => {
    let ba;

    boked.some(d => {
      if (dj === d) {
        ba = " - BA";
      } else {
        ba = "";
      }
    });

    let bookedtt = await db.fetch(`bookedshit_${dj}`);
    let slota;
    if (bookedtt === "null") {
      slota = "0";
    } else {
      slota = bookedtt;
    }
    lb2.addField(client.users.get(dj).tag + ba, slota);
  });
  await message.channel.send(lb);
  await message.channel.send(lb2);
};

output:

#

its prob smth obvious I am missing

shy rose
#

whats it meant to do?

warm marsh
#

What's the value supposed to be.

snow urchin
#

there is like 20 ids in an array, its meant to do it for, and meant to be in one embed

#

the only difference I made is the await on db.fetch

shy rose
#

your not waiting for the .some to complete

#

also why use a .some?

#

looks like a .forEach is more relevant

#

*or even a .map then you can Promise.all it

snow urchin
#

How would I go about doing that then

warm marsh
#

Rewrite

#

Kidding

snow urchin
#

owo

shy rose
valid frigate
#

async/await better

earnest phoenix
#

anyone opinions on a good database to use for storage in node.js? needs to be
-Fast
-Able to handle requests from multiple processes at once
-Able to store javascript objects (i dont care if its in JSON or something else as long as it works)
(Ping me if u answer)

tight heath
#

mongo

west spoke
#

json

tight heath
sick cloud
#

@earnest phoenix mongo or rethink are your best options, rethink is great at multiple connections and sharding

west spoke
#

Yes shoot me harder ravy

tight heath
#

Rethink is ded

#

Use mongo

#

Goodnight

valid frigate
#

does Client.channels.fetch get a channel even if the client never saw/can see that channel

hollow saddle
#

Mongo

valid frigate
#

low key

hollow saddle
#

All the way

#

I think it's only the channels that it has access to

#

Maybe

valid frigate
#

id assume that yeah

hollow saddle
#

Not entirely sure though

tight heath
#

There is no fetch iirc

valid frigate
#

if cache is false would it do otherwise

tight heath
#

All channels are cached in djs aren't they?

valid frigate
#

there

#

if i turned this off would it be able to fetch another channel mmulu

tight heath
#

Oh huh

valid frigate
#

havent tested it, but my bot is offline

topaz fjord
#

Mongo is best

wild tide
prime cliff
#

@wild tide it does have a class left-container and you can use this to select certain elements

.left-container p:nth-child(1) {
    
}```
wild tide
#

yea, I just figured it out before after a quick google search, thanks for the confirmation!

scarlet phoenix
#

Anyone ever seen a scenario when a bot doesnt send voice data? (Kotlin/JDA/Lavaplayer) But running the code locally works, just on scaleway it doesnt

prime cliff
#

Some voice servers can have issues try switching the server region and see if that fixes it

scarlet phoenix
#

it doesnt seem to be tied to a specific server. I have gotten reports from ~10 different users across regions. Running locally it works. I just switched hosts to scaleway yesterday and it worked up until about an hour ago Thonk

#

Also not getting datadog updates

#

This is odd

sick cloud
#

blocked ports maybe?

scarlet phoenix
#

Maybe but for about the last 24 hrs it worked fine, but randomly (no reboots or shard disconnects) it seemed to stop wanting to talk to some stuff

#

I am going to just restart all of the pods

#

reboot didnt help. Why does this have to happen right when I want to go to sleep

valid frigate
#

does shardReady emit on every client when a shard becomes ready

#

smh

#

or just that client*

scarlet phoenix
#

Recreating all of the pods in new VPS instances worked. I need to just make a shell script for that...

earnest phoenix
#

Is it possible to send an embed as a Discord user without using any code?

mossy vine
#

no

earnest phoenix
#

Its possible with code right? Because I did it once.

#

yes, but you're not allowed to login with a user token outside of the official client

mossy vine
#

wait so if you execute the embed sending code in the discord client dev tools its ok? MegaThonk

sick cloud
#

maybe you could send json and just make it parse it bloblamp

earnest phoenix
#
[object Cyber]Today at 9:36 AM
wait so if you execute the embed sending code in the discord client dev tools its ok? :MegaThonk:```

theoretically, yes and no
#

how does an embed look like in JSON?

#

like json

#

you'd be modifying the client which would be breaking another TOS rule, but it would circumvent the rule of the user token @mossy vine

mossy vine
#

right

earnest phoenix
#

lol ok

sick cloud
#
{
    "title": "hi",
    ...
}```
#

overly simple

earnest phoenix
#

i dont get why they just wouldnt disallow sending rich embeds for users overall api side instead of allowing you to send one but hunting you down for it

sick cloud
#

then people will abuse it

#

embeds are for bots only

#

and if you disabled it api side that just causes issues for them

earnest phoenix
#

wat

#

you... are aware that in the auth headers you define which type the token is

#

which is how some endpoints are available for users and not for bots

#

im saying they should ignore rich embeds or return a 400 if a user token sends a message with a rich embed

bright spear
#

@earnest phoenix link previews are the same thing

#

which is why they were implemented in the first place

earnest phoenix
#

link previews arent rich embeds

bright spear
#

yeah they are

earnest phoenix
#

attempt to add fields with a link preview yourself

bright spear
#

thats why the same "embed links" permissions applies to both of them

earnest phoenix
#

fields in youtube/steam links are done discord side

bright spear
#

some link previews are custom and have stuff like fields and footers

#

its the same embed system though

slender thistle
earnest phoenix
#

despite that, link previews work in a way where the message is first sent, then checked for links, links are checked for opengraph metatags and then a MESSAGE_UPDATE is sent saying that the message has proper link preview

#

which means it's being done server side

tranquil drum
#

maybe theyre keeping it open for future implementation

#

or they just don't want servers to waste resources on logic that trivial

earnest phoenix
#

it's really not resource wasting* at all

#

it's a simple if check

tranquil drum
#

bruh when you have 11 million concurrent users thats resourceful

#

like if you can remove that condition it probably saves at least a little

earnest phoenix
#

that's like saying the bulk delete endpoint is heavy because it has a check to see whether the token is a user one

#

it's a bad point for an argument

#

despite that, even if it wasted resources, they would be saving database space

#

so it would pay off

tranquil drum
#

wait what

#

you cant bulk delete with a bot?

earnest phoenix
#

you can

#

you can't bulk delete with a user token

tranquil drum
#

ohh

#

i guess my counter point would be that that's a bot facing endpoint which probably has way less concurrent clients

storm grail
#

hey im having a thought block on how to do a user mute for X amount of time

#

im using .NET and right now you can mute users in text channels but you have to unmute them

#

how would you setup a timed mute. I dont really want to call a database every second to see if a user needs to be unmuted

earnest phoenix
#

mute, offload a Task.Delay to another thread, pass an unmute method to ContinueWith on Task.Delay

storm grail
#

oh i never thought about using Task.Delay

#

genius

earnest phoenix
#

e.g

public async Task Mute()
{
    //your stuff here
    _ = Task.Delay(ms).ContinueWith(_ => { your unmute stuff here});
}
storm grail
#

so what I'd mute the user then call another async Task that has a delay of the required amount and once the delay is up it calls the unmute function

#

whats the continueWith for though

earnest phoenix
#

isn't it self explanatory

storm grail
#

can i not just stick the unmute call underneath

earnest phoenix
#

well, no

storm grail
#

yeah im just wondering why use lin

#

q

earnest phoenix
#

that isn't linq

storm grail
#

:O

#

¯_(ツ)_/¯

earnest phoenix
#

the task.delay above is being offloaded into another thread, meaning it won't block the method and hang it, instead it will return

#

the task.delay will be queued in another thread, ContinueWith is telling it what to do after the delay is done

storm grail
#

ah alright

#

so i shouldnt await the function call

earnest phoenix
#

which? Task.Delay? you shouldn't

storm grail
#

as in if I were to call that Mute function

earnest phoenix
#

you can await that

storm grail
#

oh i thought it would block it

#

sorry for all the questions just one more thing

#

_ = Task.Delay(ms).ContinueWith(_ => { your unmute stuff here});

#

why do you set it equal to an underscore

#

well why do you set it to any variable for that matter

earnest phoenix
#

it's a discard, it's telling visual studio not to complain about it not being awaited in this case

storm grail
#

ah so thats why i can await the function

earnest phoenix
#

yup

storm grail
#

alright thanks thats really helpful

#

back to work!

pallid zinc
#

Which API is best for YouTube video notification

mossy vine
#

youtube api

pallid zinc
#

I think YouTube API do not have notification think

earnest phoenix
#

google's official yt data api does have push notifications

tulip wave
#

I think he means API wrapper maybe?

pallid zinc
#

Cry is right

#

My English is rip

earnest phoenix
#

from what i'm reading it works like webhooks

mossy vine
#

isnt it the same fucked up notification system users have access to?

#

wouldnt it be better to just parse the channels page for new content every x minutes

earnest phoenix
#

probably

tulip wave
#

Most likely

earnest phoenix
#

google is very dumb when it comes to realtime

tulip wave
#

Not dumb

#

Just bad

earnest phoenix
#

multiple people have called them out for using bad methods on twatter

pallid zinc
#

I just don't want to add webhook

#

I want my bot to do it

earnest phoenix
#

it's not a discord webhook

pallid zinc
#

YouTube webhook

#

??

#

Lol

earnest phoenix
#

your vps will act like a server which receives webhook requests, you can then pipe those through your bot

tulip wave
#

^

pallid zinc
#

Ohh

#

Thansk

#

Thanks

tulip wave
#

It's the only way you can actually get the data

#

Unless you wanna request the data yourself and stuff which would be very inefficient

mossy vine
#

so im experimenting with fs.watch() a bit, and when i modify a file the callback fires 4 times (rename, change, rename, rename) and doesnt react to anything after that

#

does anyone know why that could be happening?

#

oh wait, i might be doing it completely wrong

#

nope

#

everything still fires only once

#
watch('server.js', (eventType, filename) => {
    console.log(eventType)
    if(eventType === 'change') {
        console.log('shit changed')
    }
}).on('change', (eventType, filename) => {
    console.log('shit changed')
})
#

it logs twice

#

but nothing afterwards

quartz kindle
#

On Linux and macOS systems, fs.watch() resolves the path to an inode and watches the inode. If the watched path is deleted and recreated, it is assigned a new inode. The watch will emit an event for the delete but will continue watching the original inode. Events for the new inode will not be emitted. This is expected behavior.

mossy vine
#

but im not deleting and recreating it

#

so

quartz kindle
#

are you modifying it locally or via ssh?

mossy vine
#

locally with vim

quartz kindle
#

then idk

mossy vine
#

perhaps that will help

#

yeah, node-watch works flawlessly

#
const watch = require('node-watch')

watch('server.js', (evt, name) => {
    if(evt === 'update') {
        console.log('shit changed uwu')
    }
})
small sky
abstract crow
nova rivet
#

Eris-sharder

west spoke
#

Why hide the guild ID

#

We all know its dbl

unique nimbus
#

@abstract crow me

quartz kindle
#

@small sky what did you put in the owners field?

small sky
#

nothing

#

g

abstract crow
#

@unique nimbus You have always been at the top of my DB lol

unique nimbus
#

yes

#

I always know its me

#

kek

abstract crow
#

This time it was @south moon lol

unique nimbus
#

what

#

kek

abstract crow
#

I happened to be fooling around with an API with Express.JS and I just saw how many points lol

unique nimbus
#

nice

#

idk how to make a level up system in python so i never thought of making levels

#

except maybe levels by usage

abstract crow
#

I mean for me, I just divide the level by the xp

#

needed*

#

I mean XP divided by XP needed

#

So like if I have 1k I divide it by 500xp(Since that it my level up xp) and I get level 2

unique nimbus
#

yes

viral spade
#

Hi,
what is the best solution, if you have lots of statistical server data in your database (that is read from and written to all the time). but have your bots running on different vps?
currently i use mysql on one vps that all shards connect to. But with more guilds added i need a distributed solution. Every shard only needs to hold/manipulate the respective rows for its assigned servers.
Id guess this problem is kinda common, how do people go about this?

copper crystal
#

How could I have the bot retrieve the message URL of a command?

earnest phoenix
#

Does anybody know how to make a web dashbaord? If so, please DM me some form of proof that you know what you're doing.

I am paying for somebody to start off a web dashboard on my project, you will be given credit on the bot along with PayPal payment.

tight heath
#

@viral spade probably setup a handler on that server which all shards connect to, that manages what data is written

viral spade
#

@tight heath this way the database does not scale with the shards, but will soon be the bottleneck. I am asking for a solution that reduces strain on the database.
The naive approach would be what you said, but using the remote database only as backup and loading from it only at the start of each bot.

tight heath
#

I mean my naive approach works for storing a shitload of tracks within Groovy

viral spade
#

i am making a write for every message anyone sends

#

which means you need to think about hundreds to thousands of writes per second

tight heath
#

boi we have over a million servers and need to store every track mmLol

#

also that's rather your optimization

#

why not cache some and then send in bulk

viral spade
#

The naive approach would be what you said, but using the remote database only as backup and loading from it only at the start of each bot. thats caching

tight heath
#

I'm not saying cache the whole db

#

but let's say cache all messages in a minute and then write them to db

viral spade
#

not the whole db, but all records accociated with all servers that bot has

tight heath
#

instead of writing them each 10ms

viral spade
#

i also need to access the information as often

#

so only dumping is no use. i need to have all the info accessible in the bot

tight heath
#

what are you actually doing

#

maybe explaining that helps solve the problem more efficiently

viral spade
#

sure. i do statistics, fe. count messages per day per channel per user

quartz kindle
#

mysql is designed to handle millions of queries per day, i dont think it will reach a bottle neck that easily, but yes the best thing you can do is add an in-memory cache layer

copper crystal
#

That's not what I mean @tight heath

tight heath
#

then say what you mean

copper crystal
#

When someone uses a command, I want the bot to fetch the link of the command invocation.

tight heath
#

what

#

which link

#

can you give an example

quartz kindle
#

like !get http://somewebsite?

copper crystal
#

!thisisthecommand

#

It should return the link to that message.

tight heath
#

then what I said?

quartz kindle
#

the link or the contents of the link?

copper crystal
#

The message link.

tight heath
#

you can get the rest

quartz kindle
#

then yeah what he said lol

copper crystal
#

I don't think you get what I mean.

tight heath
#

you can literally fill in the fields

#

guildID, channelID, and messageID

tight heath
#

and you get the link to the message

copper crystal
#

I want the bot to fetch the link.

tight heath
#

there is no fetching

#

that link is nowhere stored on Discord

#

you have to create it

#

using those three IDs

copper crystal
#

omg

viral spade
#

@quartz kindle
I also thought so but i am not sure because my bot really does a lot of queries. when you say millions per day i am not sure if thats enough in longterm.

  1. so whenever a message is sent by anyone in any channel, it does a read to get the old score, an increment to the databse value, then a hell lot of joins to calculate old and new level (to see if theres a levelup) . this means a dozen reads and a write for each message. For lets say 100 messages per sec, this would be over 8 million messeages per day. this would be easily 100 million reads/writes per day.

  2. Part of the bot is calculating users minutes in voicechannels. For this i rotate through all voicechannels with users, and tick them up a minute, and do this once per minute. This rotation, once per minute, puts my harddrive on very high usage for 20 seconds when using my 3k servers. This wont work with more than 10k servers (i can postpone the problem by incrasing the interval but still..).

copper crystal
#

I want the bot to automatically create it then

#

the link is obviously going to be different each time

tight heath
#

yes so you use the different IDs each time

#

it's not an invite link boi

#

it's not random

copper crystal
#

!THISisTHEcommand

#

!THISisTHEcommand again

#

these will have different links

tight heath
copper crystal
#

ffs

#

nvm

#

you don't get what I mean

tight heath
#

yes I do but you don't know how these links work

#

lmao

copper crystal
#

THE BOT SHOULD AUTOMATICALLY RETURN THE LINK

quartz kindle
#

@viral spade keep a copy of each users level in memory, and increment it locally, and only push to db once a while. if you do it every 30 seconds for example, the most it can happen is you lose 30 seconds of data in case of crash

tight heath
#

it does automatically

#

boi I can write that command in 20s

#

you're just a big mumbodumbo

twilit rapids
#
msg.channel.send(`https://discordapp.com/channels/${msg.guild.id}/${msg.channel.id}/${msg.id}`)
quartz kindle
#

@viral spade as for incrementing minutes, i dont see how something like that could hang your drive for 20 seconds. do the same thing, keep a copy of the minutes in memory, and only push them to db once a while

twilit rapids
#

yeetn'fleet

copper crystal
#

that makes more sense, thank you

tight heath
#

literally what we wrote

#

20 times

quartz kindle
#

^

tight heath
#

but library independent

twilit rapids
#

Every new bot developer is using Discord.js these days

quartz kindle
#

js language of the future

#

and eris is @_@

tight heath
#

js is ez