-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost_tuits.py
More file actions
99 lines (84 loc) · 3.36 KB
/
Copy pathpost_tuits.py
File metadata and controls
99 lines (84 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from connect_DB import get_mongo_collection
from connect_Twitter import connect_to_twitter
from create_tweet import create_tweet
import logging
import os
import sys
from datetime import datetime
log_file = os.path.join(os.path.dirname(__file__), "chuchu_bot.log")
# file_path = os.path.join(os.path.dirname(__file__), "data.json")
logging.basicConfig(
encoding="utf-8",
format="%(asctime)s - %(levelname)s - %(message)s",
level=logging.INFO,
handlers=[
logging.FileHandler(log_file, encoding="utf-8"),
logging.StreamHandler(sys.stdout),
],
)
logger = logging.getLogger(__name__)
today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logger.info(f"***** ***** ***** {today} ***** ***** *****")
def get_one_document(collection, x_client, x_api):
logger.info("Iniciando búsqueda de tuit...")
intentos = 0
max_intentos = 10
while intentos < max_intentos:
try:
# Pipeline optimizado para prioridad a los de 1 o 0
pipeline = [
{
"$match": {"enviado": {"$lt": 2}}
}, # Aquellos con valor "enviado" menor a 2
{"$sort": {"enviado": 1}}, # De menor a Mayor
{"$limit": 20}, # "top 20"
{"$sample": {"size": 1}},
]
random_item = list(collection.aggregate(pipeline))
if not random_item:
logger.warning(
"Consulta a MongoDB vacía. Revisa si quedan documentos con enviado < 2."
)
return None
item = random_item[0]
# Logueamos ID para rastrearlo
logger.info(
f"Candidato hallado: ID {item.get('_id')} | Intentos: {intentos + 1}"
)
# Cálculo de longitud (ajusta según formato de string en create_tweet)
longitud_texto = len(item.get("texto", "")) + len(item.get("libro", "")) + 6
if longitud_texto < 281:
logger.info(f"✅ Tuit válido: {item['texto'][:40]}...")
create_tweet(item, x_client, x_api)
# Actualización en db
collection.update_one(
{"_id": item["_id"]},
{
"$set": {"publicado": True},
"$inc": {"enviado": 1},
"$currentDate": {"fecha_ultimo_post": True}
},
)
return item
else:
logger.info(f"❌ Descartado por largo ({longitud_texto} chars).")
except Exception as e:
logger.error(f"Error crítico: {e}")
break
intentos += 1
return None
if __name__ == "__main__":
try:
logger.info("--- INICIANDO PROCESO DEL BOT ---")
# Conectamos dentro del try para capturar errores en el log
collection = get_mongo_collection()
x_client, x_api = connect_to_twitter()
if collection is not None and x_client is not None:
get_one_document(collection, x_client, x_api)
else:
logger.error("No se pudo establecer conexión con los servicios.")
except Exception as e:
# Esto guardará cualquier error de conexión en el log
logger.critical(f"--- EL BOT NO PUDO ARRANCAR: {e}", exc_info=True)
finally:
logger.info("--- FIN DE LA EJECUCIÓN ---")