I have this .py code that should send an event to google analytics 4. When i execute the code, i get 204 message which i think means it run successfully. My problem is that when i go to events on google analytics, nithing appears there, I can only see the information of the events in real time tab on counting events by name only. Here is my code:
`import firebase_admin
from firebase_admin import credentials, db
import json
import requests
import uuid
# Configuração do Firebase
if not firebase_admin._apps:
cred = credentials.Certificate("C:/SensiaFortaleza/Scripts/Assets/sensiafortaleza-firebase-adminsdk-ymbm5-4d5161e452.json")
default_app = firebase_admin.initialize_app(cred, {'databaseURL': 'https://sensiafortaleza-default-rtdb.firebaseio.com/'})
# Carregar dados do arquivo JSON
file = "C:/SensiaFortaleza/Scripts/arquivoteste.json"
data = {}
try:
with open(file, encoding="utf-16") as f:
data = json.load(f)
except:
with open(file, encoding="utf-8") as f:
data = json.load(f)
# Referência ao caminho do banco de dados
ref = db.reference("Testando/")
def merge_dict(existing_data, new_data):
for key, value in new_data.items():
if isinstance(value, dict):
node = existing_data.setdefault(key, {})
merge_dict(node, value)
else:
existing_data[key] = value
# Atualizar os dados no banco de dados sem sobrescrever
existing_data = ref.get()
if existing_data:
merge_dict(existing_data, data)
ref.set(existing_data)
else:
ref.set(data)
# Função para enviar eventos ao Google Analytics
def send_event_to_google_analytics(event_name, params):
measurement_id = "G-9LVFTMGLV7" # Substitua pelo seu Measurement ID
api_secret = "VHxWrcbqQnG-FomGscQM6g" # Se necessário, substitua pelo seu segredo da API
url = f"https://www.google-analytics.com/mp/collect?measurement_id={measurement_id}&api_secret={api_secret}"
headers = {
"Content-Type": "application/json",
}
payload = {
"client_id": str(uuid.uuid4()), # Identificador único para o usuário. Pode ser um UUID ou similar
"events": [
{
"name": event_name,
"params": params,
}
],
}
# Imprimir o payload para depuração
print("Enviando payload:", json.dumps(payload, indent=4))
response = requests.post(url, headers=headers, json=payload)
# Imprimir a resposta para depuração
print(f"Resposta do servidor: {response.status_code}, {response.text}")
return response
# Enviar evento para o Google Analytics
def send_data_to_analytics(data):
for op_id, op_data in data.get("ComCadastro", {}).items():
for room, features in op_data.get("Apartamento Meio", {}).items():
# Enviar um evento para cada cômodo com suas características
event_name = f"room_{room.replace(' ', '_').lower()}"
event_params = {
"piso": features.get("Piso", "N/A"),
"rodape": features.get("Rodape", "N/A"),
"parede": features.get("Parede", "N/A"),
"bancada": features.get("Bancada", "N/A"),
"cuba": features.get("Cuba", "N/A"),
"torneira": features.get("Torneira", "N/A"),
"box": features.get("Box", "N/A"),
"bacia": features.get("Bacia", "N/A"),
"divisoria": features.get("Divisoria", "N/A"),
"ducha": features.get("Ducha", "N/A"),
}
response = send_event_to_google_analytics(event_name, event_params)
print(f"Evento {event_name} enviado: {response.status_code}, {response.text}")
send_data_to_analytics(data)`
I want to be able to see the event when i execute my .py and after that works, make customs reports from the infos inside the event. Can someone help me with this, please? I’m new to python and I’m using chatGPT to get help but it seems stuck on this! Also, I don’t have an web page to trigger the events, I need just the python code to do it!