寻求用于Pinpoint Campaign Hook的Python Lambda(boto3)实现示例及操作指引
Got it, let's break this down clearly for you. The Pinpoint Campaign Hook lets you intercept and modify message content right before it's sent to recipients, and Lambda is the ideal tool to handle this custom logic. Here's a step-by-step implementation with Python code and key details you need to know:
First, Let's Clarify the Campaign Hook Workflow
Pinpoint triggers your Lambda function at the final stage of message delivery—after it's resolved templates but before sending the message to the user. The function receives a payload with the original message, user attributes, and campaign metadata. You modify the content in this payload, then return the updated version to Pinpoint, which uses that modified content to send the message. No need to call Pinpoint via boto3 here; the integration is event-driven.
Python Lambda Function Example
This example handles common content modifications: replacing placeholders with user attributes, adding campaign-specific text, and appending an opt-out notice.
import json def lambda_handler(event, context): try: # Extract the Pinpoint event from the Lambda trigger payload pinpoint_record = event['Records'][0]['pinpoint'] message = pinpoint_record['message'] user_data = pinpoint_record.get('user', {}) user_attributes = user_data.get('attributes', {}) campaign_details = pinpoint_record['campaign'] # -------------------------- # Your Custom Modification Logic # -------------------------- original_body = message['body'] modified_body = original_body # 1. Replace template placeholders with user attributes (e.g., {{FirstName}}) if 'FirstName' in user_attributes: modified_body = modified_body.replace('{{FirstName}}', user_attributes['FirstName']) # 2. Add campaign-specific content (e.g., flash sale for a specific campaign) if campaign_details['id'] == 'your-target-campaign-id': modified_body = f"🚨 FLASH ALERT: {modified_body} Ends tonight!" # 3. Append mandatory SMS opt-out language (compliance requirement) modified_body += "\nReply STOP to unsubscribe from future messages" # Update the message body in the payload message['body'] = modified_body # Return the updated payload to Pinpoint return { 'Records': [{'pinpoint': pinpoint_record}] } except KeyError as e: # Fallback: if payload parsing fails, return original message to avoid delivery issues print(f"Error parsing event payload: {str(e)}") return event
Critical Configuration Steps
- Lambda Trigger Setup:
- In your Lambda function, add a Pinpoint trigger.
- Select your Pinpoint application, set the event type to
MESSAGE_SEND, and save. This tells Pinpoint to invoke the Lambda when sending messages.
- IAM Permissions:
- Ensure your Lambda's execution role has the
mobiletargeting:SendMessagespermission (though Pinpoint handles the invocation, this permission ensures the function can return the modified payload back to Pinpoint). - If your Lambda fetches data from other AWS services (e.g., DynamoDB for personalized content), add the necessary permissions to the role (e.g.,
dynamodb:GetItem).
- Ensure your Lambda's execution role has the
- Pinpoint Campaign Configuration:
- When creating/editing your SMS campaign, navigate to the Hook section.
- Select "Lambda function" as the hook type, choose your deployed Lambda, and confirm the hook is set to trigger on
MESSAGE_SEND.
How to Test & Validate
- Test Lambda with Sample Payload: Use Pinpoint's sample event payload (from CloudWatch logs after a test campaign run) to test the Lambda in the AWS Console. Verify the modified body matches your expected output.
- Check CloudWatch Logs: After triggering a test campaign, check your Lambda's CloudWatch Logs to inspect the incoming event and the modified payload you're returning.
- Send Test Messages: Run a small test campaign targeting your own phone number to confirm the modified SMS content is delivered correctly.
Bonus: Fetching Dynamic Content with Boto3
If you need to pull content from an AWS service (e.g., DynamoDB) to modify the message, here's a quick snippet to add to your Lambda:
import boto3 # Initialize DynamoDB client dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('your-content-table') # Fetch personalized content for the user response = table.get_item(Key={'user_id': user_data.get('userId')}) if 'Item' in response: custom_offer = response['Item']['offer'] modified_body += f"\nExclusive offer: {custom_offer}"
Just make sure your Lambda's execution role has permission to access the DynamoDB table.
内容的提问来源于stack exchange,提问作者sameerawsnoob

