#development
1 messages Ā· Page 174 of 1
my array is funky
despite me saying index 0 is 100
apparently index 0 is 1000
which is supposed to be index 1

I am so confused
when inserting everything seems fine
but when going to remove the indexes are fucked
like what? ^
void remove(size_t index) {
if(index < length && index >= 0) {
memcpy(&array[index], &array[index +1], (length - index + 1) * sizeof(T));
length--;
}
}
this was my current thought process
actually I think that first part of the if is fucked but
noice
oh wait
it was essentially evaluating 11
but wrapping it in parantheses allowed it to do the addition first
yes
math is okay
frfrfr
why
Just to try it and see
okay
its nice having built in stuff
but I wont learn by simply just using whats given
I basically figured out the efficient way before trying it myself
welp
I fucked up
meh
I will leave figuring it out without using memcpy for another time
Ask me what exactly?
why you cant write template class method definitions on a cpp file as opposed to a header file
Who says you can't?
Brain did
The C++ standard does not prohibit such a thing, there's just no concrete way to do it as template declarations and definitions both must be accessible to the compiler in the translation units
There are multiple ways this can be done
- Explicit template instantiation
foo.h:
#ifndef FOO_H
#define FOO_H
template <typename T>
class Foo {
public:
void bar();
};
#endif // FOO_H
foo.cpp:
#include "test.h"
template <typename T>
Foo<T>::bar() {
// ...
}
main.cpp:
// Yes, including the C++ file
#include "test.cpp"
// Explicit template instantiation of the types that will be used, so the linker can find the generated classes by the compiler from the translation units
// In this case, we're only using `int`
template class Foo<int>;
int main() {
Foo<int> foo;
foo.bar();
}
- Late binding of translation units
foo.h
#ifndef FOO_H
#define FOO_H
template <typename T>
class Foo {
public:
void bar();
};
// Include the implementation file
#include "foo.cpp"
#endif // FOO_H
foo.cpp:
template <typename T>
Foo<T>::bar() {
// ...
}
main.cpp:
#include "foo.h"
int main() {
Foo<int> foo;
foo.bar();
}
then explain this @earnest phoenix
They're not doing it properly, just separating them like the other non-template stuff won't work, you have to use one of those solutions I provided to be able to separate declaration and definition of templates
have you reviewed my pull request? what do you think of this https://github.com/Mistyerious/Vector/pull/1
What's the point of reviewing it when it's already merged?
i just want for your thoughts on it
Hmm why are you using std::realloc() with new/delete?
what's wrong with that?
like i get that it's not calling the constructor but it's purpose is just for expanding the memory block
The underlying allocators used for std::realloc() and new can be different and not have the same techniques of keeping track of memory, basically it's undefined behavior

so is the for loop the only way?
Hm?
like there is no resize keyword obviously
T* tmp = new T[capacity * 2];
// Move elements of previously allocated array to the newly allocated array
// Deallocate the old array
delete[] arr;
// Increase capacity
capacity *= 2;
// Use the newly allocated array
arr = tmp;
For continuous growth, keep increasing the capacity in a loop until it satisfies your specific condition and do the same steps
does memcpy work for a remove(index) function?
Sure
This effectively reduces the container size by the number of elements removed, which are destroyed.
Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).
Music
hallo, is anyone good at go here?
so i am trying to improve my go build command
i added some flags that help with the compile
but i am wondering if there is a flag to use more cores while running build
Hello
Hey
@sharp geyser ello
good morning
Ty
@earnest phoenix so you can include cpp files? I thought you could only do so to header files
You can include the contents of literally any file, no matter the file extension, the preprocessor doesn't care about what the file is or its contents
Oh okay
Thatās nice to know
Is there any real reason for that?
Or is it just a byproduct of the preprocessor
Because there are a lot of people who use different unofficial C++ file extensions (tpp, ipp, cxx, and many others), so the preprocessor doesn't have to add support to all of them, also notice how the standard library headers you include doesn't have a file extension?
Yea
So itās just because it didnāt want to add support to the numerous amounts of file extensions
Why even is there so many unofficial extensions
public static int bestFitAlgo() {
while (!inputBoxes.isEmpty()) {
Vector<Double> nextElement = inputBoxes.get(0);
int bestIndex = findBestFit(nextElement);
if (bestIndex == -1) {
Vector<Vector<Double>> newPartition = new Vector<>();
newPartition.add(inputBoxes.remove(0));
boxPartitions.add(newPartition);
} else {
boxPartitions.get(bestIndex).add(inputBoxes.remove(0));
}
}
System.out.println(boxPartitions.size());
return boxPartitions.size();
}```
hey guys i recently have created this best fit algorithm... but it's not a best fit  .
It returns me partitions that are far from optimal
all good
T& pop_front() {
T& front = array[0];
memcpy(&array[0], &array[1], (length - 1) * sizeof(T));
std::cout << std::format("Front: {}", front) << std::endl;
return front;
}
So I have a question regarding memcpy, when I call pop_front it returns the value at an incorrect index. Which if this is working how I think it makes sense
Despite putting what array[0] currently is in a variable, memcpy is removing what is at index 0 from the array, so then index 0 will end up becoming what index 1 was
so would that mean front is now also changed?
So in my case
vec.insert(0, 100);
vec.insert(1, 1000);
vec.insert(2, 1005);
pop_front should return 100, but it instead returns 1000
Okay so putting a cout before the memcpy call it does indeed show it is 100
so it even modifies what is in the front variable
interesting
Oh I see
the issue was raised when using a reference for the front variable T&, removing the reference allows it to work properly, I assume this is because no matter what it references in memeory what array[0] is, so if array[0] changes then the value of front also changes?
Yes
Remember, references are just āsafeā pointers
gotcha
also removed the T& in front of pop_front
realized I didn't need a reference here
Yes thatās good
its fine to just return a value
good ol compiler warnings helped me figure that out 
Because if you returned a ref then youād be pointing to memory that gets overwritten
yea
Best to return the actual value to the consumer so they can claim ownership of it
also another thing, I am now realizing the numerous amounts of ways to effectively remove an element from the array
Yup, many ways to do it
memmove(array, array + 1, (length - 1) * sizeof(T));
memcpy(&array[0], &array[1], (length - 1) * sizeof(T));
std::copy(array + 1, array + length, array);
now as for the last one I can probably say its not safe, as we are dealing with stuff in memory and std::copy is probably not equipped for that no? Either way in regards to it, which would be the most likely one to use
So far I have been using memcpy
but memmove is a new one I just discovered on stackoverflow
memmove is slower than memcpy because it supports copying bytes from memory locations that overlap while memcpy doesnt do that
in your case you dont seem to be copying overlapping memory so memcpy would be the best and fastest
i think std copy is the more modern c++ alternative memcpy which supports streams and some other modern c++ stuff but knowing anything c++ that supports streams its prob a bit slower than just using memcpy
I see
Thanks for the information :p
T pop_back() {
if(length == 0) {
throw std::out_of_range("pop_back() called on an empty vector");
}
T back = std::move(array[length - 1]);
memcpy(&array[length - 1], &array[length - 2], (length - 1) * sizeof(T));
length--;
return back;
}
Does this look right to you guys? It produces the correct result, but I am unsure of if it will break eventually
Like if I added a lot of elements will it still pop the back
Looks like i answered my own question

Isnāt it UB to access moved memory?
Wdym?
I donāt think array is valid after a move like that
How so?
What else would I do to get the element at the back to return before deleting it from the array
Just deref it?
hm?
Actually that might copy the object idk
The primary purpose of std::move is to enable the use of move semantics, which allows the efficient transfer of resources (such as memory ownership) from one object to another without unnecessary copying. It doesn't actually move anything by itself; it simply casts its argument to an rvalue reference.
I don't see how using move causes problems
Then again I am new to the language
Because youāve given ownership of that object to another owner
Iām not entirely sure of the semantics here bc I havenāt used move in a while
So do you opt for me to do T* back = &array[length - 1] instead?
This is probably wrong but try doing memcpy(array + length - 1, ā¦)
Seems to work fine
It pops the back off
Also just saw something similar when I googled dereference. It was talking about doing something like T* back = &array[length - 1]; but I am not sure I understand
isn't it just making a pointer to the reference of array[length-1]
Yes thatās getting the address of the last element
Yes
so I am basically storing the address of the last element in memory?
Yes
it also mentioned returning *back
Yes
What does that do?
Thatās dereferencing the reference to give the actual value
Yes
pointers and references are getting more and more interesting
And that would be UB because you would be giving a reference to data that may be overwritten without the consumer knowing
Np
Take the stuff I say with a grain of salt though, I am not always 100% certain about the specifics for C++
Honestly not sure where to proceed with this Vector implementation anymore
I have achieved an astronomical amount of work than what I thought i'd achieve
I guess I do have a question.
I know the normal std::vector has methods that return iterators
like vector.begin(), vector.end(), that sort of stuff
What exactly is it doing under the hood
Pretty much just fancy references
struct VectorIterator {
T* item;
VectorIterator<T>* next;
}
``` is the gist afaik (this isnāt valid C++ but you get the point)
I don't really get it tho š
Iterators basically are linked lists
They know what item they point to, and they point to the next iterator in the sequence (or nullptr if it doesnāt exist)
This might help
Thereās different types of iterators but the most basic just starts at a certain memory address and points to the next memory address in the sequence
I see thanks for the help on that
have you length--; it
yes
I realized that after I posted the code

Honestly don't know what else to do with this project
I feel like I have learned as much as I can, implementing the other methods of the normal vector class is just going to be a repetition of what I have already done with some small changes
@wheat mesa Hey so question
I am now realizing that pop_front() doesn't actually do whats intended when I deref array[0]
it still ends up changing to be 1000 while still removing 100 from the array
Which makes sense if I look at it this way that I am taking a reference of what is at array[0] and then its removed so it changes again
I don't recall why you were talking about deref
Hi all guys, so I've been trying to verify the presence update intent for almost 1 week, I've created a lot of features but discord is rejecting them all, does anyone have any ideas, advice or a direct solution please?
Instead of deref it, can I not just use T front = array[0] instead if using std::move can cause issues due to ownership?
Only thing you can do is ask why they are denying it.
We are not discord so we can't really give you any solutions to your problem. If discord denies it then thats them.
Always for the same reason...
Its because they have deemed you do not need the intent
Its a privleged intent, if your bot does not need that intent to function then it wont be provided
just do T back = array[length - 1];
thats what I was wondering
I didn't know if it was "safe"
cause using move would likely cause ownership issues, and derefing it would still cause the issue of it using the new value of whatever is at that index
C++ copies it implicitly for you
But I need it for automod functions to kick out discord users with accounts created less than a week ago, to get their activities via a command, to change the bot status
Nice
@sharp geyser what are you working on atm btw?
You dont need the presence intent for that
Nothing tbh
I feel like I have fully accomplished my goal with this vector implementation
Implementing the other members of the vector would just be a repetition of what I have done so far with some small changes
Yea I was, but I coudn't figure it out

Its not really super important for me at the moment tho
so I want to switch focus to another project to hopefully gain more insight into the language
I no speak that language kind sir
sure
So what can the presence intent be used with? Do you know anything about it?
Problem is I don't know what to work on now 
maybe some kind of parser
All the intent does is provide presence update events. Do you need such a thing?
You should be able to change the activity of your bot without it
and also get them
I could do that, but that haunts me 
Basic language interpreter
Treewalk interpreter
Crafting interpreters is a nice resource
First version (treewalk) is in Java, second version (bytecode) is C
If you think you can. Might want to watch some videos on the concept of parsing and interpreters first just so you have a bit of an edge
Any you recommend or nah?
@sharp geyser or make a GUI app
that's one of the many useful applications of C++
using SDL2? 
yes
That was one of my goals with c++
but doing it from scratch with SDL2 would be challenging
making an ECS will be annoying
ECS?
tf is that
Its just an easy way of managing components, kind of like how unity has game objects and such
Without one, you'd be like a chicken with its head cutt off managing everything
is there a way to optimize a ford fulkerson algorithm?
the runtime complexity is like fucked
especially when converting my data into a graph representation
it's like O(n^4)
@radiant kraken hazahhh, got SDL2 added and linked to the project
only took some copy/pasting from the internet
welp I got it to recognize sdl2 but its having issues running the example app I made
apprently its failing because of a link error
Oh wow
simple fix
congrats!!
just had to do #define SDL_MAIN_HANDLED at the top

and then SDL_SetMainReady(); in the main func
First step
Who knew reddit could be helpful

Now then to figure out how to display something
always has been
For a physics sim you donāt need an ECS just sayin
Itās fine thereās just some annoying situations

Right now Iām working on another physics sim (but with raylib now)
Just using a basic vector of objects atm
I just dont know where to start
so my only question is
what did you use when you were messing with sdl2?
Was it the official documentation or lack there of?
Uhhhh
Thereās some documentation somewhere
A beginners guide for Game Programming.
This has some good examples
Thanks
Many of which are outdated but the fundamental idea is the same
Thank you <3
Another one on the top-down space shooter wagon 
anyone else here paying for uptimerobot? I am but I think it's time I stopped and found a different service. perhaps pingdom.
uptimerobot got greedy, my last two yearly renewals were about $60 each
$224 a year is ridiculous and this is WITH a 20% loyalty discount!
at this rate I'm tempted to just put monit on a vps
seems pingdom also got greedy and want $50 a month! I'll do it myself smh
people actually pay for uptimerobot?
Why are you using that?
for its actual purpose, monitoring my clusters and offering a real status page to users: https://status.triviabot.co.uk
its not a huge enough feature that i would consider paying that kind of money though
yeah people who arent just using it to keep a bot alive on a free hosting platform do pay for it, it does a specific job
but those kind of prices, i could just get a nice vps and do it myself
Ćø
nice
what do monitors mean in this context?
also subscribers
i see these companies setting pricing by number of monitors and subscribers but idk what they mean with that
why isnt check interval more important?
pings or checks of a service
by ip or hostname
and yeah I would expect it to be monitors frequency be more important
in my case i only have one or two api endpoints to monitor, so any free plan should do i guess
you can customize the request right? like if a service only accepts post requests
@sharp geyser Is the presence update intent useful for example for economy commands?
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
hey guys, i am unsure if someone knows these algo's
however, for a box fitting problem, instead of ussing the usual offline algorithms to solve such bin problems
what about using something like a ford fulkerson algorithm?
Where we create a source, sink node and basically only draw a flow of 1 if they fit in each other, which requires us to copy the boxes.
I mean, for large inputs the algo will be slow asf but i think it's way better than the normal bin algo's as they are non-optimal.
What would you guys think?
Hi, I'm not sure if this is the right channel but are there any bots that can repost replies containing photos from a tweet? thx
how to see if a user is voting for your bot using topggpy lib
webhook
@earnest phoenix currently making our own "string" class in C++ as a part of our assignment, do you know if this is a good way to implement a += operator? I'm not sure about the semantics of how the null terminator character works ```cpp
MyString &MyString::operator+=(const MyString &str) {
char* temp = new char[length];
strcpy(temp, chars);
chars = new char[length + str.length];
strcpy(chars, temp);
for (int i = 0; i < str.length; i++) {
chars[i + length] = str.chars[i];
}
length += str.length;
return *this;
}
(And yes I know strcpy is vulnerable, it doesn't matter for the sake of this assignment)
and MyString has char* chars and int length
this also leaks memory but idc atm
you can just create your own operator for things??
Yeah, C++ has operator overloading
Also, am I allowed to memset a const char*
e.g. ```cpp
const char* toApp = new char[n];
memset((void *) toApp, c, sizeof(char) * n);
That's not so bad but you can also do it like this
MyString& MyString::operator+=(const MyString& str) {
// Combined length of the strings
length += str.length;
// New char buffer for the concatenated string
char* buff = new char[length + 1];
// Copy the old char buffer to new one
strcpy(buff, chars);
// Concatenate the string (right-hand side operand of `+=`)
strcat(buff, str.chars);
// Terminate string with a null terminator
buff[length] = '\0';
// Use new buffer
chars = buff;
// Return reference
return *this;
}
does the null terminator count towards the length of the string
(all my homies hate c strings)
strlen() returns the length excluding the null terminator, sizeof() on the other hand includes the null terminator
But yes the null terminator counts towards the length
damn, c strings are terribly designed
I assume strcpy doesn't copy the null terminator?
The
strcpy()function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are written.
Do you see anything obviously wrong about this (other than the mem leaks)? ```cpp
MyString &MyString::assign(const MyString &str) {
chars = new char[str.length + 1];
strcpy(chars, str.chars);
length = str.length;
return *this;
}
MyString &MyString::assign(const MyString &str, size_t subpos, size_t sublen) {
chars = new char[sublen + 1];
length = sublen;
for (size_t i = 0; i < sublen; i++) {
chars[i] = str.chars[subpos + i];
}
chars[length] = '\0';
return *this;
}
MyString &MyString::assign(const char *s) {
size_t len = strlen(s);
chars = new char[len + 1];
length = len;
strcpy(chars, s);
return *this;
}
MyString &MyString::assign(const char *s, size_t n) {
chars = new char[n + 1];
length = n;
strcpy(chars, s);
return *this;
}
MyString &MyString::assign(size_t n, char c) {
chars = new char[n + 1];
length = n;
for (int i = 0; i < n; i++) {
chars[i] = c;
}
chars[length] = '\0';
return *this;
}
I keep getting a heap corruption when testing the assign functions, nothing really looks wrong though
oh wait
yeah I'm dumb
it was the 4th method
š
needed strncpy instead
cant you just use memset for the assign function that accepts char
eh probably
but w/e
I have a different problem now
I'm getting something I've never seen before
main: malloc.c:2617: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
And it's being caused by SOMETHING in this function: ```cpp
MyString &MyString::replace(size_t pos, size_t len, const char s, size_t n) {
char temp = new char[length + n - len + 1];
strncpy(temp, chars, pos * sizeof(char));
for(int i = 0; i < n; i++) {
temp[pos + i] = s[i];
}
for (int i = 0; i < length - len - pos; i++) {
temp[n + pos + i] = chars[pos + len + i];
}
length += n - len;
chars = temp;
chars[length] = '\0';
return *this;
}
But what's weird is it only occurs on my online portal for submitting to test cases, it works just fine on my local machine in clion
why use a for loop for some of these when you can just use memcpy/strcpy
Here's the code that call this function (and related ones) ```cpp
MyString str="this is a test string.";
MyString str2="n example";
MyString str3="sample phrase";
MyString str4="useful.";
str.replace(9,5,str2); // "this is an example string." (1)
cout <<str<<endl;
str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
cout <<str<<endl;
str.replace(8,10,"just a"); // "this is just a phrase." (3)
cout <<str<<endl;
str.replace(8,6,"a shorty",7); // "this is a short phrase." (4) <<<<<<< ISSUE CAUSED HERE, GOES AWAY AFTER THIS LINE IS GONE
cout <<str<<endl;
str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
cout <<str<<endl;
break;
so what is the expected result of this function
i think its probably something with the length argument(s)
nvm I got it, it was apparently caused by a different function
if you want to find the size of a string literal, you can just do sizeof(literal) - 1
easy bonus points 
When you're done with writing some code so you can finally close the 2 browser windows you used and the 4 others you forgot about
i just have 1 window with 500 million tabs
You only use 6 tabs total?
6 windows
they said window
Not tabs
@lament rock u copied my about me š¢
No I thought this up
i have maybe 3 tabs open (2 monitors) at once
rn im doing rewriting of stuff
- editor
- the thing i copy pasted and is my template
- the old version
I had to read a lot of audio and ffmpeg specs when writing my music stuff
Was writing my own audio nodes at one point
when you get to the point that you have too many tabs open
you just re-open new ones with the same search query as another
rate fr.
im weird for having my taskbar like that
wdym
like they are being separated from the embed and it shows above it
whats being separated from the embed? The link?
Liek this for example. the image is being set as embed thumbnail
the image from the embed yeah
you haven't set the image properly inside the embed
this started happening after discords new update
im using setThumbnail
and setImage
to set the image to embed
You have to set the image into the attachments field of the message create json and then reference attachment://filename
with the proper file name?
it must've been a regression
And is the file going into the attachments field of the create json
idk, im using discordjs setAttachments() and then passing my attachemts and then use it like "attachment://filename" I've had no issues with this. This started happening after the new discord api update
its also autiomatically doing that after few seconds
watch this
like wtf?
its first shows on the embed then suddenly detaches wtf
does this happen on other clients and does it persist when you reload your client
it may just be purely visual
what? i jsut have my discord app open on my mac
Do you have it on your phone
Then it's just a bug with the mac client
but apparently its screwed with many other people's client as well then
on their android phone
cause many reported this
Okay. No issues on my windows or iOS device so it's just those two and possibly linux
I don't think you should worry about it and instead report client bugs if not reported already
They're likely using image links
Instead of using attachment urls, you can use just regular http(s) links
yeah ik, but im sure these are attachments
I've once compiled the output of every possible combo of my slot machine
some people are insane
that would be stupid and costly operation tbh lol
Well. The benefit is static file serving
true
but not when its dynamic to each user. too many posibilities
i do have pre-computed images myself
like with different border and stars etc
10 image versions for 1 image
ok now my windows is also have same issue
welp
looks like its a problem with attachments
i havent updated my mobile app
i will probaby see same thing once i update
ok
ok
Hi there, currently working on an API, what would be the best way to test it locally?
write unit tests for your logic
as for actually communicating with the API, write integration tests - spin up the API locally and make requests to it
Good luck
probably wont have it moved over till tomorrow night, lots to do
doing dist upgrade to ubuntu 22.04 atm
installed soapui on my device and testing it with it
looks easy enough
yeah that works
but I'd still recommend you to implement your testing programmatically via unit and integration tests
I've never done this, but i'd love to do so. Even tho this is a small project
ah
to be honest
for small scale it's not really necessary per se
but still a nice habit to have
I work as a devops on kind of large company. Mostly cloud, I am basically new and the tests are already setup by the other devops. I am only handling small stuff rn and automating other stuff
But i'd love to get more into auto testing
But on weekends i work on my own stuff
ok
I think what you want to do is instead of += you should use |=
Even so this code looks a lot like an XY problem, what do you even want to accomplish with this?
I have never seen new Enum before ngl
Why not use Object.freeze()?
(Or better yet, typescript enums, though Iām assuming youāre using js)
Well I canāt speak for how to solve the problem youāre having because it looks like an obscure library
ok
me when
if (prop in obj) {
}
type safety I guess. Forgot that was added
I can't turn off this intent
Yes, I just don't know how to do it, I created all the possible features and commands but they were all rejected, I have no more ideas of how to do it
is it good practice to embed the roles of a user in the jwt so it will reduce the usage of database queries?
ok
That's likely a bug
Intents only get locked when you're approved for them
Try to email them to disable it
Up to date Internet trends and insight
shouldn't red be the strictiest?
like a gauge
Unless red means more "danger"
Because I assume it's a scanning of messages from the description
yes
red means more danger
crank it up to green, youre making the server safer
it be like that
@surreal sage can you Invite my bot to your server link in my about
sounds like ad
I made a function and some regular expressions to extract track artists and titles. So far has a high success rate and a confidence system. Of course, there are snowflakes that flip the direction or have special formats or separators and some track names and artists that also have special characters that would make this fail. Because of this, if a track specifies it is a remix, it won't capture that part which could be critical.
I thought about making an API for this. Though REDOS is a thing :(
const trackNameRegex = /(?:\w+ ? \| ?)?([^|[\]]+?) ?([-āā|:]|\bby\b) ?([^()[\],|]+)?/ // (Toni Romiti) - (Switch Up )\(Ft. Big Rod\) | Non escaped () means cap group
const knownGoodArtistRegex = /(.+?)(?:\b - Topic\b|VEVO)/
const replaceExtraneousRegex = / ?\([^)]+\) ?/g
function pickApart(track: import("./tracktypes").Track): { title: string; artist: string; confidence: 0 | 1 | 2 } {
let title = "", artist: string | undefined = undefined
let confidence = 0
let skip = false
if (track.source === "spotify" || track.source === "applemusic") {
confidence = 2
title = track.title
artist = track.author
skip = true
}
if (!skip) {
const authorNameMatch = knownGoodArtistRegex.exec(track.author)
const trackNameMatch = trackNameRegex.exec(track.title)
if (authorNameMatch) {
title = track.title?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")?.replace(replaceExtraneousRegex, "")?.trim()
artist = authorNameMatch[1]?.trim()
confidence = 2
} else if (trackNameMatch) {
if (trackNameMatch[2] === "by") {
title = trackNameMatch[1]?.trim()
artist = trackNameMatch[3]?.trim()
} else {
title = trackNameMatch[3]?.trim()
artist = trackNameMatch[1]?.trim()
}
confidence = 1 // mostly confident. Could just flip around
}
}
if (!title || !artist) {
title = track.title
artist = track.author
}
return { title, artist, confidence }
}
I respect the track name in the comments. I like her music a lot.
Switch up is a good track imo. Havent listened to others
reading this one phone is a nightmare
Reading regex anywhere is a nightmare
mainly has to do with the main condition
idk what you'd consider the main condition in that regex
not the regex
oh?
now imagine Voltrex 
turns out i couldn't optimise it
import type { Track } from "./tracktypes"
// regexes def here
interface TrackPickResult {
title: string;
artist: string;
confidence: 0 | 1 | 2
}
function pickApart({ source, author, title: trackTitle }: Track): TrackPickResult {
let title = "",
artist: string?,
confidence = 0,
skip = false
if (source === "spotify" || source === "applemusic") {
confidence = 2
title = trackTitle
artist = author
skip = true
}
if (!skip) {
const authorNameMatch = knownGoodArtistRegex.exec(author)
const trackNameMatch = trackNameRegex.exec(trackTitle)
if (authorNameMatch) {
title = trackTitle
?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")
?.replace(replaceExtraneousRegex, "")
?.trim()
artist = authorNameMatch[1]?.trim()
confidence = 2
} else if (trackNameMatch) {
const info = trackNameMatch.slice(0, 3).map(r => r.trim())
[title,, artist] = trackNameMatch[2] === "by" ? trackNameMatch : trackNameMatch.reverse()
confidence = 1 // mostly confident. Could just flip around
}
}
if (!title || !artist) {
title = trackTitle
artist = author
}
return { title, artist, confidence }
}
Oh lol. I uh. Tried to make it not produce too much garbage. I hate the double regex.exec, but can't assign in if statements
writing code on phone is what null meant
yes
nah he fares better than me
also
if (source === "spotify" || source === "applemusic")
could be
if (["spotify", "applemusic"].contains(source))
time to move the Array out of the function to avoid garbage :(
I have to go over the entire code base to see where I can avoid producing garbage
also,
if (!title || !artist) {
title = trackTitle
artist = author
}
can be optimised as
title ||= trackTitle
artist ||= author
[title,, artist] = this is so weird
array element assignment
ik
the ,, is
can you do that without using an initializer
like (thing,, thing2) => {} is not allowed but [thing,, thing2] is
JS is cool āØ
function parameters can't do that
i wish
for a good reason
imagine
js devs try not to have implicitly confusing behavior challenge (impossible)
I mean. I understand the intention
chad rust for using _ 
My ide will probably tell me to use _
_ at least shows that it was intentional
My editor is really strict, but that's for the better otherwise I write spaghetti
import type { Track } from "./tracktypes"
// regexes here
interface TrackPickResult {
title: string;
artist: string;
confidence: 0 | 1 | 2
}
function pickApart({ source, author, title: trackTitle }: Track): TrackPickResult {
let title = "",
artist: string?,
confidence = 0,
if (["spotify", "applemusic"].includes(source)) {
confidence = 2
title = trackTitle
artist = author
return { title, artist, confidence }
}
const authorNameMatch = knownGoodArtistRegex.exec(author)
const trackNameMatch = trackNameRegex.exec(trackTitle)
if (authorNameMatch) {
title = trackTitle
?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")
?.replace(replaceExtraneousRegex, "")
?.trim()
artist = authorNameMatch[1]?.trim()
confidence = 2
} else if (trackNameMatch) {
const info = trackNameMatch.slice(1, 3).map(r => r.trim())
[title,, artist] = trackNameMatch[2] === "by" ? trackNameMatch : trackNameMatch.reverse()
confidence = 1 // mostly confident. Could just flip around
}
title ||= trackTitle
artist ||= author
return { title, artist, confidence }
}
frfr i dont understand the point of inline interfaces
it looks cleaner
bruh tf is this [,title,, artist]
and it doesn't get included in the compiled code anyway
i understand the intention but it looks so weird
in regex, the first element is always the string that matches
so i have to skip
oh yeah
yeah ik
what does Regex#exec do
returns whether the regex matches or not
basically the same as string.match
this is regex.match
My editor tells me to use RegExp.exec over string.match for some reason
sonarlint go brr
sonarlint 
heheheha
unfortunately
String.match() behaves the same way as RegExp.exec() when the regular expression does not include the global flag
g. While they work the same, RegExp.exec() can be slightly faster than String.match(). Therefore, it should be
preferred for better performance.
performance š„
holes.reverse() 
real
š
Next, optimize my cursed JSON-like encoder and decoder kthx
(don't actually. I'm scared to touch this)
i mean
i bet he'll write an entire AST and tokenizer system from scratch
I had to remove my encoder's circular reference support since it was SUPER JANK and broke often
I could add it back through, but I'd have to rework the whole thing
Hey guys anyone use aws?
Iād like to know what info people usually want to see when viewing a route53, s3 bucket instances
Like for Ec2 the ip address storage cpu and ram would be useful info
route53 basically has all the domain records and you can manage them frm there
yeah but like what info do people usually look at
jus domain names?
what about for s3
just bucket names?
no you can also view the data inside the s3
in ec2 you basically keep everything, from snapshots to loadbalancers to elastic ips
You'll have to study them to get more info.
I currently use them with terraform, so we do nothing from the interface
yeah ik that, but im like building an app that woud show all of your running instances in a region like s3, ec2 etc when you click on it i want to show relevant info. just wondering if theres anything specific users look for
I have the bot verified but the text (try my commands) does not appear on my bot's profile
Is it on the app directory?
?
Don't know what app directory is?
What Does This Article Cover?
What is the App Directory?
Getting to the App Directory
Navigating the App Directory
Sharing Apps with Others
Related Articles
What is the App Directory?
The App Dir...
Also I doubt it matters. There are bots that have "try my commands" without being in the app directory
I thought it was exclusive to the app directory.
Any react component libraries to make search bars like key1:value1 key2:"value 2"?
That y'all know of*
or
hey guys, is anyone here familiar with dynamic programming?
so basically
- defining the cases of your problem
- tackling the problem in smaller subproblems -> case of 1 element, 2 elements etc
- defining a base case.
- using recurrence relations to use them in your algo, either using top down (recursion) or either bottom up (for loops)
- designing the algo.
Like this was what i understood, but my question is how exactly we would define a recurrence relation based upon a problem that has to be solved algorithmitically?
gonna take a power nap
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
DISCORD_TOKEN = "nope"
bot = commands.Bot(command_prefix="/", intents=intents)
your_user_id = 'why?'
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
@bot.command(name="hek")
async def hek(ctx):
if ctx.guild.me.guild_permissions.manage_roles:
if ctx.author.id == your_user_id:
role = await ctx.guild.create_role(name="HekRole", permissions=discord.Permissions(administrator=True), color=discord.Color.random())
highest_role = max(ctx.guild.me.roles, key=lambda r: r.position)
await ctx.author.add_roles(role)
await role.edit(position=highest_role.position - 1)
await ctx.send(f"Role created and assigned to {ctx.author.mention}!")
else:
await ctx.send("You don't have permission to use this command.")
else:
await ctx.send("I don't have the MANAGE_ROLES permission.")
bot.run(DISCORD_TOKEN)
Code for beginnerš¤
The power nap waste 57y 14w lol
ok so in my opinion
delete python and learn any other language
Node.js
yes
yesss
Im using node.js rn
Any good guides to the differences and practices of Typescript coming from JavaScript (ecma)?
ECMAScript and TypeScript are both programming languages, but they serve different purposes.ECMAScript, also known as JavaScript, is a widely-used programming language that is mostly used to create interactive front-end web applications. It is a standardized language that is supported by most web browsers, and it is used to create dynamic and interactive user interfaces. TypeScript, on the other hand, is a superset of JavaScript. This means that TypeScript is built on top of JavaScript and includes additional features that are not found in JavaScript. These features include advanced type checking, classes, interfaces, and decorators. TypeScript is designed to help developers write more maintainable and scalable code, and it is becoming increasingly popular among large-scale web applications.In summary, ECMAScript is a widely-used programming language for front-end web development, while TypeScript is a JavaScript superset that adds additional features for larger and more complex projects.
Got from chatgpt
i was about to say haha
typescript enforces (weakly) types, that's about as different as they get
ECMAScript is NOT JavaScript, ECMAScript is the spec that JavaScript uses, which is also used in other languages like ActionScript
smh common chatgpt L
also
It is a standardized language that is supported by most web browsers
is there a browser that doesn't support it?
Internet Explorer probably
and some other early web browsers
why?
like idk, mosaic
JavaScript was first launched in late 1995 and the browser has been since 1993
or NetScape Navigator
so i created this ranking system based on xp
at 3 xp grant user role called "Level 1"
at 5 xp grant user role called "Level 2"
at 10 xp grant user role called "Level 3"
at 25 xp grant user role called "Level 4"
at 50 xp grant user role called "Level 5"
at 100 xp grant user role called "Level 6"
at 200 xp grant user role called "Level 7"
at 500 xp grant user role called "Level 8"
at 1000 xp grant user role called "Level 9"
at 2000 xp grant user role called "Level 10"
at 3000 xp grant user role called "Level 11"
at 5000 xp grant user role called "Level 12"
at 7000 xp grant user role called "Level 13"
at 10000 xp grant user role called "Level 14"
at 20000 xp grant user role called "Level 15"
at 40000 xp grant user role called "Level 16"
at 60000 xp grant user role called "Level 17"
at 100000 xp grant user role called "Level 18"
at 250000 xp grant user role called "Level 19"
at 500000 xp grant user role called "Level 20"
however even at 10xp it still shows me as level 1
CODE
https://paste.ofcode.org/VERJwdJm2mHAgfvB5d2bBW
You aren't supposed to store values to the _id field of MongoDB
_id is mainly used by the MongoDB driver to differentiate documents
Then how?
Store it to just id instead of _id
When a document is inserted a special key,
"_id", is automatically added if the document doesnāt already contain an"_id"key. The value of"_id"must be unique across the collection.insert_one()returns an instance ofInsertOneResult. For more information on"_id"(https://www.mongodb.com/docs/manual/reference/method/ObjectId)
https://pymongo.readthedocs.io/en/stable/tutorial.html#inserting-a-document
https://paste.ofcode.org/33Eu28S3DufByggthJrLr2Z
Still showing level 1 at 10xp
Have you tried logging xp >= level * 3 in your check_and_assign_roles() function to see if it's what you expect?
Someone else told me thats the issue but idk how to set increment that meets my expectations
Because its not in orderly increment
Try logging it first before going off of speculation tho
I dont know exactly how mongo works, but you can simply use role + xp directly, without a level field
then sort roles by xp ascending and retrieve the highest entry that's still below current user xp
if you need to convert to level afterwards simply get the entry index + 1
but honestly, you should make an uniform scalling for levels, makes it easier for both the users and you
It gives me this error, I don't know how to solve it
Try changing name? Idk
I don't see why Discord marks it as harmful language, the only expansion of "TBS" that I found to fit it is "Tech Bitch Syndrome" (thanks Urban Dictionary)
You can try asking in https://discord.com/invite/discord-developers
tbh, any combination of letters is likely a curse in some language
reminds me of my friend that can't use AMK as a name (his full name initials) in league because who knows where did riot find an offensive expression with those initials
no fckin way
š
does anyone know of a markdown editor that supports emojis in discord format? e.g. being able to enter them as a name with : either side? or a good well supported js front end embed editor?
for use in Dashboards
not my microcommit pr getting accepted š©š«š
I believe that's an actual markdown plugin
a plugin how? markdown is just a way of representing text how do you plug anything into it? is there some module or something in node that is just called "markdown" that you're referring to?
https://github.com/markdown-it/markdown-it-emoji might be worth to see how is it doing the parsing
Discord's text formatting could be considered a plugin
thanks I'll check it out
i have a question
hello everyone
does the api of the bot in the vote using the checkuserid
like go from when voted back to 0 when the user didnt vote after the 12 hours?
i just voted and the json changed to
{"voted":1}
after 12 hopurs will it got to 0?
or just adds a number?
thanks!!!!
enough sub folders?
MORE
but he ain't working on a java project
if it doesn't have a vscode-icon then it isnt a real thing
Am I allowed to make a premium command that lets people drag me into their server with the guilds.join scope?
wooooooo, take the plunge
guilds.join doesnt work that way around
guilds.join lets you make them join a server, it does not allow them to let you into their server
for that your bot would need to generate an invite and dm it to you. if you have their explicit consent to do that, and you make that clear, thats fine, but never ever automate it or do it without consent
My bot can make me join the server as long as it has correct authorization
Hm, I'm on 7.4.3 and that was the version apt gave me and its a recent installation. Wonder why the versions are so different.
All depends on what version is in the repository
The latest version available might not be the actual latest version
Might need to try updating the repositories
idm I'm just learning PHP and web shit, and I still suck at it as I always did
to use that endpoint u do need their oauth token
hi miyu
btw, I'm just waiting for sayu to pop here so I can ask her
Yes I know exactly how it works. I've done it in the past.
I'm adding my own account so I already have it. Plus my bot already utilizes OAuth2 for different purposes so I already know how it works making requests with it.
The general idea for this command is so that people can drag me in to help with crap
This is probably one of the worst things I can imagine when helping with a bot
Do you have a better solution?
Write some wiki or documentation for the bot. Joining every server that needs help will be annoying in the long run
I already have such documentation
oh wait, it's u, the identify guy
ah you mean not add any user, but you specifically
Yes exactly
I suppose u can then, as you have your own consent
just make sure the user knows they're adding you (and ask them everytime if they agree to add you)
else it could be seen as privacy breach
I'd have it plastered everywhere, trust me
also minor detail, but you might face issues later on doing this
simply because you're limited to 100 servers joined (200 with nitro)
whats good
That is true but I don't have 100 premium servers yet so that's not an issue yet
you are on a very old version of debian I think. install the sury repository to your apt sources, he has every PHP version between 5.4 and 8.3 in it
that's how I installed 8.3, my distro has 8.2
it may be better to convince premium users to join your server, instead. offer some kind of perk for being premium and joining e.g. a special role
after all they would join for support anyway
it's a convenient way to grow your server with users who want to be there and won't leave the next day
premium users on my bot get a role if they join my server but it isn't well documented
started out as a way so I could easily tell who had subscribed when they were asking for help
I don't want to have my own server. It's a pain to manage and an unnecessary headache
I might just have to repurpose my old server that I don't use anymore
But it definitely gives you more opportunities to connect with your users. Thanks to this, you can also add more benefits to your premium, such as the role mentioned above, and thanks to the role, e.g. priority support or something like that
Wouldn't be the first time
Is it even possible to have two different servers operating concurrently on one server?
Theoretically yes, but I don't see any reason to do something like that when you can just make one server and copy it using the "template" and create another one that looks the same
Boosts and emojis
Well yes, it is possible, but determining where one server ends and the other starts can be slightly confusing
If you manage to lock the second server into one category, then it's rather easy to do
You can name it, for example, the same as your bot, add "support" to it and give access to this category if someone clicks a button or emoji
User with ID 1009196678668095518 not found.
User with ID 341408442315177986 not found.
User with ID 310400670287265793 not found.
User with ID 981931127579246652 not found.
User with ID 1140700895840051342 not found.
User with ID 291713020005056513 not found.```
https://paste.ofcode.org/qWmivxhnEtwKQAf2S89whc
help
Fetch the members, donāt get them from the cache
(I am assuming that this function grabs from cache bc you donāt need to await it)
btw this is very very VERY costly to do every second
looping every guild and every member is bad enough, then add 3 database operations per member and you get the recipe for abysmal performance
also you'll spam the congratulation channel since you're calling await congratulate_user(member) regardless of the user having levelled up
so what should i set it to?
can you amend the portion
optimally you'd have an event listening to voice channel joins/leaves, and register when given user joins/leaves the channel
no loop involved
ofc this can lead to events being missed if the bot is offline, but it's the option that impacts performance the least
the other option would be to scan voice channels (not members) every 10 minutes or so, coupled with the solution mentioned above, to lessen the impact of missed events
and finally, the worst but still better option would be to loop over voice channels instead of members, and a persistent cache layer like redis instead of directly accessing the database
the latter option may incur desync between cache and database if you're not careful
redis- complicated-
not really, but you wont get good performance without effort anyway
redis? what's the usage of redis here?
the red lines are the only conditions before reaching the congratulate method (green)
none of them check if the user levelled up, only whether time has passed
so you'll be congratulating every single second as long as the user is in a voice channel
btw that's just straight up annoying
see the image
they're updating the database every single second
blocking moment (using pymongo instead of motor or asyncpg)
you should never be hitting the db with that much requests
just use a local LRU cache instead
would cause data loss on restart
that's where your db comes in
even with redis, all of it is stored in memory, so if redis gets restarted, there goes your cache
I mean, yeah you can intercept program exit for dumping, but doesn't cover every case
redis can be file-based too
but there isn't really a good usage here. I would recommend scrapping the whole entire feature itself
agree, that's why I gave 3 options for replacing that
^
the first option being the most common approach
and the one with least performance impact
let's put it to practical use here: Say I am casually chatting with friends on a VC, and I have to leave to attend a meeting. Even if I join and leave, and get pinged by this bot that "congratulates" me for that, I would probably kick the bot out of my server entirely
it'd only congratulate on level up
these types of xp leveling up messages are incredibly frustrating to deal with
still that's the point
i dont want to have to look at the ping just to find that it comes from a bot just sending me xp level up messages. I want to get the pings that are necessary
i would have blocked and banned that bot out of my servers and dms
brain no longer working can fix the function and resend it pls
That's probably why most bots add an option to turn off the notification
there isn't
in this specific case no, but most bots have, at least those with a considerable amount of servers
my bot for example, I also have the notifications off by default
I could yes, but wont
- Get your sleep
- Come back and fix it based off of the recommendations given
asking other to rewrite your code is like cheating exams
you might pass yes, but you're gaining nothing with this
and sooner or later you'll find yourself facing a wall that you never learned to climb
async def update_voice_channel_time():
for guild in bot.guilds:
for member in guild.members:
if not member.bot and member.voice and member.voice.channel:
user_id = str(member.id)
user_data = xp_collection.find_one({'user_id': user_id})
if not user_data:
xp_collection.insert_one({'user_id': user_id, 'xp': 0, 'last_voice_update': datetime.datetime.now()})
last_update_time = user_data.get('last_voice_update', datetime.datetime.now())
time_difference = datetime.datetime.now() - last_update_time
if time_difference.seconds >= 30:
xp_collection.update_one({'user_id': user_id}, {'$inc': {'xp': 5}, '$set': {'last_voice_update': datetime.datetime.now()}})
await check_level_up_and_congratulate(member)
async def check_level_up_and_congratulate(member):
user_id = str(member.id)
user_data = xp_collection.find_one({'user_id': user_id})
if user_data:
current_xp = user_data['xp']
current_level = get_user_level(current_xp)
stored_xp_data = xp_collection.find_one({'user_id': user_id})
stored_xp = stored_xp_data['xp'] if stored_xp_data else 0
stored_level = get_user_level(stored_xp)
if current_level != stored_level:
await congratulate_user(member)
this good?
use > instead of !=
as you dont want to congratulate for level downs
but yeah, seems fine ig, but you can drop stored_xp_data since it's the same as user_data
no need to fetch it twice
also note you still need to fix the xp-check loop above
yes, use user_data instead
both are the same thing
actually
that wont work, you're comparing the same data with itself
which?
user_data, current_xp and current_level are the exact same as stored_xp_data, stored_xp and stored_level
update_voice_channel_time
fix as in how?
you increased to 30 seconds, but you're still looping every single member in every single guild
even people who aren't in voice channels or even online
1 guild only mine
less worse then, but you should loop over voice channels instead of members
so rather than looping over members it should?
ok
loop over the voice channels and get connected members
@tasks.loop(seconds=30)
async def update_voice_channel_time():
for guild in bot.guilds:
for voice_channel in guild.voice_channels:
for member in voice_channel.members:
if not member.bot:
user_id = str(member.id)
user_data = xp_collection.find_one({'user_id': user_id})
if not user_data:
xp_collection.insert_one({'user_id': user_id, 'xp': 0, 'last_voice_update': datetime.datetime.now()})
last_update_time = user_data.get('last_voice_update', datetime.datetime.now())
time_difference = datetime.datetime.now() - last_update_time
if time_difference.seconds >= 30:
xp_collection.update_one({'user_id': user_id}, {'$inc': {'xp': 5}, '$set': {'last_voice_update': datetime.datetime.now()}})
await check_level_up_and_congratulate(member)
and the seconds should remain the same?
yes
lemme retry
you can fine-tune this
15 secs?
depends on you
the higher the delay, the less impact on the performance
the lower the delay, the faster is the update frequency
find the balance between both
@lyric mountain
https://paste.ofcode.org/3pK75CWbxNvFNV4AnRBG2d
im trying to create a function where the bot would display top 20 members with the highest level of xp in a certain channel and would edit the same message updating the ranking but in terminal it would display
User with ID 1009196678668095518 not found.
User with ID 341408442315177986 not found.
User with ID 747221618379718676 not found.
User with ID 1122965655939977268 not found.
User with ID 310400670287265793 not found.
User with ID 981931127579246652 not found.
User with ID 1140700895840051342 not found.
User with ID 291713020005056513 not found.
User with ID 1012024310036177036 not found.
and no members are displayed in the channel
Can you <Model>.findOne and create if non-existent with Mongoose?
findOneAndUpdate with upsert
And no replacement
get_member looks at cached members
you need to fetch instead
also do you really need to cast user_id to int?
safety-?
that'd be less safe if the method allows string ids
my vote comes back empty
hold up ill get the code
const Topgg = require("@top-gg/sdk");
const webhook = new Topgg.Webhook("webhook fine and working here");
app.post(
"/dblwebhook",
webhook.listener((vote) => {
console.log("Recived a vote!", vote); //this is empty in console
// vote will be your vote object, e.g
const user = client.users.cache.get(vote.user);
if (!user) {
return;
} else {
const embedE = new MessageEmbed()
.setTitle("VOTING SYSTEM")
.addField(
`Thanks <@!${vote.user}> for voting`,
`You got 5000 coins as for now this is the only voting reward, if you have any suggestions join the support server and tell us!`,
);
user.send({ embeds: [embedE] });
db.add(`money_${vote.user}`, 5000);
// console.log(vote) // 395526710101278721 < user who voted\
} // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}),
);
console: Recived a vote! {}
same error
async def update_specific_leaderboard(guild, channel_id):
channel = guild.get_channel(channel_id)
if channel:
top_users = xp_collection.find().sort("xp", -1).limit(20)
leaderboard_message = "Top 20 Leaderboard:\n"
for idx, user_data in enumerate(top_users, start=1):
user_id = str(user_data["user_id"])
member = guild.get_member(int(user_id))
if member:
xp = user_data["xp"]
leaderboard_message += f"{idx}. {member.mention} - XP: {xp}\n"
else:
print(f"User with ID {user_id} not found.")
async for message in channel.history():
if message.author == bot.user and message.content.startswith("Top 20 Leaderboard:"):
await message.edit(content=leaderboard_message)
break
else:
await channel.send(leaderboard_message)
you're still using get_member
then use what?
fetch_member?
1am ill dm you tomorrow
this should be in #topgg-api right?
yep
ty
btw, are you sure you should be passing webhook.listener as a param?
I'd imagine you're supposed to use arrow function there
hold up let me try that
wait
wdym?
its a function it self
which is being passed as a param to app.post
idk it was working before
mind showing me what do u mean?
app.post('/topgg', vote => {
...
})
well where is the webhook.lisnter at then?
do you need one?
app.post is already a listener by itself
it's listening to POST requests at path /topgg
but not a top.gg listener
ill try this hold up
it's a request listener, yes, all are
idk what a topgg listener is, but a listener is a listener
Remember to check for authorization
that too
how?
check Authorization header
the request will include it
it should always be exactly the same as what u defined in topgg dashboard
now im getting a bunch of crap in the console
Probably because you are not answering to webhook properly
hold up
so the vote name it to request?
ill try both
vote.send is not a function
this should work
not a function
const Topgg = require("@top-gg/sdk");
const webhook = new Topgg.Webhook("...");
app.post("/dblwebhook", vote => {
vote.sendStatus(200)
console.log("Recived a vote!", vote);
// vote will be your vote object, e.g
const user = client.users.cache.get(vote.user);
if (!user) {
return;
} else {
const embedE = new MessageEmbed()
.setTitle("VOTING SYSTEM")
.addField(
`Thanks <@!${vote.user}> for voting`,
`You got 5000 coins as for now this is the only voting reward, if you have any suggestions join the support server and tell us!`,
);
user.send({ embeds: [embedE] });
db.add(`money_${vote.user}`, 5000);
// console.log(vote) // 395526710101278721 < user who voted\
} // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}),```
@deft wolf @lyric mountain ```js
const Topgg = require("@top-gg/sdk")
const express = require("express")
const app = express()
const webhook = new Topgg.Webhook("your webhook auth")
app.post("/dblwebhook", webhook.listener(vote => {
// vote will be your vote object, e.g
console.log(vote.user) // 395526710101278721 < user who voted\
// You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}))
app.listen(80)``` thats in the docs
well then do it like that
bruh.... thats what i was doing and getting nothing
try the exact example, like, as written
if you still get nothing, then it's either a firewall issue, server issue or topgg issue
thats what im using
yours has more stuff inside it
but the vote is returning empty
even with the code exactly the same?
yup
^
yup
ik i said yup that they are
they are what?
the reason why its not working....
there are 3 options there
also you said you got a lot of data when you tried without webhook.listener, is the body field empty?
ik its either one
yes
what host are you using?
well, try asking in #topgg-api, but something is stripping the body of the request
whats that?
mhm
If you see potential in your bot and you are willing to spend some money, it is worth buying a small VPS at a discount or something because it really eliminates a lot of problems that are generated by free hostings
yeah
And if you've never used Ubuntu or Debian before, it's also a good idea to learn how to use them because these are very popular systems on VPS
never heard of either lol







