GroupMe Bot开发:Webhook中通过JSON消息传参调用函数的问题
Got it, let's break down how to add that JSON variable-passing functionality to your GroupMe Bot. I’ll walk you through a practical approach that integrates seamlessly with your existing code:
1. Update the Webhook to Parse Variables from JSON
First, we’ll modify your webhook() function to look for custom variables in the incoming GroupMe message JSON. Let’s say you want to pass a command name and optional parameters to trigger specific functions—here’s how to adjust the code:
def webhook(): message = request.get_json() # Skip bot messages to avoid infinite loops (critical!) if sender_is_bot(message): return "OK", 200 speaker = message['name'] message_text = message['text'].lower() # Keep your existing hypefact logic intact if 'hypefact!' in message_text: reply(f"{speaker} - Here is your Hype Fact: {get_random_hypefact()}") # Call your follow-up function here as before post_hypefact_followup(speaker) return "OK", 200 # Now handle variable-driven function calls # We'll look for a custom 'bot_command' field in the incoming JSON # Example payload might include: {"bot_command": {"function": "greet", "params": {"target": "Jane"}}} bot_command = message.get('bot_command') if bot_command: func_name = bot_command.get('function') params = bot_command.get('params', {}) # Map function names to actual Python functions (easy to expand!) function_map = { 'greet': send_greeting, 'custom_hypefact': generate_category_hypefact, # Add new functions here later } # Execute the function if it exists if func_name in function_map: try: # Pass the speaker and any parameters to the function response = function_map[func_name](speaker=speaker, **params) reply(response) except Exception as e: reply(f"Oops, something went wrong with that command: {str(e)}") else: reply(f"Sorry, I don’t recognize the command '{func_name}'") return "OK", 200 # Default return if no triggers hit return "No command matched", 200
2. Define the Functions You Want to Trigger
Next, create the actual functions that will be called based on the JSON variables. These can use the parameters passed in to customize their behavior:
import random def send_greeting(speaker, **params): # Pull the target user from params, default to the speaker if not provided target = params.get('target', speaker) return f"Hey {target}! {speaker} wanted me to say hi 😊" def generate_category_hypefact(speaker, **params): category = params.get('category', 'general') # Your logic to fetch a hypefact by category category_facts = { 'sports': "The fastest recorded tennis serve is 163.7 mph!", 'tech': "Python was first released in 1991!", 'general': "Bananas are berries, but strawberries aren’t!" } fact = category_facts.get(category, "Did you know? Hype is contagious!") return f"{speaker} - Custom Hype Fact ({category}): {fact}" # Your existing helper functions def get_random_hypefact(): facts = ["Hype fact 1!", "Hype fact 2!", "Hype fact 3!"] return random.choice(facts) def post_hypefact_followup(speaker): # Your existing follow-up logic here reply(f"P.S. {speaker}, that hype fact was extra hype!")
3. Test with a JSON Request
To test this, send a POST request to your webhook URL with a JSON payload that includes the bot_command field. For example, using curl:
curl -X POST -H "Content-Type: application/json" -d '{ "name": "TPup", "text": "Trigger custom command", "bot_command": { "function": "custom_hypefact", "params": {"category": "tech"} }, "sender_type": "user" }' https://your-webhook-url.com/webhook
Quick Tips for Success
- Loop Prevention: Never remove that
sender_is_botcheck—otherwise your bot might reply to its own messages and create an infinite loop. - Error Handling: The try/except block ensures your bot stays running even if a function fails, and gives users helpful feedback.
- Scalability: The
function_mapmakes it super easy to add new commands later—just add the function name to the map and define the function.
This setup keeps your existing hypefact functionality working while adding the flexibility to call functions via JSON variables.
内容的提问来源于stack exchange,提问作者TPup

