如何从机器人调用外部REST API并传入用户输入参数?
Hey there! Let's walk through how to implement calling a REST API from your bot, passing user input as request parameters to fetch sample data. Here's a practical, step-by-step breakdown:
First, you need to extract the relevant parameters from what the user sends to your bot. The exact method depends on your bot framework, but here's a simple Python example for a basic chat bot setup:
# Assume this is the raw input received from the user user_input = "Get sample info for product_id 456" # Extract the parameter (use regex or string splitting based on your use case) import re match = re.search(r'product_id (\d+)', user_input) if match: product_id = match.group(1) else: # Handle missing/invalid parameter scenario bot_response = "Could you please provide a valid product ID?"
Next, build your API request with the extracted parameter. REST APIs typically accept parameters either as query strings (for GET requests) or in the request body (for POST/PUT).
Example: GET Request with Query Parameters
Using Python's requests library:
import requests api_url = "https://your-web-service.com/api/sample-info" # Pass the parameter as a query string params = {"product_id": product_id} try: # Add timeout to avoid hanging on network issues response = requests.get(api_url, params=params, timeout=10) response.raise_for_status() # Trigger error for HTTP status codes ≥400 except requests.exceptions.RequestException as e: bot_response = f"Oops, failed to fetch data: {str(e)}"
Example: POST Request with Body Parameters
If your API expects parameters in the request body (common for POST operations):
payload = {"product_id": product_id} headers = {"Content-Type": "application/json"} try: response = requests.post(api_url, json=payload, headers=headers, timeout=10) response.raise_for_status() except requests.exceptions.RequestException as e: bot_response = f"Oops, failed to fetch data: {str(e)}"
Once you get a successful response, parse the data and format it into a user-friendly message for your bot to send back:
if response.status_code == 200: sample_data = response.json() # Format data into a readable response bot_response = f"Here's the sample info for product {product_id}:\n" bot_response += f"- Name: {sample_data.get('name', 'N/A')}\n" bot_response += f"- Category: {sample_data.get('category', 'N/A')}\n" bot_response += f"- Price: ${sample_data.get('price', 'N/A')}"
Don’t overlook these scenarios to make your bot more robust:
- User provides invalid or missing parameters (add clear prompts to guide them)
- API returns error responses (use try/except blocks to catch and communicate issues)
- Network timeouts or connectivity problems (always set a timeout on your requests)
This approach works across most bot frameworks—whether you’re using Discord.py, Slack Bolt, Microsoft Bot Framework, or a custom bot. Just adjust the input parsing and response formatting to match your framework’s conventions!
内容的提问来源于stack exchange,提问作者hamza barhoun




