Well, you can find the Nth line of $query($nick) with $line( $nick,N) and $line($Nick,0) tells you how many lines there are in the window. So since you want the last line, you want N to be the total number of lines. So:

//echo -a $line( $nick , $line($nick,0) )

Note that this works only if there is at least 1 line of text in the window, or else this returns 0.

Here's another option you can do instead. If you're doing a random 4-digit number, I assume you're doing something like $rand(1000,9999). You can instead do something that changes the number every 30 seconds, makes it be a 9 digit number by default, and you can even make it nick-specific so it can't be used by the bot to invite all its friends to query you.

//echo -a $totp(any secret $nick)

The catch with this method is that this changes every time the clock goes into a different 30-second window, so if you give them the code with 1 second left, they don't have time to reply. But you can cut down on that by making the time window be larger. This example makes the number change every 900 seconds, aka 15 minutes.

//echo -a $totp(any secret $nick,$ctime,sha256,6,900)

You can make this be an hourly code by changing 900 to 3600 in all versions recognizing this identifier, and in the newest version you can make it be a code that changes every 48 hours. enjoy!