基于Discord.NET开发医生Discord Bot:实现WebMD症状搜索回复
Alright, let's tackle adding that WebMD symptom search feature to your existing Discord bot. I've built a few similar health-focused bots before, so here's a practical, step-by-step implementation plan that should work smoothly.
整体实现 Overview
Your bot will:
- Listen for the
!Doc symptoms [症状列表]command - Parse the user's symptom input
- Fetch and scrape relevant diagnostic content from WebMD
- Format the results into a user-friendly reply
Step-by-Step Implementation
1. Install Required Dependencies
First, make sure you have these packages installed (assuming you're using discord.py for your bot):
pip install discord.py requests beautifulsoup4
discord.py: Core library for interacting with Discord's APIrequests: Handles HTTP requests to WebMDbeautifulsoup4: Parses HTML to extract useful content from WebMD's pages
2. Extend Your Bot with the Symptoms Command
Here's how to integrate the new command into your existing bot code. I'll assume you already have the basic bot setup (like intents and command prefix configured):
import discord from discord.ext import commands import requests from bs4 import BeautifulSoup import urllib.parse # Initialize bot (match your existing setup) intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!Doc ', intents=intents) # Your existing !Doc status command @bot.command(name='status') async def check_status(ctx): await ctx.send("Online!") # New !Doc symptoms command @bot.command(name='symptoms') async def search_symptoms(ctx, *, symptoms: str): # Encode symptoms for URL (handles spaces/Chinese characters) encoded_symptoms = urllib.parse.quote(symptoms) webmd_url = f"https://www.webmd.com/symptoms/search?symptom={encoded_symptoms}" try: # Mimic a browser request to avoid being blocked by WebMD's anti-scrape headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } response = requests.get(webmd_url, headers=headers, timeout=10) response.raise_for_status() # Throw error if HTTP request fails # Parse WebMD's HTML soup = BeautifulSoup(response.text, 'html.parser') # Extract possible conditions (note: WebMD's class names may change over time) condition_blocks = soup.find_all('div', class_='symptom-results__condition') if not condition_blocks: await ctx.send("Sorry, I couldn't find any diagnostic info for those symptoms right now.") return # Format results into a readable message reply = "Based on WebMD's information, your symptoms may relate to:\n" for i, block in enumerate(condition_blocks[:3], 1): condition_name = block.find('h3').get_text(strip=True) condition_desc = block.find('p').get_text(strip=True) reply += f"{i}. **{condition_name}**: {condition_desc}\n" # Add a safety disclaimer reply += "\nDisclaimer: This is not a substitute for professional medical advice. Consult a doctor if symptoms persist or worsen." await ctx.send(reply) # Handle common errors except requests.exceptions.RequestException as e: await ctx.send(f"Oops, I had trouble connecting to WebMD: {str(e)}") except AttributeError: await ctx.send("Sorry, WebMD's page structure has changed — I need an update to work properly!") except Exception as e: await ctx.send("Something went wrong while processing your request. Please try again later.") # Run your bot (replace with your token) bot.run('YOUR_DISCORD_BOT_TOKEN')
3. Key Notes & Maintenance Tips
- WebMD Page Structure: WebMD occasionally updates their site's HTML, so the class selector (
symptom-results__condition) might break. If that happens, use your browser's DevTools to find the new class name for condition blocks. - Anti-Scrape Protection: Always include a valid
User-Agentheader to avoid getting blocked. If you still get 403 errors, you might need to rotate user agents or add a small delay between requests. - Legal & Ethical: Make sure your bot complies with WebMD's Terms of Service — this implementation is for non-commercial, personal use only. Never present scraped content as your own, and always include a disclaimer that it's not professional medical advice.
- Error Handling: The code includes basic error handling, but you can expand it (e.g., handle empty symptom inputs by asking the user to provide details).
Testing the Command
Once you've added the code, run your bot and test it with:
!Doc symptoms 咳嗽、流鼻涕、喉咙痛
You should get a formatted reply with possible conditions from WebMD.
内容的提问来源于stack exchange,提问作者Mr Boolean
相关产品推荐
相关产品推荐

