text_plain_output_1.png
from azure.ai.textanalytics import TextAnalyticsClient

from azure.core.credentials import AzureKeyCredential

from kaggle_secrets import UserSecretsClient

import ast

import json

import requests

import requests
import json
import ast
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
from kaggle_secrets import UserSecretsClient
user_secrets = UserSecretsClient()
azure_endpoint = user_secrets.get_secret('AZURE_LANGUAGE_ENDPOINT')
azure_language_key = user_secrets.get_secret('AZURE_LANGUAGE_KEY')
bearer_token = user_secrets.get_secret('bearer_token')

def create_twitter_url():
    handle = 'nasi goreng'
    max_results = 10
    mrf = 'max_results={}'.format(max_results)
    q = 'query={}'.format(handle)
    url = 'https://api.twitter.com/2/tweets/search/recent?{}&{}'.format(mrf, q)
    return url

def twitter_auth_and_connect(bearer_token, url):
    headers = {'Authorization': 'Bearer {}'.format(bearer_token)}
    response = requests.request('GET', url, headers=headers)
    return response.json()

def lang_data_shape(res_json):
    data_only = res_json['data']
    doc_start = '"documents": {}'.format(data_only)
    str_json = '{' + doc_start + '}'
    dump_doc = json.dumps(str_json)
    doc = json.loads(dump_doc)
    return ast.literal_eval(doc)

def main():
    url = create_twitter_url()
    res_json = twitter_auth_and_connect(bearer_token, url)
    documents = lang_data_shape(res_json)
    text_analytics_client = TextAnalyticsClient(endpoint=azure_endpoint, credential=AzureKeyCredential(azure_language_key))
    result = text_analytics_client.analyze_sentiment(documents['documents'], show_opinion_mining=False)
    doc_result = [doc for doc in result if not doc.is_error]
    for document in doc_result:
        print('\n')
        print(document.sentiment)
        print('=======')
        for sentence in document.sentences:
            print(sentence.text)
if __name__ == '__main__':
    main()