#development
1 messages Β· Page 789 of 1
Oh ty!
Hey all, im trying to make a simple bot that adds people to my minecraft whitelist.
It running nearly perfect, im just trying to set permissions so only mods can use it. So far, it works properly in only letting mods use it. But i cant get it to reply to people who arent mods. Im working in Python
Send your code
@radiant marten
@copper cradle
Lemme see
I mean
@has_permissions(administrator=True)
It'll only respond with ppl with admin perms
Oh.
So then i would NEED to make it an "if user has admin then do action, else say 'you cant do this'" right?
im getting this error all the time
MongooseTimeoutError: Server selection timed out after 30000 ms
i searched the whole internet and still cant find a fix
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://arcle:<password>@xeroc-z467s.mongodb.net/test?retryWrites=true&w=majority',{
useNewUrlParser: true,
useUnifiedTopology: true
});```
Hey I think your password is bugged. let me help you with that. Just send it here π π€£
Some users said commenting (or removing) useUnifiedTopology may fix the issue
yes. but it logs a warning that i should set it to true
i turned it off yesterday and waited if the error was logged again
it was
are you using atlas?
did you add your ip in the admin panel?
According to kunal usapkar on stack overflow
let me try
still
same error
been getting this error for months i still cant fix it
and if youre using the latest creds for npm mongoose, it doesnt support it, if i remember right, you need to use 2.4 creds
what's the issue?
im getting this error all the time
MongooseTimeoutError: Server selection timed out after 30000 ms
i searched the whole internet and still cant find a fix
@fallen arch k then you need the older creditentals, region shouldnt matter
wdym?
bruh
@fallen arch did you try 127.0.0.1:port?
replace this with password of database user
yep thats true xd
Lmao
Is this code correct?
client.users.forEach(async u => {
// my code
});
ok thanks
How do you set up the bot? I apologize new server and such
what bot
The currency
which bot
Isnβt this nadeko?
this server isn't a support server for any bot
@HiddenRider#7786 https://discord.gg/nadekobot
π invite link here
it's fine when it answers a question
what is the max amount of users you can fetch with reaction.fetchUsers()?
Difference between discord js stable and discord js master
stable is a stable version while master has newer features (and removed quite a few that were marked as deprecated on stable) and continually gets updated
Which one is better for beginner's
literally doesnt matter
Oh
I don't use JS, but I guess master has more features
We can create bot with python too?
you couldve just linked the discordapp doc page but ok
I get error when using meme command. Sometimes it works, but sometimes I get this:
https://nmw03.is-inside.me/94Q34wYN.png
i am using reddit api
Like I said; scuffed
reddit is often broken, also for humans
you will have to try again later

does it really matter which is better, you couldve just specified the limit for both
client.on(`guildCreate`, guild => {
sendJoinLeave(`New guild joined: \`${guild.name}\` [ID: ${guild.id}]. This guild has ${guild.memberCount} members!`);
}
client.on('guildMemberAdd', (guildMember) => {
guildMember.addRole(guildMember.guild.roles.find(role => role.name === "ew"));
}
How can i combined these two?
wdym?
if you want to give all members role when your bot joins just do a loop (with cooldowns or its api ban)
Oh and btw I think you're missing a )
Could someone help me change my ytdl-core music to lavalink?
or something better than ytdl-core?
like where do I start
lavalink is standalone music player, it wont need ytdl.
The docs
it has music seaech etc. alr
Oh thats really cool
LL has its own separate node which requires hosting
Yes
or ask timo a. for his lk server
I've managed to host it successfully on the same server
I host like 20 things on shared server
Depending on your usage it could be demanding
okay, so where would I start with lavalink? downloading the server?
ok
wait what was it
https://discord.gg/0hMr4ce0tIk3pSjp support here
remember that LP is not LL
k
Need some help with command handler
It won't work
This is the code:
const Discord = require("discord.js")
const fs = require("fs")
const bot = new Discord.Client()
exports.run = async(client, message, msg) => {
if (message.author.bot) return;
if (message.channel.type == "dm") return message.channel.send(`Sorry, you can't use commands here, please go to a server to use Corynth commands.`);
const db = require('quick.db')
let prefix = await db.fetch(`prefix_${message.guild.id}`);
if (!prefix) {
prefix = 'p?'
}
if (message.content.startsWith(prefix)) {
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if(!client.commands.get(cmd.slice(prefix.length))) return;
client.commands.get(cmd.slice(prefix.length)).run(bot, msg, args);
}
}```
This is the error:
is client.commands a discord collection ?
you dont need this const bot = new Discord.Client(), delete it
show the code where you create client.commands
also, run(bot, msg, args) should use client not bot
and what is the difference between message and msg?
you use message everywhere in this file, but then you try to send msg to the command
prob copy pasta
I have a problem. I am quite new to coding and bot development so I get this error
var embedSent = await message.channel.send(embed); ^^^^^ SyntaxError: await is only valid in async function β[90m at wrapSafe (internal/modules/cjs/loader.js:1067:16)β[39m β[90m at Module._compile (internal/modules/cjs/loader.js:1115:27)β[39m β[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)β[39m β[90m at Module.load (internal/modules/cjs/loader.js:1000:32)β[39m β[90m at Function.Module._load (internal/modules/cjs/loader.js:899:14)β[39m β[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)β[39m β[90m at internal/main/run_main_module.js:17:47β[39m
line 77 is
var embedSent = await message.channel.send(embed);
the await keyword can only be used inside an async function
for example ```js
function() {
await bla() // error
}
async function() {
await bla() // works
}```
in your case, your function is probably the message event itself
for example
client.on("message",message => {
await bla() // error
})
client.on("message", async message => {
await bla() // works
})```
message => { is the same as function(message) {
Can I have some help for a JavaScript bot?
How do I get my bot to wait for a message and then respond with Java? This is what I need help understanding how to do:
I am trying to do a series of commands, like a few bots can do, where you say a command like
"Random Person: '!verify'"
"Bot: 'What is your Discord ID?'"
"Random Person: '2838423788323'"
"Bot: 'You have been verified!'"
Is that too confusing?
This is the code so far
if (command === "bet") {
message.channel.send("Hello, ${message.author.username}, how much would you like to bet?")
awaitMessages
Is that it?
You have to keep in mind when uploading an update to your bot when it is in the Discord Bot List
Are you using discord.js ? @viral flax
Thank you so much!
I have another question. What is the filter's job in the example?
// Await !vote messages
const filter = m => m.content.startsWith('!vote');
// Errors: ['time'] treats ending because of the time limit as an error
channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })
.then(collected => console.log(collected.size))
.catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));
@quartz kindle ```
for (var i = 3; i < messageArray.length; i++) {
item += (messageArray[i] + " ");
}
winnerCount = Number(messageArray[1]);
time = Number(messageArray[2]);
var embed = new Discord.RichEmbed();
embed.setDescription(item);
var embedSent = await message.channel.send(embed);
embedSent.react("π");
Here is part of the code
in this example, bot await messages which starts with !vote @viral flax
@earnest phoenix i already told you
you need to add the async keyword before the start of the function where your code is
the problem is not that part, its the beginning of the code block
@viral flax btw Java is not Javascript, they are completely different things lul
discord.js is Javascript
@quartz kindle Thanks, resolved the problem <3
Can someone give me some code that can set a status for my bot? I use node.js/discord.js I tried looking it up online, but the code I found isn't working.
DM me a response
You mean the bot's presence
If so, look into this: https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setPresence
what is your d.js version
IDK
go to package.json and look
11.5.1
put the code in your ready event
OK
/home/tim lol
hes in ur pc
what does the package do
lfdgh
something along the lines of discord.js-light
its discord.js but without caching
discord.js-light will do
timcord.js
lmao
but is tim light enough? π
lul
djs-but-fuck-cache
discord.js-but-without-a-memory-leak-in-its-sharder
lmao
d.js-bwamliis
skinny-discord.js
lightcord.js
discord.js-but-good
this thing is pretty cool for names lmao https://jtho.me/Package-Name-Generator/
yeah lmao
discord.js-confucianist
corneocalcareous
just use anime character names like any other EdGy developer
^^^^^^
all other djs frameworks already do that
cry is onto something
discord.js-san
two of my projects are named after anime chars lol
lmao
akame and rize
one of my projects is called "waifu"
mainstream boi
i want to get back to doing my wrapper for the weeb.sh api but the api is kind of messy 
honestly cant be ask bad a CR's
In lavalinks application.yml, does the address matter? or will 0.0.0.0 do localhost? js server: # REST and WS server port: 2333 address: 0.0.0.0
dont matte
@mystic violet 0.0.0.0 binds it to every interface. That does mean it'll be accesible to the global internet. If you bind it to something like 127.0.0.1, it'll only be available locally on the machine
okay
Hello\
I'm having some trouble with python. I have a function that I call that isn't running, if I print the function it logs <function start at 0x000001C43EFFC048> meaning it does exist. There is no error either.
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at Piper.VoiceConnection.piper.on (/rbd/pnpm-volume/fed41ecc-e99f-4fee-96f5-f55ca85d3ceb/node_modules/.github.com/abalabahaha/eris/71dd17eaf6a587ddb1427d406df411c18de0b7be/node_modules/eris/lib/voice/VoiceConnection.js:131:48)
at Piper.emit (events.js:189:13)
at Piper.stop (/rbd/pnpm-volume/fed41ecc-e99f-4fee-96f5-f55ca85d3ceb/node_modules/.github.com/abalabahaha/eris/71dd17eaf6a587ddb1427d406df411c18de0b7be/node_modules/eris/lib/voice/Piper.js:188:18)
at ClientRequest.HTTPS.get.once (/rbd/pnpm-volume/fed41ecc-e99f-4fee-96f5-f55ca85d3ceb/node_modules/.github.com/abalabahaha/eris/71dd17eaf6a587ddb1427d406df411c18de0b7be/node_modules/eris/lib/voice/Piper.js:57:101)
at Object.onceWrapper (events.js:277:13)
at ClientRequest.emit (events.js:189:13)
at TLSSocket.socketErrorListener (_http_client.js:392:9)
at TLSSocket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
facing this error while playing music
eris dev version
Why does using .split(":")[0]; sep at periods too?
colons*
You're probably doing more than that. What exactly are you splitting / source code
s
What should be normal the latency of a discord bot?
it should not be bigger than 1000ms imo
does it also depend on bot hosting region
im trying to make my function return an integer. parseInt() returns something, but if i try to do any math task with it - it returns NaN.
code: ```js
// Get file size in bytes.
"use strict";
const get = require ("node-fetch");
module.exports = async url => {
const file = await get (url);
const buffer = await file.arrayBuffer();
return buffer.byteLength;
};```
1 s
can you read
mine is having 367. something
thats around a ball park
wdym
its about right
oh
depending on how ur calculating it
so, arrayBuffer() in node-fetch returns an ArrayBuffer object
and byteLength is how much bytes are in a file
i just dont get it why is it not an integer
doesnt it return the bytes from that position
no
@modest maple
so for example if i do js getSize ("https://audio.ngfiles.com/0/1_newgrounds_consin.mp3")
it is gonna return 68880
how are you using parseInt?
parseInt(result)
since byteLength is already an int, why do you need it?
then how if i do any math task with it (multiply, divide, whatever) - it sets to NaN?
console.log it, it might be undefined
@quartz kindle
try (await require(...)(url)) / 1024
what was the problem? lol
await
how to design a readme for github repository of a discord bot?
well I already use markdown
I meant how would I structure my bot's information on the md file
that it look nice
and provide all info
Timmmmmmmm
i cannot for the life of me
get those text boxes to come up
xD
padding just forces everything else down
span img {
height: 300px;
display: inline-block;
vertical-align: middle;
}
.content span span {
font-size: 200% !important;
font-size-adjust: auto;
font-family: "Stencil Std", fantasy;
column-fill: rgba(0, 0, 0, 1) !important;
}
.live-feed-1, .anime-search {
display: inline-block;
width: 50%;
padding-left: 50px;
padding-bottom: 50px;
font-size: 30px;
}
.anime-details {
display: inline-block;
width: 50%;
padding-left: 150px;
padding-bottom: 50px;
font-size: 30px;
}
img {
display: inline-block;
}
.live-img {
width: 400px;
display: inline-block;
padding-left: 50px
border-style: solid !important;
border-color: white;
border-radius: 8px;
border-width: 4px;
}
.details-img {
width: 500px;
display: inline-block;
border-style: solid !important;
border-color: white;
border-radius: 8px;
border-width: 4px;
}
.search-img {
width: 500px;
display: inline-block;
border-style: solid !important;
border-color: white;
border-radius: 8px;
border-width: 4px;
}
#bot-details-page #details .container {
padding-left: 50px;
}
.left-container .column {
padding-left: 50px !important;
}
.wrapper-page > .container .columns > .column {
padding-left: 50px !important;
}
.search-img {
border: None !important;
padding-left: 50px
}
.anime-details {
padding-left: 50px !important;
padding-top: 50px !important;
}
.live-img {
padding-left: 50px !important;
padding-top: 20px !important;
width: 500px;
}
.live-feed-1 {
padding-left: 50px !important;
padding-bottom: 50px !important;
}
.anime-details {
padding-bottom: 50px !important;
}```
yes ik im a !important abuser
xDD
jesus christ
vertical-align:top on all inline-blocks
caller.utils.createMessage(command.msg.channel.id, {
embed: {
color: caller.color.blue,
description: lang.commands.vote.description.replace('@link', `https://top.gg/bot/668481980547072007/vote${command.guild ? `?guild=${command.guild.id}` : ''}`),
},
});
};
exports.Settings = {
command: 'link',
category: 3,
show: true,
permissions: [],
dm: true,
};```
why no work
what library is that?
use webhook
forgot the thing about js const command = message.content .trim <idk here> <idk here>
idk what there need to stand same after .trim(<here>)
nvm
trim removes the wanted string
like msg content is "hello world", and you want to delete "d", you can do "hello world".trim("d") and now it becomes "hello worl"
i think so
@restive furnace trim() doesnβt have any arguments
if you want to "delete" d in a string
you do "de".replace("d", "")
result would be "e"
first Argument for what you want to replace second for what you want to replace it with
const Discord = require("discord.js");
const db = require('quick.db');
const ayarlar = require('../ayarlar.json')
module.exports.run = async (client, message, args) => {
if (!message.guild) {
return }
let user = await db.fetch(`prem_${message.author.id}`);
let server = await db.fetch(`sunucupre_${message.guild.id}`);
if( user || server == undefined){
message.channel.send(":bizcooluzyee: You are not premium /TR: Premium deΔilsin.")
}else{
if( kullanΔ±cΔ± || sunucu == 'pre'){
var embed = new Discord.RichEmbed()
.setTitle('Demo')
.setDescription('Testing')
.setColor('RED')
return message.channel.sendEmbed(embed)
}
}
};```
if( user || server == undefined){ < I made two quick.db's here.
I want the user to say "You're not premium" if pre <is not open. If the server is pre, it should not say "You are not premium".
However, I get alerts even though the user is premium and the server is premium.
i how to fix pls help.
thanks so much β€οΈ
no wait
okay
if (server || user !== 'pre') {
//code
}```
that doesnt work the way you think it does
if(A || B === C)
means
if A exists or if B equals C
if( user || server == undefined){ means if the "user" variable exists, or server doesnt exist, but i recommend you toi use !server or server !== null instead of server === undefined
ah yes ^
trying to resolve an object Promise any ideas ?
It's related to Node.js's process object, trying to get the swap, cpu and disk usage
If it's inside a function you can make that function async by adding the async keyword to the function declaration
And then you'll be able to use something like this let resolvedPromise = await somethingThatReturnsPromise();
You could also use somethingThatReturnsPromise().then(resolved => {/*Do something with resolved*/})
which doesn't require the async function and won't block your code (code below the .then() will continue while waiting for the promise to resolve)
You submit the bot @ https://top.gg/bot/new
And then wait for it to be approved
ok
i don't think you can use the api until your bot is approved
can u still teach me how to use it?
read the docs
which docs are u talking about
thx
hey now, dont offend our dear website admins and lib devs
get its content, get the channel, and send the content to the channel
You use the docs
i mean, this is basic stuff that you already know how to do
Ill explain here. ```
- Get the message content (like on message -> if message channel type is dm -> send to desired channel)
- Get the channel
- Send the message content into the channel```
More clearly
if he didnt understand tim
message.content isnt a function
as it said
it's a property
you are doing message.content()
do you even try to read your error
yes
Do you know how to retrieve values from an object (it's a class in this case with a getter)
remove () @earnest phoenix
does anyone know here how to set the hours in a string to a certain time?
some background. i calculate the past 7 days but i want to set the hours to 00:00:00 for retriving stuff from a database (use a timestamp as key)
can I store data as key-value in mongoDB?
@lusty quest you can use modulo on a timestamp
does this work in js?
its a human readable timestamp. may i need to make a other system
whats the format?
can it be imported into new Date()?
what is the database key format?
@summer torrent yes
07-02-2020 00:00:00 as example
you're using that format in the database as well?
it would be easier to use timestamps in the database, and only convert to human readable when needed
I want to make auto-response system. For example
const responses = {
"Hi": "Hai",
"abc": "bca"
}```
I am looking for a guide for save data as this ^. But I can't find
MongoDB consists of collections that have documents, those documents consist of key-value pairs
use <Array>.find and save it as a variable (assuming it's an array)
You could have a responses collection for example, which can have documents that look like this
{
trigger: "abc",
response: "bca"
}```
And that would probably be a lot easier to work with
@summer torrent ^
some returns true if one or more elements match
find returns the first element that matches
filter returns all elements that match
thanks I will try
why did he delete the question tho lol
wait did you answer to me or to that guy
to you
Deleting your messages just makes the people that helped you look stupid because they answered something that wasn't asked
oh
@quartz kindle thank you. got now everything working
the thing is i need to check if any element of an array i have fetched from a json, matches with the content of a discord message
which is easy using the function if (words.some(word => msg.content.toLowerCase().includes(word))) {
however that only returns true/false and its fine only to trigger the if
as i said
but i also need to know what the element that matched is
some returns true/false
ye
the one that matched
for example i have an array where i have ["donate", "buy"] and so on
but do you want to return the words or the messages?
the word that matched
only one or many?
in theory one
then use find
words.find(t => msg.content.includes(t))
some, find and filter are all used exactly the same way
the only difference is what they return
and the fact that find stops after finding the first match, filter doesnt stop
lul
and it was that simple
Que no vengan que no cuela
lul ty
Umm so I am using the Giphy API and i cant seem to get the url to the image to work
more detail pls
i cant get the url from the API response
since it sends so much information
of course you can
lmao "since it sends out so much information"
its keep sending undefined
then stop making up your own properties and read the docs
thats what it says to do......
show your code
if(command === `gif`) {
let gifName = args.join(` `);
if(gifName === ``) {
message.channel.send(`Please provide a GIF!`);
}
else {
let url = `http://api.giphy.com/v1/gifs/search?q=${gifName}&api_key=${config.giphyAPI}&limit=1`;
request(url, function (err, response, body) {
let gif = JSON.parse(body);
const gifEmbed = new Discord.RichEmbed()
.setColor(`#03d3fc`)
.addField(`GIF Name`, `[` + gif.data[0].title + `](` + gif.data[0].url + `)`)
.setImage(`${gif.data.images.original.url}`)
.setFooter(`Provided by: ${config.clientName} & https://developers.giphy.com/`)
message.channel.send(gifEmbed)
.catch(error => sendLog(error));
sendLog(message.author.username + ` sent: \` ` + message.content + `\` in channel \`` + message.channel.name + `\` of guild \`` + message.guild.name + ` \``);
return;
});
}
}
this is what i got
the url property is just the url to the page
you need a direct image url
which you can get through the images array inside of the data object
images is an array of objects
so we can see whats in there
you will never be able to access it through a named property
the images object gives me a bunch of stuff
"original":{
"frames":"58",
"hash":"cda24476b70d2c43dafc0b9653f8a69b",
"height":"160",
"mp4":"https:\/\/media3.giphy.com\/media\/65ODCwM00NVmEyLsX3\/giphy.mp4?cid=1776ca554d9a0ae18245b0e491162617c71ee16e6589e499&rid=giphy.mp4",
"mp4_size":"2047281",
"size":"1077609",
"url":"https:\/\/media3.giphy.com\/media\/65ODCwM00NVmEyLsX3\/giphy.gif?cid=1776ca554d9a0ae18245b0e491162617c71ee16e6589e499&rid=giphy.gif",
"webp":"https:\/\/media3.giphy.com\/media\/65ODCwM00NVmEyLsX3\/giphy.webp?cid=1776ca554d9a0ae18245b0e491162617c71ee16e6589e499&rid=giphy.webp",
"webp_size":"339352","width":"160"
},
this is what i want
the url from this
but it comes out as undefined
then treat it like a dict
@earnest phoenix that is not the content of the console.log i told you to do
does it start with {[ or just with {?
just {
or [ {
Free text/code sharing site supporting 450+ different languages!
and if you console.log(gif.data[0].images.original.url) ?
ok
@quartz kindle https://media2.giphy.com/media/kHcaX3uLU3IME/giphy.gif?cid=1776ca55a961b4299da95f6356cd2bf9d2c82ce9960e8141&rid=giphy.gif
this is what it sent
then its correct
try without `${}`
π
How do you set a bot's status to dnd in discord.js
setStatus("dnd")
I tried
It just doesn't work
it always goes to online
client.user.setStatus('dnd', c!help | Serving ${client.guilds.size} servers)
It sets the second part of the status
What if I do this
client.user.setActivity(c!help | Serving ${client.guilds.size} servers, {type:PLAYING});
client.user.setStatus('dnd')
Nope still not working
I don't know what channel to put this but I'm having trouble because I started coding my bot 2 days ago and I don't know how to do the role permission
Can anyone see the issue with my code
client.user.setActivity(`c!help | Serving ${client.guilds.size} servers`, {type:`PLAYING`});
client.user.setStatus('dnd') ```
did you tryed it without setActivity?
Yes
does it work?
error log ?
your client is the client right? (Client = new Discord.Client())
client.user.setStatus('dnd')
.then(console.log)
.catch(console.error);```
to show in the logs
ClientUser {
id: '660818351638970370',
username: 'Corynth',
discriminator: '3308',
avatar: 'cf91aa0308408db6f9df610ba26ecbde',
bot: true,
lastMessageID: null,
lastMessage: null,
verified: true,
email: null,
localPresence:
{ status: 'dnd',
game:
{ name: 'c!help | Serving 171 servers', type: 0, url: undefined },
afk: false,
since: 0 },
_typing: Map {},
friends: Collection [Map] {},
blocked: Collection [Map] {},
notes: Collection [Map] {},
premium: null,
mfaEnabled: true,
mobile: null,
settings: ClientUserSettings { user: [Circular] },
guildSettings: Collection [Map] {} }```
That's the error
I mean the log
This is allright mate.
Your Discord client
Also keep the bot offline until it disconnects from the websocket.


Hello
Anyone here that could help me a second?
I'm trying to retrieve the user's ID when he logged in. How do i get that using the request.query or request.session?
is this about oauth2
well. i already got the oath2 and this is what i get back in console.log
Session {
cookie:
{ path: '/',
_expires: 2020-02-15T21:06:14.871Z,
originalMaxAge: 60000,
httpOnly: true },
discord:
{ access_token: 'THE_ACTUAL_TOKEN',
expires_in: 604800,
refresh_token: 'THE_ACTUAL_TOKEN',
scope: 'identify',
token_type: 'Bearer' } }
{ code: 'THE_ACTUAL_CODE' }```
read docs
where the code is in request.query and the session is ofc.. request.session.
now you should be able to use this token to make a GET request to retrieve the user's id
ahm. So i've started coding a bit back. But how does that work using the GET request there?
app.get(request.query.code) {
// do something?
}```
You make the request with the bearer token
I believe it's a header as authorization like Bearer CODE
not sure on that though
@peak venture
code is now exchanged for the user's access token by making a POST request to the token URL with the following parameters:
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
i was looking into this @quartz kindle https://discordapp.com/developers/docs/resources/user
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
yes
GET/users/@me
Returns the user object of the requester's account. For OAuth2, this requires the identify scope, which will return the object without an email, and optionally the email scope, which returns the object with an email.
exports.connect = async (request, response) => {
if(request.session) {
await exchange_code(request.query.code, request.session);
console.log(request.session)
console.log(request.query)
}
else
{
console.log("Cookie error");
}
response.send(login);
}```
so basically, user authorizes -> you get a code -> you sent the code to get an access token -> you get the user with the access token
ah you're using an oauth library?
so if exchange_code already does the exchange
let exchange_code = function (code, session)
{
const params = new URLSearchParams();
params.append('client_id', CLIENT_ID)
params.append('client_secret', CLIENT_SECRET)
params.append('grant_type', 'authorization_code')
params.append('code', code)
params.append('redirect_uri', REDIRECT_URI)
params.append('scope', 'identify')
return fetch(API_ENDPOINT + '/oauth2/token', { method: 'POST', body: params })
.then(res => res.json()) // expecting a json response
.then(json => { session.discord = json; })
.catch(err => console.log(err));
}```
yes it does
alright, so you need to get the content of exchange_code
let token = await exchange_code(...)
console.log(token)
token logs me undefined though
hmmm, ah i see it is being placed in session.discord
then console.log(session.discord)
or request.session.discord
session.discord is undefined though and request.session is
cookie:
{ path: '/',
_expires: 2020-02-15T21:19:31.994Z,
originalMaxAge: 60000,
httpOnly: true } }```
what about request.session.discord?
even after you await exchange_code?
after await there is a discord
does it look like this? json { "access_token": "6qrZcUqja7812RVdnEKjpzOL4CvHBFG", "token_type": "Bearer", "expires_in": 604800, "refresh_token": "D43f5y0ahjqew82jZ4NViEr2YafMKhue", "scope": "identify" }
yes
ok, so thats your access token
now you can make a GET request to /users/@me
using headers: { Authorization: `Bearer ${access_token}` }
discord base url /users/@me
https://discordapp.com/api/v6/users/@me
its a request you make, not a request you receive
app.get(url, (request,response)) is for receiving requests
app is your express server right?
yes
return fetch(API_ENDPOINT + '/oauth2/token', { method: 'POST', body: params })
.then(res => res.json()) // expecting a json response
.then(json => { session.discord = json; })
.catch(err => console.log(err)); ```
but then a new exchange_code function i assume
method of get
its not the same function, but its the same principle
fetching the api endpoint, with a get method, with the authorization headers
then awaiting the json response
so you can take that function as a boilerplate and modify it
as params i would need the session.discord.acces_token and the code hm?
identify
let exchange_login = function (code, session)
{
return fetch(API_ENDPOINT + "/users/@me", { method: 'GET', headers: 'identify'})
}
``` Would this suffice then?
headers should be headers: { Authorization: "Bearer "+session.discord.access_token }
then to you need to await the json response
.then(res => res.json())
Cannot read property 'discord' of undefined
make sure you give it the session from before lol
haha
ofcourse
stupid me :p
aight Tim.
This is what i have at this moment getting undefined token
let exchange_login = function (code, session)
{
return fetch(API_ENDPOINT + "/users/@me", { method: 'GET', headers: { Authorization: "Bearer " + session.discord.access_token }})
.then(res => res.json()) // expecting a json response
.then(json => { session.discord = json; })
.catch(err => console.log(err))
}
exports.connect = async (request, response) => {
if(request.session) {
await exchange_code(request.query.code, request.session);
let token = await exchange_login(request.query.code, request.session)
console.log(token)```
remove this .then(json => { session.discord = json; })
and you dont need code here, you can remove both request.query.code and code from the function
alright
at this point, token should be the user object already
Aight. it does work :)
Mind sharing the thought process behind it
sure, which part?
the get request
So if im correct the request first goes to check wether it has an authorisation key
then with that key it can do various requests like this get request correct?
yes, first the use gives you his explicit consent, by clicking authorize
this gives you a code that says "i have received consent from this user"
then you send this code to discord saying "i have been given consent by the user, give me access"
and discord gives you "ok, here is an access token for this user"
then you use this access token to make requests to discord in that user's name
nice
the access token has a scope limitation, where it can only do what the scope specifies, for example "identify" only lets you access certain things about the user
and it has an expiration time, so its only valid for a limited time
I wish to make the user login for a maximum of 6 hours though
Dunno wether this is enough for that though
or wether i'll need to use the authorisation and refresh code for that
there are two things you can do here:
- you save the user's id in a cookie, so you remember the user next time he visits. no need to request authorization again
- you use the refresh_token you received together with the access_token to extend the validity of the token
aight
Tim!
hey but ahm one more thing hΓ©a.
this response send, can i carry this cookie to the next page to use his avatar f.e.
i mean. i probably can. π but do i need to store it in a variable or so?
you can do whatever you want, as a variable, as a cookie, as a session storage, etc
you can save it for example, in session.user
thats a good thing.
So I was trying to create a music bot, but im getting this error even though I have FFMPEG installed
and then on the website. how would i use this plain
avatar: 'e13d55ada46c982c53170db88c564426',
@earnest phoenix is that heroku?
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
π thnx
@amber fractal yes it is
One sec
You have these buildpacks? https://oliy.is-just-a.dev/nwx9ln_2816.png
well not the nodejs one
no....
You need the ffmpeg buildpack
ah i never knew there were more than the ones listed in settings
That was the only reason I ever used heroku I didnt wanna kill my cpu for a private bot lmao
yea same
make a heroku/glitch cluster for music processing lul
how can send my bot messages with an webhook in jda?
wait i thought you guys didnt allow projects from glitch hosting service
They just dont allow bot ghost iirc
Tim π Thank you for your support so far π
π
how can send my bot messages with an webhook in jda?
but it doesn`t work
i cant make it work. wait for someone who can
ok
Let me show you the jda docs https://oliy.is-just-a.dev/6q5d8d_2817.png
my bot was rejected for having Nsfw in the .urban command, but my urban command is an upstream type of library to get a definition of the word that the person speaks.
any command that exposes (potentionally) nsfw content needs to be locked to a nsfw channel
yup that is nsfw
re-read what i said
Your bot @invalid-user was declined. Reason: Your bot has an NSFW command (.urban) that can be used in non-NSFW channels. Please lock this command to only NSFW channels.
that can not be potentially nsfw
you need to either remove it or make it only work in nsfw channels
but there is no Nsfw in that command
function play(connection, message){
var server = server[message.guild.id];
server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter: `audioonly`}));
server.queue.shift();
server.dispatcher.on(`end`, function(){
if(server.queue[0]){
play(connection, message);
}
else {
connection.disconnect();
}
});
}
So im getting an error and i have no idea why....gain
server is undefined
oh wait
what even is server lol
wait
lol
also double definition of server

Lol
How would make rich embed field titles white and the descriptions gray instead of the usual gray & white? discord.js
and .setTitle and .setDescription only allows one
you can't
you can make them look a tiny bit different by using ` and *
Who tests these bots? They said my commands are not working. All commands work lol 2 weeks waiting and not even tested. It's always the same reason, I had already given up trying to post bots here. ππ
mods check the bots
you can check the full reason in mod logs
and see who declined your bot and DM them
dm the mod
Is using self.bot.dbl_client.check(user_id) good (to be used every time a user uses a command) or will I need yet need to cache the request in my bot for some time
are you on python?
yes
store in cache
dont send a request for every message
just gonna get u ratelimited or banned by le api
How would I convert this format 0:00 to milliseconds, and vise-versa?
good that i asked before doing it
is there a quick library or utility I could use?
@mystic violet what language
hi i have a question
and we may have an answer if you ask
im trying to make a suggestion command and
the suggestion returns in commaas
commas
i understand why but how do i fix it
Can you show some code?
example: u,should,add,a,shop
here
const Discord = require('discord.js')
module.exports = {
name: 'suggest',
description: 'Suggest!',
execute(client, msg, args, begcool, findset, Coole) {
const guild = new (require('discord.js')).Guild;
const channel2 = `678049713240408069`
if(msg.guild.id === `677694433675706409`){
let suggestion = args.slice(1-1000)
msg.channel.send(`Sucess! Check #bot-suggestions to see your suggestion. Tip: You only have 1000 words to type. if you go over the limit your message will be cut to 1000 words.`)
const embed = new Discord.RichEmbed();
embed.setTitle(`Suggestion:`)
embed.setColor("F08080")
embed.setDescription(`${suggestion}`)
embed.setThumbnail(`${msg.author.avatarURL}`)
embed.addBlankField(true)
embed.addField('Suggestion By',
`${msg.author.tag}`)
embed.setFooter(`Upvote | Downvote`)
msg.guild.channels.get(channel2).send(embed).then(x=> x.react('π').then(x.react('π')))
}
},
};
Can I ask what args.slice(1-1000) is for and why you don't join it instead (if args is an array anyways)
when i do the pong command thing but replaced it with noot, i said noot and my bot just spams noot noot tagging me
args is not an array
@hybrid sequoia make it ignore bots
you're positive?
oh
thats an array
one sec brb
split turns it into an array
You're gonna wanna join it instead, but it might contain the command to so I'd slice off the beginning then join it
example?
or alternatively you can just shift then join
Just <Array>.join(" ")
That will join the array by space
there are no spaces in the array
doesnt matter
k
that's not how that works
all it does is combines all the elements into one string
by whatever you provided as a parameter
l
"this is a test".split(" ") = ["this","is","a","test"]
["this","is","a","test"].join("whatever") = "thiswhateveriswhateverawhatevertestwhatever"
.
discord.py
How could I make my bot automatically leave the voice channel if no audio is being olayed for some time?
when a song ends, start a timer. if another song starts, cancel the timer
if the timer runs through, make it leave the channel
i dont use py, so idk how timers work there, but that the logic of it
Hmm, thanks for help.
Implementing it in my code now.
discord.js
i tried making a clear command and it did not work. When i ran the command it did not do it and it said invalid args and my args were fine.
Here is code:
module.exports = {
name: 'clear',
description: 'Clear!',
execute(client, msg, args, begcool, findset, Coole) {
if(args[1] && isNaN(JSON.parse(args[1]))){
msg.channel.bulkDelete(args[1])
}else{
return msg.reply(`invalid args`)
}
},
};
and this is what i ran: ,clear 1
I think its parseInt()
Also in your argument array there is only 1 object
parseInt(args[0])
It should be args[0]
@dusky garden
oh
I suggest you should learn arrays before doing this
nothing advanced twords them
Yes, using index numbers in an array is one of the most basic thing about it, m8

nv,
nvm that
it does not work
module.exports = {
name: 'clear',
description: 'Clear!',
execute(client, msg, args, begcool, findset, Coole) {
let args2 = args.join(" ")
if(args[0] && isNaN(parseInt(args[0]))){
msg.channel.bulkDelete(args[0])
}else{
return msg.reply(`NO`)
}
},
};
What is args2 for
And youβre checking if the parseInt value is not a number, which will return βNOβ
Remove the isNaN() function
And do if(parseInt(args[0]){ ... } only cause idk why you added args[0] before that
Has anyone here used youtube-grabber-js?
hey is there a radio new vegas bot i can use trying to find one....
how to make avatar command? Example:"!avatar (mentioned user)" or "!avatar"
find the user from the first argument
get its user/member object
and send that back
if the member is not found from the first arg say it wasn't found. if no arg was supplied just default to the author message.author
we can't/aren't just going to give code
aight
@earnest phoenix this module just needs to be updated
most likely user agent header is old
rip
any postgres users here? trying to figure out whats wrong with this query
SELECT * FROM users WHERE ARRAY_LENGTH(SELECT json_object_keys(pets), 1) > 0;
i want to select users where the object.keys length of pets is > 0
the error is error: syntax error at or near "SELECT"
Hey there I want to know that whether I am fairly using the top.gg api for getting votes:
- On the load of cog I store the current voted users data under 1000
for u in await bot.dbl_client.get_bot_upvotes():
self.bot.user_votes[u.id]["voted"] = True
self.bot.user_votes[u.id]["cache_time"] = datetime.datetime.utcnow()
- at command usage time i check if the votes data contains the user if not then I do a request to the api and then store that:
u = self.bot.user_votes.get(ctx.author.id, {})
voted = u.get("voted", None)
cache_time = u.get("cache_time")
if voted is None and cache_time - datetime.datetime.utcnow() > datetime.timedelta(minutes=15):
voted = await self.bot.dbl_client.get_user_vote(ctx.author.id)
self.bot.user_votes[ctx.author.id]["voted"] = voted
self.bot.user_votes[ctx.author.id]["cache_time"] = datetime.datetime.utcnow()
I store the data in variable for 15minutes and then refresh it, is that good?
language: python
libraray: discord.py 1.3.1, dblpy latest from master branch
module "d:/suu-bot/node_modules/youtube-grabber-js/index"
Could not find a declaration file for module 'youtube-grabber-js'. 'd:/suu-bot/node_modules/youtube-grabber-js/index.js' implicitly has an 'any' type.
Try `npm install @types/youtube-grabber-js` if it exists or add a new declaration (.d.ts) file containing `declare module 'youtube-grabber-js';`ts(7016)
Im getting this error and idk why
i tried what it suggested
but it gave me more errors.
tada The new winner is @Ittim! Congratulations!
im having a problem saying MODULE_NOT_FOUND, i installed discord.js again but still didnt work
what module exactly is missing if you don't mind sharing the entire console error.
Why it's not showing image? Mean bot avatar???
@violet nimbus could be cache issue / your bot is offline / not in the server
@spare goblet yeah it's not in server that's why it shows offline
BTW my bot is 24/7 online π
@violet nimbus then figure out why it's not in the server
Actually, your bot is in the server @past jacinth
@flat pelican I wanna know that why my Griffin-Bot is not in this server?
It is in the server.
Oooh?
@past jacinth
Yes it was
And it's online
It isn't
It's caching issues, just delete your cache
I've approved it yesterday, it's now muted for level up messages.
On your browser
@spare goblet no it's not the pic
I changed 2 days ago
look at the bot
@past jacinth
It'll update eventually
Oooh

Luca will fetch it and update it
π

How will dbl knwo my bot is in how many servers??
By posting your servercount to our api
@weak parrot how?
read the docs
its in the topic of #topgg-api
Hi



