Building Simple Command-Based Bots
TL;DR
You'll learn how to make a bot that responds to specific text commands. This involves listening for messages, checking if they start with your command prefix, and then performing an action based on the command. It's a fundamental skill for building interactive bot experiences.
1. The Mental Model
Think of your bot as a really simple digital assistant. It patiently waits for someone to say a special "trigger word" (its command prefix), then it listens closely for a keyword (the command), and finally, it tries to follow those instructions.
2. The Core Material
Building a command-based bot boils down to three main steps:
1. Listen for messages: Your bot needs to be constantly watching for new messages in its chat environment.
2. Identify commands: When a message comes in, your bot checks if it's meant for it. This usually involves looking for a specific starting character (the command prefix) like ! or /.
3. Execute actions: If it finds a command, your bot needs to figure out what that command means and then do something in response.
### Setting Up Your Bot's Environment
Before you write any command logic, you'll need to set up your bot. This usually means installing a library for your chosen platform (e.g., discord.py for Discord, python-telegram-bot for Telegram) and connecting your bot using an API token.
Here's a basic Python example using a hypothetical BotFramework (this isn't real code, just for illustration, but shows the structure):
import bot_framework # This would be your actual bot library
# Your unique token from the bot platform
BOT_TOKEN = "YOUR_SUPER_SECRET_TOKEN"
COMMAND_PREFIX = "!" # This is what makes your bot listen
bot = bot_framework.Client()
@bot.event # This decorator tells our framework this function handles an event
async def on_ready():
print(f"Bot connected as {bot.user}")
@bot.event
async def on_message(message):
# Don't let the bot reply to its own messages, or you'll get an infinite loop!
if message.author == bot.user:
return
# More logic goes here!
bot.run(BOT_TOKEN)
### Processing Commands
Once your on_message handler is set up, you'll add the command processing logic. You'll check for the prefix, then extract the command and any arguments.
```python
Inside your on_message function from the previous example:
if message.content.startswith(COMMAND_PREFIX):
full_command = messa