Hey everyone! I’m working on a Discord bot and I’ve got the basics down for sending a single image or GIF when someone uses a command. But now I want to take it to the next level and make my bot choose randomly from a collection of different images and GIFs each time the command gets triggered.
I can handle the simple case where it’s just one file, but I’m stuck on how to implement the random selection part. Should I store all the image URLs in an array or is there a better approach? Also wondering about the best way to pick a random item from whatever storage method I use.
Any tips or code examples would be super helpful. Thanks in advance!
I’ve been managing a Discord bot that features random images for about eight months. Storing URLs in arrays is efficient, but I recommend categorizing the images rather than lumping them all together. For instance, use separate arrays like catImages and dogImages. To select a random image, use Math.floor(Math.random() * array.length), which works well. However, keep an eye out for broken links, as I faced this issue and it can cause silent failures in your bot. It’s always a good idea to validate links before you add them. Additionally, consider backing up your URL arrays in a separate file; it’s a hassle to rebuild if something goes wrong. Once you have around 100-200 images per category, switching to a simple JSON file simplifies adding new content.
I’ve built several Discord bots and honestly prefer text files over hardcoding arrays. I create a .txt file with one URL per line, then read it into an array when the bot starts. Super easy to add new images without touching code - just edit the file and restart.
Random selection works the same with Math.random(), but external files let non-technical mods add content too. Learned this the hard way after constantly getting requests for new images and having to redeploy every time.
Bonus: you can have multiple themed files like reactions.txt, memes.txt, etc. and load them into separate arrays for different commands.
ya arrays r def the way to go! just throw all ur image links in there and use Math.random() to grab one. i do it like images[Math.floor(Math.random() * images.length)] and it works perfectly. been doing this for a while, super easy!