Discord.js have bot take in input from a user posting digit string

Viewed 71

I'm trying to work on a bot that allows a user to use the prefix (!) and then type in a random digit string (ex !1234) which then the bot will use as an input to add into a website url to find an image. I'm new to js so I'm not really sure how to do it so if anyone could point me in the right direction that would be great!

Person types: !1234 Bot responds with: https://youtube.com/1234

1 Answers

This is simple with regex. You just search for an exclamation mark followed by a number.

let str = '!1234'; //message content
let chosenNum = str.match(/!\d+/)?.[0].slice(1); //1234
//to send
<channel>.send(`https://youtube.com/${chosenNum}`)

If you want a certain amount of digits use this

let chosenNum = str.match(/!\d{1, 4}/)?.[0].slice(1)
//1 is min, 4 is max

Another way you can do this, you will have to do some checks before doing this or it could have some unexpected results

if(parseInt(msg.content.slice(1)) != msg.content.slice(1)) return;
let chosenNum = msg.content.slice(1);
Related