comparison src/handlers/sentiment.py @ 3:5c36f51105c2

fetch tweets working
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Thu, 16 Sep 2021 16:51:59 +0200
parents 0277e7fc0f0a
children cfd876570008
comparison
equal deleted inserted replaced
2:561bc303784f 3:5c36f51105c2
1 import json 1 import json
2 import requests
3 import boto3
4 import base64
5 from botocore.exceptions import ClientError
2 6
3 7
4 def get_tweet_sentiment(event, context): 8 def get_tweet_sentiment(event, context):
5 """ 9 """
6
7 :param event: dict, required 10 :param event: dict, required
8 API Gateway Lambda Proxy Input Format 11 API Gateway Lambda Proxy Input Format
9 :param context: object, required 12 :param context: object, required
10 Lambda Context runtime methods and attributes 13 Lambda Context runtime methods and attributes
11 :return: dict 14 :return: dict
12 API Gateway Lambda Proxy Output Format 15 API Gateway Lambda Proxy Output Format
13 """ 16 """
14 17
15 print('hello world') 18 twitter_url = create_twitter_url(user='dennisconcep')
19 twitter_key = get_twitter_key()
20 bearer_token = twitter_key['BEARER']
21 twitter_header = {"Authorization": "Bearer {}".format(bearer_token)} # Auth header
22 twitter_response = requests.request("GET", twitter_url, headers=twitter_header)
23 print(twitter_response.json())
16 24
17 return { 25 return {
18 "statusCode": 200, 26 "statusCode": 200,
19 "body": json.dumps({ 27 "body": json.dumps({
20 "message": "hello world" 28 "message": "hello world",
21 }), 29 }),
22 } 30 }
31
32
33 def create_twitter_url(user, max_results=100):
34 """
35 Create url to fetch `max_results` of tweets from `user`
36 :param user: string, required
37 :param max_results: int, optional, default 100
38 :return: string url
39 """
40
41 formatted_max_results = 'max_results={}'.format(max_results)
42 formatted_user = 'query=from:{}'.format(user)
43 url = "https://api.twitter.com/2/tweets/search/recent?{}&{}".format(formatted_max_results, formatted_user)
44
45 return url
46
47
48 def get_twitter_key():
49 """
50 Get Twitter Api Key from AWS Secrets Manager
51 :return:
52 """
53 secret_name = "tweet-analysis-keys"
54 region_name = "eu-west-2"
55
56 # Create a Secrets Manager client
57 session = boto3.session.Session()
58 client = session.client(
59 service_name='secretsmanager',
60 region_name=region_name
61 )
62
63 try:
64 get_secret_value_response = client.get_secret_value(SecretId=secret_name)
65 except ClientError as e:
66 if e.response['Error']['Code'] == 'DecryptionFailureException':
67 # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
68 # Deal with the exception here, and/or rethrow at your discretion.
69 raise e
70 elif e.response['Error']['Code'] == 'InternalServiceErrorException':
71 # An error occurred on the server side.
72 # Deal with the exception here, and/or rethrow at your discretion.
73 raise e
74 elif e.response['Error']['Code'] == 'InvalidParameterException':
75 # You provided an invalid value for a parameter.
76 # Deal with the exception here, and/or rethrow at your discretion.
77 raise e
78 elif e.response['Error']['Code'] == 'InvalidRequestException':
79 # You provided a parameter value that is not valid for the current state of the resource.
80 # Deal with the exception here, and/or rethrow at your discretion.
81 raise e
82 elif e.response['Error']['Code'] == 'ResourceNotFoundException':
83 # We can't find the resource that you asked for.
84 # Deal with the exception here, and/or rethrow at your discretion.
85 raise e
86 else:
87 # Decrypts secret using the associated KMS CMK.
88 # Depending on whether the secret is a string or binary, one of these fields will be populated.
89 if 'SecretString' in get_secret_value_response:
90 secret = get_secret_value_response['SecretString']
91 else:
92 secret = base64.b64decode(get_secret_value_response['SecretBinary'])
93
94 return json.loads(secret)