Li uns cinco problemas com esse mesmo erro no f, mas não consigo avançar.
import requests
import os
import json
# To set your enviornment variables in your terminal run the following line:
# export 'BEARER_TOKEN'='<your_bearer_token>'
def auth():
return os.environ.get("BEARER_TOKEN") # Chave de acesso para acessar essa API do Twitter. Pede que o token vá para uma variável de ambiente.
def create_url():
query = "AluraOnline"
# Tweet fields are adjustable.
# Options include:
# attachments, author_id, context_annotations,
# conversation_id, created_at, entities, geo, id,
# in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
# source, text, and withheld
tweet_fields = "tweet.fields=author_id,conversation_id,created_at,id,in_reply_to_user_id,public_metric"
user_fields = "expansions=author_id&user.fields=id,name,username,created_at"
filters = "start_time=2022-07-08T00:00:00.000Z&end_time=2022-07-12T00:00:00.000Z"
# Nos é permitido pedir os tweets de até 7 dias atrás relativo ao dia atual. Por exemplo, hoje é 13 de julho de 2022.
url = "https://api.twitter.com/2/tweets/search/recent?query={}&{}&{}&{}".format(
query, tweet_fields, user_fields, filters
)
return url
def create_headers(bearer_token):
headers = {"Authorization": "Bearer {}".format(bearer_token)}
return headers
def connect_to_endpoint(url, headers):
response = requests.request("GET", url, headers=headers)
print(response.status_code)
if response.status_code != 200:
raise Exception(response.status_code, response.text)
return response.json()
def main():
bearer_token = auth()
url = create_url()
headers = create_headers(bearer_token)
json_response = connect_to_endpoint(url, headers)
print(json.dumps(json_response, indent=4, sort_keys=True))
if __name__ == "__main__":
main()
O resultado está sempre:
(.env) akhenaton@akhenaton-VirtualBox:~/airflow$ python recent_search.py
400
Traceback (most recent call last):
File "/home/akhenaton/airflow/recent_search.py", line 54, in <module>
main()
File "/home/akhenaton/airflow/recent_search.py", line 49, in main
json_response = connect_to_endpoint(url, headers)
File "/home/akhenaton/airflow/recent_search.py", line 41, in connect_to_endpoint
raise Exception(response.status_code, response.text)
Exception: (400, '{"errors":[{"parameters":{"tweet.fields":["author_id,conversation_id,created_at,id,in_reply_to_user_id,public_metric"]},"message":"The `tweet.fields` query parameter value [public_metric] is not one of [attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,organic_metrics,possibly_sensitive,promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld]"}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}')
Estou usando o Editor de texto para o arquivo recent_search.py e estou testando a resposta no prompt de comando do Linux no Virtualbox. Já cliquei em regenerate mais de três vezes em várias tentativas. Onde estou errando? Entendi que meu arquivo está sendo lido, mas estou o tempo todo com o request invalid. No terminal, uso primeiro "$ python3 -m venv .env" e "$ source .env/bin/activate" sempre e depois uso o "$ export BEARER_TOKEN=" e digito o código. Esse código tem validade?
Logo, digito "$ python recent_search.py", mas da