Build With Me: Discord State Bot
The Community Manager Bot
In this build, we are creating a stateful Discord/Telegram bot. Most bots are stateless (they reply to a single command). We are building a bot that remembers conversation history and walks a user through a multi-step onboarding process.
Step 1: The State Machine
We need a dictionary to remember what step each user is currently on.
user_state = {}
# States
STATE_WAITING_NAME = 1
STATE_WAITING_EMAIL = 2
STATE_DONE = 3
def handle_message(user_id, message):
# If new user, start onboarding
if user_id not in user_state:
if message == !onboard:
user_state[user_id] = {step: STATE_WAITING_NAME}
return Welcome! What is your full name?
return Type !onboard to begin.
# Get their current step
step = user_state[user_id][step]
Step 2: Routing the Logic
Now we route the user's message based on what the bot is expecting next.
if step == STATE_WAITING_NAME:
# Save their name to their state profile
user_state[user_id][name] = message
# Move to next step
user_state[user_id][step] = STATE_WAITING_EMAIL
return f"Nice to meet you, {message}. What is your email address?"
elif step == STATE_WAITING_EMAIL:
if @ not in message:
return "That doesn't look like a valid email. Try again."
user_state[user_id][email] = message
user_state[user_id][step] = STATE_DONE
name = user_state[user_id][name]
return f"Registration complete! Saved {name} with email {message}."
elif step == STATE_DONE:
return You are already registered!
Your Turn: Copy this logic into the Chatbot Sandbox on the right. Deploy the bot, and type !onboard in the chat window to test your state machine!
Objectives & Tasks
Review the tasks below and follow the interactive instructions to complete this module.
Clearance Required
Interactive sandbox environments consume dedicated compute resources and are restricted to authenticated operators.
Sign InKnowledge Check
Ready to test your understanding of Build With Me: Discord State Bot?