0

I have a lambda function connected to AWS Lex that calls an API key and gives the user a response with different articles, but since Lex's responce is in plaintext I am having issues getting each new article onto a new line and being to able highlight the links.

import json
import requests
def lambda_handler(event, context):
 try:
 # Log the event for debugging
 print("Received event:", json.dumps(event, indent=2))
 
 # Check if 'sessionState' and 'intent' are present in the event
 session_state = event.get("sessionState", {})
 intent = session_state.get("intent", {})
 # Get the intent name from the event
 intent_name = intent.get("name", "Unknown")
 if intent_name == "GetCyberNewsIntent":
 # API key and URL for NewsAPI
 api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
 base_url = "https://newsapi.org/v2/everything"
 query = "cybersecurity, cyber, Tech, IT" # Search keywords
 # Make a request to NewsAPI
 response = requests.get(f"{base_url}?q={query}&apiKey={api_key}")
 # Check if the API request was successful
 if response.status_code == 200:
 # Parse the JSON response from the API
 news = response.json()
 articles = news.get("articles", [])
 # Get the top 5 articles from the response
 top_articles = articles[:5]
 
 if not top_articles:
 # No articles found, set the response message
 message_content = "No recent cybersecurity news found."
 else:
 # Format the articles with line breaks (URLs in plain text)
 message_content = "\n".join(
 f"{i + 1}. {article['title']} - {article['url']}"
 for i, article in enumerate(top_articles)
 )
 else:
 # Handle API errors gracefully
 message_content = "Failed to fetch news. Please try again later."
 # Return the formatted response to Lex
 return {
 "sessionState": {
 "dialogAction": {
 "type": "Close" # Close the conversation
 },
 "intent": {
 "name": intent_name,
 "state": "Fulfilled" # Mark the intent as fulfilled
 }
 },
 "messages": [
 {
 "contentType": "PlainText", # Output the response as plain text
 "content": message_content
 }
 ]
 }
 else:
 # Handle unsupported intents
 return {
 "sessionState": {
 "dialogAction": {
 "type": "Close"
 },
 "intent": {
 "name": intent_name,
 "state": "Failed"
 }
 },
 "messages": [
 {
 "contentType": "PlainText",
 "content": f"Intent {intent_name} is not supported."
 }
 ]
 }
 except Exception as e:
 # Log and handle any unexpected errors
 print(f"Error: {e}")
 return {
 "sessionState": {
 "dialogAction": {
 "type": "Close"
 },
 "intent": {
 "name": "GetCyberNewsIntent", # Fallback to a valid intent
 "state": "Failed"
 }
 },
 "messages": [
 {
 "contentType": "PlainText",
 "content": f"An error occurred: {str(e)}"
 }
 ]
 }
Pat Myron
4,6664 gold badges30 silver badges52 bronze badges
asked Jan 14, 2025 at 15:34

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.