comparison src/handlers/tweet_sentiment_handler.py @ 8:6541622b6127

add tweet analysis method
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Fri, 17 Sep 2021 21:10:02 +0200
parents src/handlers/sentiment.py@db2ce7097ff3
children
comparison
equal deleted inserted replaced
7:1b1296559c31 8:6541622b6127
1 import json
2 import requests
3
4 # noinspection PyUnresolvedReferences
5 from aws_controller import AwsSecretsManager, AwsComprehend
6 # noinspection PyUnresolvedReferences
7 from event_controller import SentimentFunctionEvent
8 # noinspection PyUnresolvedReferences
9 from url_controller import TwitterApi
10
11
12 # noinspection PyUnusedLocal
13 def get_tweet_sentiment(event, context):
14 """
15 :param event: dict, required
16 API Gateway Lambda Proxy Input Format
17 :param context: object, required
18 Lambda Context runtime methods and attributes
19 :return: dict
20 API Gateway Lambda Proxy Output Format
21 """
22
23 # Unwrap query string parameters
24 twitter_user, number_of_tweets = SentimentFunctionEvent.unwrap_parameters(event)
25
26 # URL creation & authentication
27 twitter_url = TwitterApi.create_sentiment_url(twitter_user, number_of_tweets)
28 twitter_key = AwsSecretsManager.get_secret(secret_name='tweet-analysis-keys')
29 twitter_header = {"Authorization": "Bearer {}".format(twitter_key['BEARER'])}
30
31 # Request tweets to Twitter
32 twitter_response = requests.request("GET", twitter_url, headers=twitter_header)
33 twitter_json_response = twitter_response.json()
34
35 tweets = []
36 for tweet in twitter_json_response['data']['tweets']:
37 tweets.append(tweet['text'])
38
39 # Analyse tweets with AWS Comprehend
40 result = AwsComprehend.get_sentiment(tweets)
41
42 return {
43 "statusCode": 200,
44 "body": {
45 "tweets": json.dumps(result)
46 }
47 }