Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice Exercises: Bot Problems with Solutions

Six hands-on bot exercises with runnable solutions: quoted command arguments, leaderboards in SQL, idempotent updates, pagination, HMAC webhooks and splitting long messages.

Reading about bots teaches you the ideas. Solving small, realistic problems teaches you where the details bite. These six exercises each come from something every bot ends up needing. For each one, read the problem, try to write your own solution in an empty editor first (even ten minutes of trying helps), and only then open the solution and compare. Every solution runs, and each includes checks that print what to expect.

The exercises use only plain Node.js, so they run right here. The skills they exercise were introduced in this chapter and the earlier ones: state, storage, webhooks, security and architecture.

Exercise 1: quoted arguments

Problem. Users type /note "buy oat milk" high or /note groceries low. Write parseArgs(text) that returns the command and a list of arguments, where double quotes group words, \" inside quotes is a literal quote, and an unterminated quote returns an error instead of crashing.

Hint. Walk the string one character at a time with a small state: inside quotes or not.

Node.js Solution 1: tokenizer with quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The started flag is what lets an empty quoted string "" count as an argument.

Exercise 2: a leaderboard with ties

Problem. A table xp(guild_id, user_id, points) holds scores. Write the SQL for "top 3 in guild g1" that shows rank with ties sharing a rank (two users with 50 points are both rank 2, and the next is rank 4), and "my rank" for one user.

Hint. SQLite supports window functions. RANK() leaves gaps after ties.

Node.js Solution 2: RANK() in SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the filter WHERE guild_id = ? happens inside the window query, so ann in g2 never affects g1 ranks.

Exercise 3: idempotent update handling

Problem. A webhook may deliver the same update twice and sometimes out of order. Write makeUpdateGate() that returns shouldProcess(update_id): false for duplicates, true for new ones, and which stays memory-bounded by remembering only the last 1,000 IDs.

Hint. A Set plus an array (or a Map in insertion order) lets you drop the oldest.

Node.js Solution 3: a bounded dedupe gate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last 2 is processed again because it was evicted: the bound trades perfect memory for bounded memory. For payments or anything where a repeat is harmful, store the update ID in the database inside the same transaction as the effect.

Exercise 4: pagination

Problem. /items shows a list of 23 items, five per page, with Previous and Next buttons. Write page(items, n, size) returning the visible lines and the callback data for the two buttons (null when there is no such page), keeping callback data under 64 bytes.

Node.js Solution 4: page slicing and button data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Clamping matters: a button from an old message may ask for a page that no longer exists after items were deleted.

Exercise 5: verifying an HMAC webhook

Problem. Many services (code hosts, payment providers) call your bot's endpoint with a header such as X-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body using a shared secret. Write verifySignature(rawBody, header, secret) that is safe against timing attacks and returns false for malformed headers.

Node.js Solution 5: HMAC-SHA256 verification

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same shape as the Telegram and Discord checks you wrote earlier: verify the raw bytes before parsing, compare in constant time, and answer 401 when it fails.

Exercise 6: splitting long messages

Problem. Telegram messages are limited to 4,096 characters and Discord messages to 2,000. Write splitMessage(text, max) that splits on line breaks where possible, never exceeds max, and breaks a single over-long line at the limit.

Node.js Solution 6: a message splitter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Count characters the way the platform does. Telegram counts after entity parsing; Discord counts UTF-16 code units like JavaScript's length, except for some emoji edge cases, so leave a safety margin (for example 1,900).

What to do next

  • Combine two exercises: a paginated /leaderboard that uses exercise 2's query and exercise 4's button data.
  • Add exercise 1's tokenizer in front of the registry in command handler architecture.
  • Write tests for each solution using the pattern from testing bots with fakes.
  • Build your own project: a trivia bot, an expense splitter, a ticket system, a standup collector. Start with the state model, then the commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which SQL function gives tied scores the same rank and leaves a gap afterward?

    RANK() gives equal values the same rank and skips the next rank numbers; ROW_NUMBER() never ties.
  2. 2. Why clamp the requested page number in pagination?

    Data changes after a message is sent, so a stale button can ask for an out-of-range page.
  3. 3. In the HMAC solution, why is the comparison done with timingSafeEqual?

    Early-exit string comparison can reveal how many leading bytes matched.
  4. 4. What is the trade-off of remembering only the last N update IDs?

    An evicted ID is forgotten, so for harmful repeats store IDs durably in the same transaction as the effect.

Summary

  • Tokenize arguments with a small state machine so quotes and escapes work.
  • Use window functions for ranks; filter by guild inside the query.
  • Bound dedupe memory, and make high-stakes operations durable and idempotent.
  • Clamp pagination, verify HMACs in constant time and split messages at line boundaries with a margin.

Next: back to the track overview