Spaces:
Running
Running
Upload 4 files
Browse files- modules/blogger/database.py +360 -0
- modules/blogger/processor.py +748 -0
- modules/blogger/scheduler.py +369 -0
- modules/blogger/ui.py +1959 -0
modules/blogger/database.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import threading
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
_DEFAULT_DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "data")
|
| 10 |
+
_HF_DATA = "/data" if os.path.isdir("/data") and "SPACE_ID" in os.environ else None
|
| 11 |
+
DB_FILE = os.environ.get("BLOGGER_DB_PATH", os.path.join(_HF_DATA or _DEFAULT_DB_DIR, "blogger_data.json"))
|
| 12 |
+
lock = threading.Lock()
|
| 13 |
+
|
| 14 |
+
DEFAULT_BLOGGER_DATA = {
|
| 15 |
+
"config": {
|
| 16 |
+
"blog_id": "",
|
| 17 |
+
"client_id": "",
|
| 18 |
+
"client_secret": "",
|
| 19 |
+
"refresh_token": "",
|
| 20 |
+
"publish_as_draft": False,
|
| 21 |
+
"enabled": False,
|
| 22 |
+
"default_jobs_image": "",
|
| 23 |
+
},
|
| 24 |
+
"ai_keys": {},
|
| 25 |
+
"channels": {},
|
| 26 |
+
"articles": {},
|
| 27 |
+
"published_ids": [],
|
| 28 |
+
"sections": {},
|
| 29 |
+
"logs": [],
|
| 30 |
+
"stats": {
|
| 31 |
+
"total_published": 0,
|
| 32 |
+
"total_failed": 0,
|
| 33 |
+
"daily": {},
|
| 34 |
+
"monthly": {},
|
| 35 |
+
},
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BloggerDatabase:
|
| 40 |
+
def __init__(self):
|
| 41 |
+
self._cache = None
|
| 42 |
+
|
| 43 |
+
def _ensure_file(self):
|
| 44 |
+
os.makedirs(os.path.dirname(DB_FILE), exist_ok=True)
|
| 45 |
+
if not os.path.exists(DB_FILE):
|
| 46 |
+
old_path = os.path.join(_DEFAULT_DB_DIR, "blogger_data.json")
|
| 47 |
+
if _HF_DATA and os.path.isfile(old_path):
|
| 48 |
+
import shutil
|
| 49 |
+
shutil.copy2(old_path, DB_FILE)
|
| 50 |
+
logger.info(f"Migrated DB from {old_path} to {DB_FILE}")
|
| 51 |
+
else:
|
| 52 |
+
with open(DB_FILE, "w", encoding="utf-8") as f:
|
| 53 |
+
json.dump(DEFAULT_BLOGGER_DATA, f, ensure_ascii=False, indent=2)
|
| 54 |
+
|
| 55 |
+
def _read(self):
|
| 56 |
+
self._ensure_file()
|
| 57 |
+
try:
|
| 58 |
+
with open(DB_FILE, "r", encoding="utf-8") as f:
|
| 59 |
+
data = json.load(f)
|
| 60 |
+
except Exception:
|
| 61 |
+
data = {}
|
| 62 |
+
for key, value in DEFAULT_BLOGGER_DATA.items():
|
| 63 |
+
if key not in data:
|
| 64 |
+
data[key] = value.copy() if isinstance(value, (list, dict)) else value
|
| 65 |
+
if not isinstance(data.get("config"), dict):
|
| 66 |
+
data["config"] = {}
|
| 67 |
+
for k, v in DEFAULT_BLOGGER_DATA["config"].items():
|
| 68 |
+
data["config"].setdefault(k, v)
|
| 69 |
+
return data
|
| 70 |
+
|
| 71 |
+
def _write(self, data):
|
| 72 |
+
self._ensure_file()
|
| 73 |
+
tmp = DB_FILE + ".tmp"
|
| 74 |
+
with open(tmp, "w", encoding="utf-8") as f:
|
| 75 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 76 |
+
f.flush()
|
| 77 |
+
try:
|
| 78 |
+
os.fsync(f.fileno())
|
| 79 |
+
except Exception:
|
| 80 |
+
pass
|
| 81 |
+
os.replace(tmp, DB_FILE)
|
| 82 |
+
self._cache = None
|
| 83 |
+
|
| 84 |
+
def get_config(self):
|
| 85 |
+
with lock:
|
| 86 |
+
return dict(self._read().get("config", {}))
|
| 87 |
+
|
| 88 |
+
def update_config(self, key, value):
|
| 89 |
+
with lock:
|
| 90 |
+
data = self._read()
|
| 91 |
+
data["config"][key] = value
|
| 92 |
+
self._write(data)
|
| 93 |
+
|
| 94 |
+
def get_channel(self, channel_id):
|
| 95 |
+
with lock:
|
| 96 |
+
data = self._read()
|
| 97 |
+
return data.get("channels", {}).get(str(channel_id))
|
| 98 |
+
|
| 99 |
+
def get_all_channels(self):
|
| 100 |
+
with lock:
|
| 101 |
+
data = self._read()
|
| 102 |
+
return list(data.get("channels", {}).values())
|
| 103 |
+
|
| 104 |
+
def save_channel(self, channel_id, channel_data):
|
| 105 |
+
with lock:
|
| 106 |
+
data = self._read()
|
| 107 |
+
data["channels"][str(channel_id)] = channel_data
|
| 108 |
+
self._write(data)
|
| 109 |
+
|
| 110 |
+
def delete_channel(self, channel_id):
|
| 111 |
+
with lock:
|
| 112 |
+
data = self._read()
|
| 113 |
+
data["channels"].pop(str(channel_id), None)
|
| 114 |
+
self._write(data)
|
| 115 |
+
|
| 116 |
+
def save_article(self, article_id, article_data):
|
| 117 |
+
with lock:
|
| 118 |
+
data = self._read()
|
| 119 |
+
data["articles"][str(article_id)] = article_data
|
| 120 |
+
self._write(data)
|
| 121 |
+
|
| 122 |
+
def get_article(self, article_id):
|
| 123 |
+
with lock:
|
| 124 |
+
data = self._read()
|
| 125 |
+
return data.get("articles", {}).get(str(article_id))
|
| 126 |
+
|
| 127 |
+
def delete_article(self, article_id):
|
| 128 |
+
with lock:
|
| 129 |
+
data = self._read()
|
| 130 |
+
data["articles"].pop(str(article_id), None)
|
| 131 |
+
self._write(data)
|
| 132 |
+
|
| 133 |
+
def get_all_articles(self):
|
| 134 |
+
with lock:
|
| 135 |
+
data = self._read()
|
| 136 |
+
return list(data.get("articles", {}).values())
|
| 137 |
+
|
| 138 |
+
def is_published(self, fingerprint):
|
| 139 |
+
with lock:
|
| 140 |
+
data = self._read()
|
| 141 |
+
return fingerprint in data.get("published_ids", [])
|
| 142 |
+
|
| 143 |
+
def mark_published(self, fingerprint):
|
| 144 |
+
with lock:
|
| 145 |
+
data = self._read()
|
| 146 |
+
if fingerprint not in data["published_ids"]:
|
| 147 |
+
data["published_ids"].append(fingerprint)
|
| 148 |
+
data["stats"]["total_published"] += 1
|
| 149 |
+
self._write(data)
|
| 150 |
+
|
| 151 |
+
def mark_failed(self):
|
| 152 |
+
with lock:
|
| 153 |
+
data = self._read()
|
| 154 |
+
data["stats"]["total_failed"] += 1
|
| 155 |
+
self._write(data)
|
| 156 |
+
|
| 157 |
+
def add_log(self, entry):
|
| 158 |
+
with lock:
|
| 159 |
+
data = self._read()
|
| 160 |
+
data["logs"].append(entry)
|
| 161 |
+
if len(data["logs"]) > 1000:
|
| 162 |
+
data["logs"] = data["logs"][-1000:]
|
| 163 |
+
self._write(data)
|
| 164 |
+
|
| 165 |
+
def get_logs(self, limit=50):
|
| 166 |
+
with lock:
|
| 167 |
+
data = self._read()
|
| 168 |
+
return list(data["logs"])[-limit:]
|
| 169 |
+
|
| 170 |
+
def get_stats(self):
|
| 171 |
+
with lock:
|
| 172 |
+
data = self._read()
|
| 173 |
+
return dict(data.get("stats", {}))
|
| 174 |
+
|
| 175 |
+
def get_articles_by_status(self, status):
|
| 176 |
+
with lock:
|
| 177 |
+
data = self._read()
|
| 178 |
+
return [a for a in data.get("articles", {}).values() if a.get("status") == status]
|
| 179 |
+
|
| 180 |
+
def update_article_status(self, article_id, status, extra=None):
|
| 181 |
+
with lock:
|
| 182 |
+
data = self._read()
|
| 183 |
+
if str(article_id) in data["articles"]:
|
| 184 |
+
data["articles"][str(article_id)]["status"] = status
|
| 185 |
+
if extra:
|
| 186 |
+
data["articles"][str(article_id)].update(extra)
|
| 187 |
+
self._write(data)
|
| 188 |
+
|
| 189 |
+
def get_all_sections(self):
|
| 190 |
+
with lock:
|
| 191 |
+
data = self._read()
|
| 192 |
+
return dict(data.get("sections", {}))
|
| 193 |
+
|
| 194 |
+
def add_section(self, section_id, section_data):
|
| 195 |
+
with lock:
|
| 196 |
+
data = self._read()
|
| 197 |
+
data["sections"][str(section_id)] = section_data
|
| 198 |
+
self._write(data)
|
| 199 |
+
|
| 200 |
+
def delete_section(self, section_id):
|
| 201 |
+
with lock:
|
| 202 |
+
data = self._read()
|
| 203 |
+
data["sections"].pop(str(section_id), None)
|
| 204 |
+
self._write(data)
|
| 205 |
+
|
| 206 |
+
def get_all_ai_keys(self):
|
| 207 |
+
with lock:
|
| 208 |
+
data = self._read()
|
| 209 |
+
return dict(data.get("ai_keys", {}))
|
| 210 |
+
|
| 211 |
+
def add_ai_key(self, key_id, key_data):
|
| 212 |
+
with lock:
|
| 213 |
+
data = self._read()
|
| 214 |
+
data["ai_keys"][str(key_id)] = {
|
| 215 |
+
"name": key_data.get("name", str(key_id)),
|
| 216 |
+
"key": key_data.get("key", ""),
|
| 217 |
+
"enabled": key_data.get("enabled", True),
|
| 218 |
+
"usage_count": 0,
|
| 219 |
+
"error_count": 0,
|
| 220 |
+
"last_used": 0,
|
| 221 |
+
"added_at": int(time.time()),
|
| 222 |
+
}
|
| 223 |
+
self._write(data)
|
| 224 |
+
|
| 225 |
+
def delete_ai_key(self, key_id):
|
| 226 |
+
with lock:
|
| 227 |
+
data = self._read()
|
| 228 |
+
data["ai_keys"].pop(str(key_id), None)
|
| 229 |
+
self._write(data)
|
| 230 |
+
|
| 231 |
+
def set_ai_key_enabled(self, key_id, enabled):
|
| 232 |
+
with lock:
|
| 233 |
+
data = self._read()
|
| 234 |
+
if str(key_id) in data["ai_keys"]:
|
| 235 |
+
data["ai_keys"][str(key_id)]["enabled"] = enabled
|
| 236 |
+
self._write(data)
|
| 237 |
+
|
| 238 |
+
def increment_daily_count(self, section):
|
| 239 |
+
with lock:
|
| 240 |
+
data = self._read()
|
| 241 |
+
today = time.strftime("%Y-%m-%d")
|
| 242 |
+
if "daily" not in data["stats"]:
|
| 243 |
+
data["stats"]["daily"] = {}
|
| 244 |
+
if today not in data["stats"]["daily"]:
|
| 245 |
+
data["stats"]["daily"][today] = {}
|
| 246 |
+
data["stats"]["daily"][today][section] = data["stats"]["daily"][today].get(section, 0) + 1
|
| 247 |
+
self._write(data)
|
| 248 |
+
|
| 249 |
+
def increment_ai_key_usage(self, key_id):
|
| 250 |
+
with lock:
|
| 251 |
+
data = self._read()
|
| 252 |
+
if str(key_id) in data["ai_keys"]:
|
| 253 |
+
data["ai_keys"][str(key_id)]["usage_count"] = data["ai_keys"][str(key_id)].get("usage_count", 0) + 1
|
| 254 |
+
data["ai_keys"][str(key_id)]["last_used"] = int(time.time())
|
| 255 |
+
self._write(data)
|
| 256 |
+
|
| 257 |
+
def increment_ai_key_error(self, key_id):
|
| 258 |
+
with lock:
|
| 259 |
+
data = self._read()
|
| 260 |
+
if str(key_id) in data["ai_keys"]:
|
| 261 |
+
data["ai_keys"][str(key_id)]["error_count"] = data["ai_keys"][str(key_id)].get("error_count", 0) + 1
|
| 262 |
+
self._write(data)
|
| 263 |
+
|
| 264 |
+
SCHEDULE_KEY = "_schedule"
|
| 265 |
+
|
| 266 |
+
def get_schedule_state(self) -> dict:
|
| 267 |
+
with lock:
|
| 268 |
+
data = self._read()
|
| 269 |
+
return data.get("stats", {}).get(self.SCHEDULE_KEY, {"day": "", "last_slot": -1})
|
| 270 |
+
|
| 271 |
+
def save_schedule_state(self, state: dict):
|
| 272 |
+
with lock:
|
| 273 |
+
data = self._read()
|
| 274 |
+
if "stats" not in data:
|
| 275 |
+
data["stats"] = {}
|
| 276 |
+
data["stats"][self.SCHEDULE_KEY] = state
|
| 277 |
+
self._write(data)
|
| 278 |
+
|
| 279 |
+
GEMINI_PENDING_KEY = "_gemini_pending"
|
| 280 |
+
|
| 281 |
+
def get_gemini_pending_queue(self) -> list:
|
| 282 |
+
with lock:
|
| 283 |
+
data = self._read()
|
| 284 |
+
return data.get(self.GEMINI_PENDING_KEY, [])
|
| 285 |
+
|
| 286 |
+
def save_gemini_pending_queue(self, queue: list):
|
| 287 |
+
with lock:
|
| 288 |
+
data = self._read()
|
| 289 |
+
data[self.GEMINI_PENDING_KEY] = queue
|
| 290 |
+
self._write(data)
|
| 291 |
+
|
| 292 |
+
def add_to_gemini_pending(self, raw_text: str, source_url: str = "", media: list = None,
|
| 293 |
+
fingerprint: str = "", channel_id: str = "", section: str = ""):
|
| 294 |
+
with lock:
|
| 295 |
+
data = self._read()
|
| 296 |
+
pending = data.get(self.GEMINI_PENDING_KEY, [])
|
| 297 |
+
# Avoid duplicate entries for the same fingerprint (e.g. re-enqueued after a failed attempt)
|
| 298 |
+
if fingerprint and any(p.get("fingerprint") == fingerprint for p in pending):
|
| 299 |
+
return
|
| 300 |
+
pending.append({
|
| 301 |
+
"raw_text": raw_text,
|
| 302 |
+
"source_url": source_url,
|
| 303 |
+
"media": media or [],
|
| 304 |
+
"fingerprint": fingerprint,
|
| 305 |
+
"channel_id": channel_id,
|
| 306 |
+
"section": section,
|
| 307 |
+
"attempts": 0,
|
| 308 |
+
"added_at": int(time.time()),
|
| 309 |
+
})
|
| 310 |
+
data[self.GEMINI_PENDING_KEY] = pending
|
| 311 |
+
self._write(data)
|
| 312 |
+
|
| 313 |
+
def remove_from_gemini_pending(self, index: int = 0):
|
| 314 |
+
with lock:
|
| 315 |
+
data = self._read()
|
| 316 |
+
pending = data.get(self.GEMINI_PENDING_KEY, [])
|
| 317 |
+
if 0 <= index < len(pending):
|
| 318 |
+
pending.pop(index)
|
| 319 |
+
data[self.GEMINI_PENDING_KEY] = pending
|
| 320 |
+
self._write(data)
|
| 321 |
+
|
| 322 |
+
def remove_pending_by_fingerprint(self, fingerprint: str):
|
| 323 |
+
"""Remove a pending item by fingerprint (safe against list reordering/races)."""
|
| 324 |
+
with lock:
|
| 325 |
+
data = self._read()
|
| 326 |
+
pending = data.get(self.GEMINI_PENDING_KEY, [])
|
| 327 |
+
new_pending = [p for p in pending if p.get("fingerprint") != fingerprint]
|
| 328 |
+
if len(new_pending) != len(pending):
|
| 329 |
+
data[self.GEMINI_PENDING_KEY] = new_pending
|
| 330 |
+
self._write(data)
|
| 331 |
+
|
| 332 |
+
def increment_pending_attempts(self, fingerprint: str) -> int:
|
| 333 |
+
"""Increment and return the attempt counter for a pending item. Returns -1 if not found."""
|
| 334 |
+
with lock:
|
| 335 |
+
data = self._read()
|
| 336 |
+
pending = data.get(self.GEMINI_PENDING_KEY, [])
|
| 337 |
+
for p in pending:
|
| 338 |
+
if p.get("fingerprint") == fingerprint:
|
| 339 |
+
p["attempts"] = p.get("attempts", 0) + 1
|
| 340 |
+
data[self.GEMINI_PENDING_KEY] = pending
|
| 341 |
+
self._write(data)
|
| 342 |
+
return p["attempts"]
|
| 343 |
+
return -1
|
| 344 |
+
|
| 345 |
+
GEMINI_STATE_KEY = "_gemini"
|
| 346 |
+
|
| 347 |
+
def get_gemini_state(self) -> dict:
|
| 348 |
+
with lock:
|
| 349 |
+
data = self._read()
|
| 350 |
+
if "stats" not in data:
|
| 351 |
+
data["stats"] = {}
|
| 352 |
+
return data["stats"].get(self.GEMINI_STATE_KEY, {"global_cooldown_until": 0.0})
|
| 353 |
+
|
| 354 |
+
def save_gemini_state(self, state: dict):
|
| 355 |
+
with lock:
|
| 356 |
+
data = self._read()
|
| 357 |
+
if "stats" not in data:
|
| 358 |
+
data["stats"] = {}
|
| 359 |
+
data["stats"][self.GEMINI_STATE_KEY] = state
|
| 360 |
+
self._write(data)
|
modules/blogger/processor.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
import hashlib
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Optional, Dict, Any, List, Tuple
|
| 7 |
+
|
| 8 |
+
from modules.blogger.ai_manager import AIClient, AIKeyManager, AllProvidersExhausted as AllKeysExhausted
|
| 9 |
+
from modules.blogger.prompts import (
|
| 10 |
+
SYSTEM_REWRITE,
|
| 11 |
+
SYSTEM_EXTRACT,
|
| 12 |
+
SYSTEM_SEO,
|
| 13 |
+
SYSTEM_HASHTAGS,
|
| 14 |
+
SYSTEM_ALT_IMAGE,
|
| 15 |
+
SYSTEM_SUMMARY,
|
| 16 |
+
SYSTEM_NOTES,
|
| 17 |
+
SYSTEM_KEYWORDS,
|
| 18 |
+
make_rewrite_prompt,
|
| 19 |
+
make_extract_prompt,
|
| 20 |
+
make_seo_prompt,
|
| 21 |
+
make_hashtag_prompt,
|
| 22 |
+
make_summary_prompt,
|
| 23 |
+
make_notes_prompt,
|
| 24 |
+
make_keywords_prompt,
|
| 25 |
+
)
|
| 26 |
+
from modules.blogger.database import BloggerDatabase
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ArticleProcessor:
|
| 32 |
+
def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None):
|
| 33 |
+
self.db = db
|
| 34 |
+
self.gemini = ai_client
|
| 35 |
+
self.config = config
|
| 36 |
+
|
| 37 |
+
MAX_PENDING_ATTEMPTS = 5
|
| 38 |
+
|
| 39 |
+
async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[Dict]:
|
| 40 |
+
"""Immediate/manual processing path (e.g. UI 'preview now' button).
|
| 41 |
+
Attempts Gemini processing right away. NOT used by the automatic channel
|
| 42 |
+
polling flow โ that flow uses enqueue_raw_post() instead so that message
|
| 43 |
+
ingestion never depends on Gemini availability."""
|
| 44 |
+
raw_text = raw_text.strip()
|
| 45 |
+
if not raw_text:
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 49 |
+
if self.db.is_published(fingerprint):
|
| 50 |
+
logger.info(f"Article already processed: {fingerprint[:16]}...")
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
return await self._process_fresh(raw_text, source_url, media, fingerprint, channel_id)
|
| 54 |
+
|
| 55 |
+
def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None,
|
| 56 |
+
channel_id: str = "", section: str = "") -> Optional[str]:
|
| 57 |
+
"""Save an incoming raw post straight to the Gemini pending queue, WITHOUT ever
|
| 58 |
+
calling Gemini. This is the entry point used by the automatic channel-polling
|
| 59 |
+
scheduler, so that ingesting new posts never fails or blocks because of a
|
| 60 |
+
Gemini cooldown/quota issue. Returns the fingerprint if newly queued,
|
| 61 |
+
None if it's a duplicate or already being handled."""
|
| 62 |
+
raw_text = raw_text.strip()
|
| 63 |
+
if not raw_text:
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 67 |
+
if self.db.is_published(fingerprint):
|
| 68 |
+
return None
|
| 69 |
+
existing = self.db.get_article(fingerprint)
|
| 70 |
+
if existing and existing.get("status") in ("queued", "published", "gemini_pending", "processing"):
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 74 |
+
return fingerprint
|
| 75 |
+
|
| 76 |
+
def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str,
|
| 77 |
+
channel_id: str = "", section: str = ""):
|
| 78 |
+
article = {
|
| 79 |
+
"fingerprint": fingerprint,
|
| 80 |
+
"source_text": raw_text,
|
| 81 |
+
"source_url": source_url,
|
| 82 |
+
"media": media or [],
|
| 83 |
+
"channel_id": channel_id,
|
| 84 |
+
"status": "gemini_pending",
|
| 85 |
+
"created_at": int(time.time()),
|
| 86 |
+
}
|
| 87 |
+
self._save_article(article)
|
| 88 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 89 |
+
|
| 90 |
+
def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str,
|
| 91 |
+
media: List[Dict], channel_id: str, error: Exception,
|
| 92 |
+
article: Dict, section: str = ""):
|
| 93 |
+
"""Called whenever an unexpected error occurs while processing an article
|
| 94 |
+
(fresh or from the pending queue). Keeps the article retry-able in the
|
| 95 |
+
pending queue instead of losing it, up to MAX_PENDING_ATTEMPTS."""
|
| 96 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 97 |
+
if attempts == -1:
|
| 98 |
+
# Wasn't in the pending queue yet (e.g. failed during the "fresh" path) โ add it.
|
| 99 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 100 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 101 |
+
if attempts == -1:
|
| 102 |
+
attempts = 1
|
| 103 |
+
if attempts >= self.MAX_PENDING_ATTEMPTS:
|
| 104 |
+
logger.error(
|
| 105 |
+
f"Article {fingerprint[:16]} failed {attempts} times, giving up permanently: {error}"
|
| 106 |
+
)
|
| 107 |
+
article["status"] = "failed_permanent"
|
| 108 |
+
article["error"] = str(error)
|
| 109 |
+
self._save_article(article)
|
| 110 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 111 |
+
else:
|
| 112 |
+
logger.warning(
|
| 113 |
+
f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), "
|
| 114 |
+
f"kept in pending queue for retry: {error}"
|
| 115 |
+
)
|
| 116 |
+
article["status"] = "gemini_pending"
|
| 117 |
+
article["error"] = str(error)
|
| 118 |
+
self._save_article(article)
|
| 119 |
+
|
| 120 |
+
async def _process_fresh(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = "") -> Optional[Dict]:
|
| 121 |
+
article = {
|
| 122 |
+
"fingerprint": fingerprint,
|
| 123 |
+
"source_text": raw_text,
|
| 124 |
+
"source_url": source_url,
|
| 125 |
+
"media": media or [],
|
| 126 |
+
"channel_id": channel_id,
|
| 127 |
+
"status": "processing",
|
| 128 |
+
"created_at": int(time.time()),
|
| 129 |
+
}
|
| 130 |
+
try:
|
| 131 |
+
session_ok = await self.gemini.acquire_session()
|
| 132 |
+
if not session_ok:
|
| 133 |
+
logger.warning(f"Gemini session failed for {fingerprint[:16]}, saving to pending")
|
| 134 |
+
article["status"] = "gemini_pending"
|
| 135 |
+
self._save_article(article)
|
| 136 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 140 |
+
return result
|
| 141 |
+
except AllKeysExhausted:
|
| 142 |
+
logger.warning(f"All Gemini keys exhausted processing {fingerprint[:16]}, saving to pending")
|
| 143 |
+
article["status"] = "gemini_pending"
|
| 144 |
+
self._save_article(article)
|
| 145 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 146 |
+
return None
|
| 147 |
+
except Exception as e:
|
| 148 |
+
logger.exception(f"Article processing failed: {e}")
|
| 149 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article, section)
|
| 150 |
+
return None
|
| 151 |
+
finally:
|
| 152 |
+
self.gemini.release_session()
|
| 153 |
+
|
| 154 |
+
async def _process_next_pending(self) -> Optional[Dict]:
|
| 155 |
+
"""Try to process the first item in Gemini pending queue (FIFO).
|
| 156 |
+
Returns the processed article if successful, None otherwise."""
|
| 157 |
+
pending = self.db.get_gemini_pending_queue()
|
| 158 |
+
if not pending:
|
| 159 |
+
return None
|
| 160 |
+
first = pending[0]
|
| 161 |
+
raw_text = first.get("raw_text", "").strip()
|
| 162 |
+
fingerprint = first.get("fingerprint", "")
|
| 163 |
+
if not raw_text:
|
| 164 |
+
if fingerprint:
|
| 165 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 166 |
+
else:
|
| 167 |
+
self.db.remove_from_gemini_pending(0)
|
| 168 |
+
return None
|
| 169 |
+
source_url = first.get("source_url", "")
|
| 170 |
+
media = first.get("media", [])
|
| 171 |
+
channel_id = first.get("channel_id", "")
|
| 172 |
+
pending_section = first.get("section", "")
|
| 173 |
+
if not fingerprint:
|
| 174 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 175 |
+
|
| 176 |
+
if self.db.is_published(fingerprint):
|
| 177 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 178 |
+
return None
|
| 179 |
+
|
| 180 |
+
article = {
|
| 181 |
+
"fingerprint": fingerprint,
|
| 182 |
+
"source_text": raw_text,
|
| 183 |
+
"source_url": source_url,
|
| 184 |
+
"media": media,
|
| 185 |
+
"channel_id": channel_id,
|
| 186 |
+
"status": "processing",
|
| 187 |
+
"created_at": int(time.time()),
|
| 188 |
+
}
|
| 189 |
+
try:
|
| 190 |
+
session_ok = await self.gemini.acquire_session()
|
| 191 |
+
if not session_ok:
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 195 |
+
if result:
|
| 196 |
+
result["channel_id"] = channel_id
|
| 197 |
+
if pending_section and not result.get("section"):
|
| 198 |
+
result["section"] = pending_section
|
| 199 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 200 |
+
logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}")
|
| 201 |
+
return result
|
| 202 |
+
except AllKeysExhausted:
|
| 203 |
+
return None
|
| 204 |
+
except Exception as e:
|
| 205 |
+
logger.exception(f"Pending recovery failed for {fingerprint[:16]}: {e}")
|
| 206 |
+
# Keep the item in pending (up to MAX_PENDING_ATTEMPTS) instead of losing it.
|
| 207 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article)
|
| 208 |
+
return None
|
| 209 |
+
finally:
|
| 210 |
+
self.gemini.release_session()
|
| 211 |
+
|
| 212 |
+
async def _run_pipeline(self, article: Dict, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]:
|
| 213 |
+
"""Execute the full Gemini pipeline on raw_text and populate article dict."""
|
| 214 |
+
links = self._extract_links(raw_text)
|
| 215 |
+
rewrite = await self._rewrite(raw_text)
|
| 216 |
+
if rewrite:
|
| 217 |
+
article.update(rewrite)
|
| 218 |
+
body_text = article.get("body", "")
|
| 219 |
+
if body_text and links:
|
| 220 |
+
body_text = self._restore_links(body_text, links)
|
| 221 |
+
article["body"] = body_text
|
| 222 |
+
extracted = await self._extract(raw_text)
|
| 223 |
+
if extracted:
|
| 224 |
+
article["extracted"] = extracted
|
| 225 |
+
article["labels"] = []
|
| 226 |
+
summary = await self._summary(raw_text)
|
| 227 |
+
if summary:
|
| 228 |
+
article["summary"] = summary
|
| 229 |
+
notes = await self._notes(
|
| 230 |
+
extracted or {},
|
| 231 |
+
article.get("title", raw_text[:60]),
|
| 232 |
+
article.get("body", raw_text),
|
| 233 |
+
)
|
| 234 |
+
if notes:
|
| 235 |
+
article["notes"] = notes
|
| 236 |
+
keywords = await self._keywords(
|
| 237 |
+
article.get("title", raw_text[:60]),
|
| 238 |
+
article.get("body", raw_text),
|
| 239 |
+
extracted or {},
|
| 240 |
+
)
|
| 241 |
+
if keywords:
|
| 242 |
+
article["keywords"] = keywords
|
| 243 |
+
hashtags = await self._hashtags(
|
| 244 |
+
extracted or {},
|
| 245 |
+
article.get("title", raw_text[:60]),
|
| 246 |
+
article.get("body", raw_text),
|
| 247 |
+
)
|
| 248 |
+
if hashtags:
|
| 249 |
+
article["hashtags"] = hashtags
|
| 250 |
+
logger.info(f"Hashtags Stored: {hashtags}")
|
| 251 |
+
else:
|
| 252 |
+
logger.warning(f"Hashtags Stored: empty or None")
|
| 253 |
+
body_text = article.get("body", raw_text)
|
| 254 |
+
article["reading_time"] = self._reading_time(body_text)
|
| 255 |
+
if media:
|
| 256 |
+
alt_data = await self._alt_text(
|
| 257 |
+
article.get("title", raw_text[:60]),
|
| 258 |
+
article.get("body", raw_text),
|
| 259 |
+
)
|
| 260 |
+
if alt_data:
|
| 261 |
+
article["media_alt"] = alt_data
|
| 262 |
+
article["status"] = "processed"
|
| 263 |
+
article["processed_at"] = int(time.time())
|
| 264 |
+
self._save_article(article)
|
| 265 |
+
return article
|
| 266 |
+
|
| 267 |
+
def _fingerprint(self, text: str, url: str = "") -> str:
|
| 268 |
+
raw = f"{url}|{text[:300]}"
|
| 269 |
+
return hashlib.md5(raw.encode("utf-8", errors="replace")).hexdigest()
|
| 270 |
+
|
| 271 |
+
def _save_article(self, article: Dict):
|
| 272 |
+
aid = article.get("fingerprint", str(int(time.time())))
|
| 273 |
+
self.db.save_article(aid, article)
|
| 274 |
+
|
| 275 |
+
async def _rewrite(self, text: str) -> Optional[Dict]:
|
| 276 |
+
prompt = make_rewrite_prompt(text)
|
| 277 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE)
|
| 278 |
+
if not result:
|
| 279 |
+
logger.warning("Gemini _rewrite returned no result")
|
| 280 |
+
return None
|
| 281 |
+
logger.info("Gemini _rewrite succeeded")
|
| 282 |
+
return {
|
| 283 |
+
"title": result.get("title", text[:80]),
|
| 284 |
+
"body": result.get("body", f"<p>{text}</p>"),
|
| 285 |
+
"introduction": result.get("introduction", ""),
|
| 286 |
+
"faq": result.get("faq", []),
|
| 287 |
+
"conclusion": result.get("conclusion", ""),
|
| 288 |
+
"gemini_used": True,
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
async def _extract(self, text: str) -> Optional[Dict]:
|
| 292 |
+
prompt = make_extract_prompt(text)
|
| 293 |
+
return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT)
|
| 294 |
+
|
| 295 |
+
async def _seo(self, title: str, body: str) -> Optional[Dict]:
|
| 296 |
+
prompt = make_seo_prompt(title, body)
|
| 297 |
+
return await self.gemini.generate_json(prompt, SYSTEM_SEO)
|
| 298 |
+
|
| 299 |
+
async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 300 |
+
prompt = make_hashtag_prompt(extracted, title, body)
|
| 301 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS)
|
| 302 |
+
if result and isinstance(result, dict):
|
| 303 |
+
tags = result.get("hashtags", [])
|
| 304 |
+
if isinstance(tags, list):
|
| 305 |
+
logger.info(f"Hashtags Generated: {tags}")
|
| 306 |
+
return tags
|
| 307 |
+
logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}")
|
| 308 |
+
else:
|
| 309 |
+
logger.warning(f"Hashtags Generated: AI returned invalid data: {result}")
|
| 310 |
+
return []
|
| 311 |
+
|
| 312 |
+
async def _alt_text(self, title: str, body: str) -> Optional[Dict]:
|
| 313 |
+
prompt = f"""ุฃูุดุฆ ูุตู ALT ูุชุนููู ููุตูุฑุฉ ุจูุงุกู ุนูู:
|
| 314 |
+
ุงูุนููุงู: {title}
|
| 315 |
+
ุงูู
ุญุชูู: {body[:500]}
|
| 316 |
+
ุงูุฑุฏ JSON ููุท: {{"alt": "...", "caption": "..."}}"""
|
| 317 |
+
return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE)
|
| 318 |
+
|
| 319 |
+
# Legacy โ labels now come from section settings in scheduler
|
| 320 |
+
def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]:
|
| 321 |
+
labels = set()
|
| 322 |
+
if extracted.get("type"):
|
| 323 |
+
labels.add(extracted["type"])
|
| 324 |
+
if extracted.get("ministry"):
|
| 325 |
+
labels.add(extracted["ministry"])
|
| 326 |
+
if extracted.get("province"):
|
| 327 |
+
labels.add(extracted["province"])
|
| 328 |
+
if extracted.get("city"):
|
| 329 |
+
labels.add(extracted["city"])
|
| 330 |
+
if extracted.get("company"):
|
| 331 |
+
labels.add(extracted["company"])
|
| 332 |
+
seo_labels = seo.get("labels", [])
|
| 333 |
+
if isinstance(seo_labels, list):
|
| 334 |
+
for lbl in seo_labels:
|
| 335 |
+
if lbl:
|
| 336 |
+
labels.add(str(lbl))
|
| 337 |
+
return list(labels)[:10]
|
| 338 |
+
|
| 339 |
+
async def _summary(self, text: str) -> Optional[str]:
|
| 340 |
+
prompt = make_summary_prompt(text)
|
| 341 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY)
|
| 342 |
+
if result and isinstance(result, dict):
|
| 343 |
+
return result.get("summary", "")
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
+
async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 347 |
+
prompt = make_notes_prompt(extracted, title, body)
|
| 348 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_NOTES)
|
| 349 |
+
if result and isinstance(result, dict):
|
| 350 |
+
notes = result.get("notes", [])
|
| 351 |
+
if isinstance(notes, list) and notes:
|
| 352 |
+
return notes
|
| 353 |
+
return None
|
| 354 |
+
|
| 355 |
+
async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]:
|
| 356 |
+
prompt = make_keywords_prompt(title, body, extracted)
|
| 357 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS)
|
| 358 |
+
if result and isinstance(result, dict):
|
| 359 |
+
kw = result.get("keywords", "")
|
| 360 |
+
if kw and isinstance(kw, str):
|
| 361 |
+
return kw
|
| 362 |
+
return None
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _reading_time(body_html: str) -> int:
|
| 366 |
+
text = re.sub(r'<[^>]+>', '', body_html)
|
| 367 |
+
word_count = len(text.split())
|
| 368 |
+
minutes = max(1, round(word_count / 150))
|
| 369 |
+
return minutes
|
| 370 |
+
|
| 371 |
+
@staticmethod
|
| 372 |
+
def _extract_links(text: str) -> List[str]:
|
| 373 |
+
return re.findall(r'https?://[^\s<>"\']+', text)
|
| 374 |
+
|
| 375 |
+
def _restore_links(self, body: str, links: List[str]) -> str:
|
| 376 |
+
app_links = []
|
| 377 |
+
restored = body
|
| 378 |
+
for link in links:
|
| 379 |
+
if link not in restored:
|
| 380 |
+
if any(kw in link.lower() for kw in ["apply", "form", "jobs", "ุชูุฏูู
", "ูุฏู
", "ุชุณุฌูู"]):
|
| 381 |
+
app_links.append(link)
|
| 382 |
+
elif any(kw in link.lower() for kw in ["t.me", "telegram", "docs.google", "forms"]):
|
| 383 |
+
if link not in restored:
|
| 384 |
+
restored += f'\n<p><a href="{link}">๐ ุฑุงุจุท ุฎุงุฑุฌู</a></p>'
|
| 385 |
+
else:
|
| 386 |
+
if link not in restored:
|
| 387 |
+
restored += f'\n<p><a href="{link}">๐ ุฑุงุจุท ุฎุงุฑุฌู</a></p>'
|
| 388 |
+
if app_links:
|
| 389 |
+
app_section = '<div style="background:#e8f5e9;border-right:4px solid #4caf50;padding:12px 16px;margin:15px 0;border-radius:4px;">'
|
| 390 |
+
app_section += '<strong style="color:#2e7d32;">๐ ุฑุงุจุท ุงูุชูุฏูู
</strong>'
|
| 391 |
+
for al in app_links:
|
| 392 |
+
app_section += f'<p style="margin:5px 0 0 0;"><a href="{al}" target="_blank" rel="noopener" style="color:#1a73e8;font-weight:bold;">{al[:80]}</a></p>'
|
| 393 |
+
app_section += '</div>'
|
| 394 |
+
restored = restored + '\n' + app_section
|
| 395 |
+
return restored
|
| 396 |
+
|
| 397 |
+
def _add_inline_hashtags(self, body: str, extracted: Dict) -> str:
|
| 398 |
+
entities = []
|
| 399 |
+
if extracted.get("city"):
|
| 400 |
+
entities.append(extracted["city"])
|
| 401 |
+
if extracted.get("province"):
|
| 402 |
+
entities.append(extracted["province"])
|
| 403 |
+
if extracted.get("ministry"):
|
| 404 |
+
entities.append(extracted["ministry"])
|
| 405 |
+
if extracted.get("company"):
|
| 406 |
+
entities.append(extracted["company"])
|
| 407 |
+
if extracted.get("university"):
|
| 408 |
+
entities.append(extracted["university"])
|
| 409 |
+
if extracted.get("organization"):
|
| 410 |
+
entities.append(extracted["organization"])
|
| 411 |
+
if extracted.get("job_type"):
|
| 412 |
+
entities.append(extracted["job_type"])
|
| 413 |
+
if extracted.get("district"):
|
| 414 |
+
entities.append(extracted["district"])
|
| 415 |
+
result = body
|
| 416 |
+
for entity in entities:
|
| 417 |
+
if entity and len(entity) > 2:
|
| 418 |
+
tag = entity.replace(" ", "_")
|
| 419 |
+
replacement = f'<a href="https://www.blogger.com/search?q={tag}" style="text-decoration:none;color:#1a73e8;">#{tag}</a>'
|
| 420 |
+
result = result.replace(entity, replacement, 1)
|
| 421 |
+
return result
|
| 422 |
+
|
| 423 |
+
def make_article_html(self, article: Dict) -> str:
|
| 424 |
+
parts = []
|
| 425 |
+
section = article.get("section", "")
|
| 426 |
+
# Consistent heading styles across all articles
|
| 427 |
+
parts.append('<style>h2,h3{font-weight:bold!important;margin:18px 0 10px 0;clear:both;}</style>')
|
| 428 |
+
|
| 429 |
+
# โโ 1. Featured Image โโ
|
| 430 |
+
parts.append(self._make_featured_image(article))
|
| 431 |
+
|
| 432 |
+
# โโ 2. Summary Box โโ
|
| 433 |
+
summary = article.get("summary", "")
|
| 434 |
+
if summary:
|
| 435 |
+
parts.append(self._make_summary_box(summary))
|
| 436 |
+
|
| 437 |
+
# โโ 3. Quick Information Card (enhanced for jobs) โโ
|
| 438 |
+
info_card = self._make_info_card(article)
|
| 439 |
+
if info_card:
|
| 440 |
+
parts.append(info_card)
|
| 441 |
+
|
| 442 |
+
# โโ 4. Apply & Contact Section (email, phone, apply_url) โโ
|
| 443 |
+
apply_section = self._make_apply_section(article)
|
| 444 |
+
if apply_section:
|
| 445 |
+
parts.append(apply_section)
|
| 446 |
+
|
| 447 |
+
# โโ 5. Table of Contents โโ
|
| 448 |
+
body = article.get("body", "")
|
| 449 |
+
toc, processed_body = self._make_toc(body)
|
| 450 |
+
if toc:
|
| 451 |
+
parts.append(toc)
|
| 452 |
+
|
| 453 |
+
# โโ 6. Introduction โโ
|
| 454 |
+
intro = article.get("introduction", "")
|
| 455 |
+
if intro:
|
| 456 |
+
parts.append(f'<h2 id="intro" style="font-size:18px;font-weight:bold;margin:18px 0 10px 0;color:#222;">ุงูู
ูุฏู
ุฉ</h2><p style="color:#444;line-height:1.7;">{intro}</p>')
|
| 457 |
+
|
| 458 |
+
# โโ 7. Read More + Full Article Body โโ
|
| 459 |
+
body_to_process = processed_body or body
|
| 460 |
+
if body_to_process:
|
| 461 |
+
parts.append(self._make_read_more(body_to_process))
|
| 462 |
+
|
| 463 |
+
# โโ 9. Important Notes โโ
|
| 464 |
+
notes = article.get("notes", [])
|
| 465 |
+
if notes:
|
| 466 |
+
parts.append(self._make_notes_box(notes))
|
| 467 |
+
|
| 468 |
+
# โโ 10. FAQ โโ
|
| 469 |
+
faq = article.get("faq", [])
|
| 470 |
+
if faq:
|
| 471 |
+
parts.append(self._make_faq(faq))
|
| 472 |
+
|
| 473 |
+
# โโ 11. Conclusion โโ
|
| 474 |
+
conclusion = article.get("conclusion", "")
|
| 475 |
+
if conclusion:
|
| 476 |
+
parts.append(f'<p>{conclusion}</p>')
|
| 477 |
+
|
| 478 |
+
# โโ 12. Hashtags โโ
|
| 479 |
+
hashtags = article.get("hashtags", [])
|
| 480 |
+
logger.info(f"Hashtags Before HTML: {hashtags}")
|
| 481 |
+
if hashtags:
|
| 482 |
+
parts.append(self._make_hashtags_section(hashtags))
|
| 483 |
+
|
| 484 |
+
# โโ 13. Source โโ
|
| 485 |
+
source = article.get("source", {})
|
| 486 |
+
if source:
|
| 487 |
+
parts.append(self._make_source(source))
|
| 488 |
+
|
| 489 |
+
# โโ 14. Keywords โโ
|
| 490 |
+
keywords = article.get("keywords", "")
|
| 491 |
+
if keywords:
|
| 492 |
+
parts.append(self._make_keywords_section(keywords))
|
| 493 |
+
|
| 494 |
+
# โโ 15. Schema JSON-LD โโ
|
| 495 |
+
schema = self._make_schema(article)
|
| 496 |
+
if schema:
|
| 497 |
+
parts.append(schema)
|
| 498 |
+
|
| 499 |
+
return "\n".join(parts)
|
| 500 |
+
|
| 501 |
+
def _make_featured_image(self, article: Dict) -> str:
|
| 502 |
+
alt_text = article.get("media_alt", {}).get("alt", "")
|
| 503 |
+
caption = article.get("media_alt", {}).get("caption", "")
|
| 504 |
+
img_src = None
|
| 505 |
+
if self.config:
|
| 506 |
+
img_src = self.config.get("default_jobs_image", "")
|
| 507 |
+
if not img_src:
|
| 508 |
+
return ""
|
| 509 |
+
alt = alt_text or "ุตูุฑุฉ ุงูู
ูุงู"
|
| 510 |
+
title = article.get("title", "")[:60]
|
| 511 |
+
img = f'<p style="text-align:center;"><img src="{img_src}" alt="{alt}" title="{title}" loading="lazy" style="width:100%;max-width:100%;height:auto;border-radius:8px;" /></p>'
|
| 512 |
+
if caption:
|
| 513 |
+
img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>'
|
| 514 |
+
return img
|
| 515 |
+
|
| 516 |
+
def _make_info_card(self, article: Dict) -> str:
|
| 517 |
+
extracted = article.get("extracted", {})
|
| 518 |
+
if not extracted:
|
| 519 |
+
return ""
|
| 520 |
+
section = article.get("section", "")
|
| 521 |
+
is_job = section in ("jobs", "ูุธุงุฆู") or bool(extracted.get("salary"))
|
| 522 |
+
rows = []
|
| 523 |
+
if is_job:
|
| 524 |
+
title = article.get("title", "")
|
| 525 |
+
if title:
|
| 526 |
+
rows.append(("๐ ุงูู
ุณู
ู ุงููุธููู", title))
|
| 527 |
+
if extracted.get("company"):
|
| 528 |
+
rows.append(("๐ข ุงูุดุฑูุฉ", extracted["company"]))
|
| 529 |
+
elif extracted.get("ministry"):
|
| 530 |
+
rows.append(("๐๏ธ ุงูุฌูุฉ", extracted["ministry"]))
|
| 531 |
+
if extracted.get("province"):
|
| 532 |
+
rows.append(("๐ ุงูู
ุญุงูุธุฉ", extracted["province"]))
|
| 533 |
+
if extracted.get("city"):
|
| 534 |
+
rows.append(("๐ ุงูู
ุฏููุฉ", extracted["city"]))
|
| 535 |
+
if extracted.get("job_type"):
|
| 536 |
+
rows.append(("๐ผ ููุน ุงููุธููุฉ", extracted["job_type"]))
|
| 537 |
+
if extracted.get("qualification"):
|
| 538 |
+
rows.append(("๐ ุงูู
ุคูู", extracted["qualification"]))
|
| 539 |
+
if extracted.get("salary"):
|
| 540 |
+
rows.append(("๐ฐ ุงูุฑุงุชุจ", extracted["salary"]))
|
| 541 |
+
if extracted.get("experience"):
|
| 542 |
+
rows.append(("โณ ุงูุฎุจุฑุฉ", extracted["experience"]))
|
| 543 |
+
if extracted.get("deadline"):
|
| 544 |
+
rows.append(("๐
ุขุฎุฑ ู
ูุนุฏ", extracted["deadline"]))
|
| 545 |
+
if extracted.get("gender"):
|
| 546 |
+
rows.append(("๐ค ุงูุฌูุณ", extracted["gender"]))
|
| 547 |
+
if extracted.get("positions"):
|
| 548 |
+
rows.append(("๐ฅ ุนุฏุฏ ุงูุดูุงุบุฑ", extracted["positions"]))
|
| 549 |
+
if extracted.get("apply_method"):
|
| 550 |
+
rows.append(("๐ ุทุฑููุฉ ุงูุชูุฏูู
", extracted["apply_method"]))
|
| 551 |
+
created = article.get("created_at", 0)
|
| 552 |
+
if created:
|
| 553 |
+
pub_date = time.strftime("%Y/%m/%d", time.localtime(created))
|
| 554 |
+
rows.append(("๐
ุชุงุฑูุฎ ุงููุดุฑ", pub_date))
|
| 555 |
+
else:
|
| 556 |
+
if extracted.get("ministry"):
|
| 557 |
+
rows.append(("๐๏ธ ุงูุฌูุฉ", extracted["ministry"]))
|
| 558 |
+
elif extracted.get("company"):
|
| 559 |
+
rows.append(("๐ข ุงูุดุฑูุฉ", extracted["company"]))
|
| 560 |
+
if extracted.get("province"):
|
| 561 |
+
rows.append(("๐ ุงูู
ุญุงูุธุฉ", extracted["province"]))
|
| 562 |
+
if extracted.get("city"):
|
| 563 |
+
rows.append(("๐ ุงูู
ุฏููุฉ", extracted["city"]))
|
| 564 |
+
reading_time = article.get("reading_time", self._reading_time(article.get("body", "")))
|
| 565 |
+
rows.append(("โฑ๏ธ ู
ุฏุฉ ุงููุฑุงุกุฉ", f"{reading_time} ุฏูููุฉ"))
|
| 566 |
+
rows.append(("๐ ุงููุณู
", section or "ุนุงู
"))
|
| 567 |
+
thead = '<tr style="background:#2c3e50;color:#fff;"><th style="padding:10px 14px;border:1px solid #2c3e50;text-align:right;font-size:15px;">ุงูู
ุนููู
ุฉ</th><th style="padding:10px 14px;border:1px solid #2c3e50;text-align:right;font-size:15px;">ุงูุชูุงุตูู</th></tr>'
|
| 568 |
+
trows = "".join(f'<tr style="background:{ "#fff" if i%2==0 else "#f8f9fa" };"><td style="padding:8px 14px;border:1px solid #dee2e6;font-weight:bold;white-space:nowrap;color:#2c3e50;">{k}</td><td style="padding:8px 14px;border:1px solid #dee2e6;color:#495057;">{v}</td></tr>' for i, (k, v) in enumerate(rows))
|
| 569 |
+
return f'<div style="margin:15px 0;font-size:14px;direction:rtl;text-align:right;overflow-x:auto;"><table style="width:100%;border-collapse:collapse;font-family:Tahoma,Arial,sans-serif;">{thead}{trows}</table></div>'
|
| 570 |
+
|
| 571 |
+
def _make_apply_section(self, article: Dict) -> str:
|
| 572 |
+
extracted = article.get("extracted", {})
|
| 573 |
+
items = []
|
| 574 |
+
email = extracted.get("email", "")
|
| 575 |
+
phone = extracted.get("phone", "")
|
| 576 |
+
apply_url = extracted.get("apply_url", "")
|
| 577 |
+
if email:
|
| 578 |
+
items.append(f'<div style="text-align:center;background:#e3f2fd;border:1px solid #90caf9;border-radius:8px;padding:12px 16px;margin:8px 0;"><strong style="color:#1565c0;font-size:15px;">๐ง ุงูุจุฑูุฏ ุงูุฅููุชุฑููู</strong><p style="margin:6px 0 0 0;font-size:14px;direction:ltr;text-align:center;"><a href="mailto:{email}" style="color:#0d47a1;text-decoration:none;font-weight:bold;">{email}</a></p></div>')
|
| 579 |
+
if phone:
|
| 580 |
+
items.append(f'<div style="text-align:center;background:#e8f5e9;border:1px solid #a5d6a7;border-radius:8px;padding:12px 16px;margin:8px 0;"><strong style="color:#2e7d32;font-size:15px;">๐ ุฑูู
ุงููุงุชู</strong><p style="margin:6px 0 0 0;font-size:14px;direction:ltr;text-align:center;font-weight:bold;color:#1b5e20;">{phone}</p></div>')
|
| 581 |
+
if apply_url:
|
| 582 |
+
items.append(f'<div style="text-align:center;background:#fff3e0;border:1px solid #ffcc80;border-radius:8px;padding:12px 16px;margin:8px 0;"><strong style="color:#e65100;font-size:15px;">๐ ุฑุงุจุท ุงูุชูุฏูู
</strong><p style="margin:6px 0 0 0;font-size:14px;text-align:center;"><a href="{apply_url}" target="_blank" rel="noopener" style="color:#bf360c;text-decoration:none;font-weight:bold;word-break:break-all;">{apply_url}</a></p></div>')
|
| 583 |
+
if not items:
|
| 584 |
+
return ""
|
| 585 |
+
inner = "\n".join(items)
|
| 586 |
+
return f'<div style="margin:15px 0;padding:15px;background:#fafafa;border-radius:8px;border:1px solid #e0e0e0;"><h2 style="font-size:17px;font-weight:bold;text-align:center;margin:0 0 12px 0;color:#333;">๐ฌ ุทุฑููุฉ ุงูุชูุฏูู
ูุงูุชูุงุตู</h2>{inner}</div>'
|
| 587 |
+
|
| 588 |
+
def _make_summary_box(self, summary: str) -> str:
|
| 589 |
+
return f'<div style="background:#fffbea;border-right:4px solid #f5c518;padding:12px 16px;margin:15px 0;border-radius:4px;"><strong style="color:#856404;">๐ ู
ูุฎุต ุงูู
ูุงู</strong><p style="margin:8px 0 0 0;color:#856404;font-size:15px;">{summary}</p></div>'
|
| 590 |
+
|
| 591 |
+
def _make_toc(self, body: str) -> tuple:
|
| 592 |
+
if not body:
|
| 593 |
+
return "", body
|
| 594 |
+
headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL)
|
| 595 |
+
if len(headings) < 2:
|
| 596 |
+
return "", body
|
| 597 |
+
items = []
|
| 598 |
+
processed = body
|
| 599 |
+
for i, (level, text) in enumerate(headings):
|
| 600 |
+
anchor = f"sec-{i}"
|
| 601 |
+
items.append(f'<li><a href="#{anchor}" style="text-decoration:none;">{text}</a></li>')
|
| 602 |
+
processed = processed.replace(
|
| 603 |
+
f'<h{level}>{text}</h{level}>',
|
| 604 |
+
f'<h{level} id="{anchor}">{text}</h{level}>', 1
|
| 605 |
+
)
|
| 606 |
+
toc = f'<div style="background:#f8f9fa;border-radius:8px;padding:12px 16px;margin:15px 0;"><strong style="font-size:16px;">๐ ุงูู
ุญุชููุงุช</strong><ul style="margin:8px 0 0 0;list-style:none;padding:0;">{"".join(items)}</ul></div>'
|
| 607 |
+
return toc, processed
|
| 608 |
+
|
| 609 |
+
def _make_read_more(self, body: str) -> str:
|
| 610 |
+
parts = re.split(r'(<(?:p|h[23]|div|ul|ol|table)[^>]*>)', body, maxsplit=8)
|
| 611 |
+
if len(parts) < 6:
|
| 612 |
+
return body
|
| 613 |
+
preview = parts[0]
|
| 614 |
+
for i in range(1, min(6, len(parts))):
|
| 615 |
+
preview += parts[i]
|
| 616 |
+
rest = "".join(parts[6:])
|
| 617 |
+
if not rest.strip():
|
| 618 |
+
return body
|
| 619 |
+
return f'<div>{preview}</div><details style="margin:10px 0;"><summary style="cursor:pointer;background:#1a73e8;color:#fff;font-weight:bold;padding:8px 20px;border-radius:6px;display:inline-block;">๐ ู
ุชุงุจุนุฉ ูุฑุงุกุฉ ุงูู
ูุงู</summary><div style="margin-top:12px;">{rest}</div></details>'
|
| 620 |
+
|
| 621 |
+
def _make_extracted_table(self, extracted: Dict) -> str:
|
| 622 |
+
table_rows = []
|
| 623 |
+
labels_map = {
|
| 624 |
+
"ministry": "ุงููุฒุงุฑุฉ", "company": "ุงูุดุฑูุฉ", "province": "ุงูู
ุญุงูุธุฉ",
|
| 625 |
+
"city": "ุงูู
ุฏููุฉ", "salary": "ุงูุฑุงุชุจ", "qualification": "ุงูู
ุคูู",
|
| 626 |
+
"gender": "ุงูุฌูุณ", "age": "ุงูุนู
ุฑ", "experience": "ุงูุฎุจุฑุฉ",
|
| 627 |
+
"deadline": "ุขุฎุฑ ู
ูุนุฏ", "apply_url": "ุฑุงุจุท ุงูุชูุฏูู
",
|
| 628 |
+
"email": "ุงูุจุฑูุฏ ุงูุฅููุชุฑููู", "phone": "ุงููุงุชู",
|
| 629 |
+
}
|
| 630 |
+
for key, label in labels_map.items():
|
| 631 |
+
val = extracted.get(key)
|
| 632 |
+
if val:
|
| 633 |
+
val_str = str(val)
|
| 634 |
+
if key == "apply_url" and val_str.startswith("http"):
|
| 635 |
+
val_str = f'<a href="{val_str}">ุฑุงุจุท ุงูุชูุฏูู
</a>'
|
| 636 |
+
table_rows.append(f'<tr><td>{label}</td><td>{val_str}</td></tr>')
|
| 637 |
+
if not table_rows:
|
| 638 |
+
return ""
|
| 639 |
+
return f'<h2>ู
ุนููู
ุงุช ุฅุถุงููุฉ</h2><table>{"".join(table_rows)}</table>'
|
| 640 |
+
|
| 641 |
+
def _make_notes_box(self, notes: list) -> str:
|
| 642 |
+
lis = "".join(f"<li>{n}</li>" for n in notes)
|
| 643 |
+
return f'<div style="background:#fff3f3;border-right:4px solid #dc3545;padding:12px 16px;margin:15px 0;border-radius:4px;"><strong style="color:#721c24;">โ ๏ธ ู
ูุงุญุธุงุช ู
ูู
ุฉ</strong><ul style="margin:8px 0 0 0;color:#721c24;">{lis}</ul></div>'
|
| 644 |
+
|
| 645 |
+
def _make_faq(self, faq: list) -> str:
|
| 646 |
+
items = ""
|
| 647 |
+
for item in faq:
|
| 648 |
+
q = item.get("question", "")
|
| 649 |
+
a = item.get("answer", "")
|
| 650 |
+
if q and a:
|
| 651 |
+
items += f'<h3 itemscope itemprop="mainEntity" itemtype="https://schema.org/Question" style="font-size:16px;margin-top:15px;">{q}</h3><div itemprop="acceptedAnswer" itemscope itemtype="https://schema.org/Answer"><p itemprop="text">{a}</p></div>'
|
| 652 |
+
if not items:
|
| 653 |
+
return ""
|
| 654 |
+
return f'<h2 style="font-size:18px;font-weight:bold;margin:18px 0 10px 0;color:#222;">ุงูุฃุณุฆูุฉ ุงูุดุงุฆุนุฉ</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div>'
|
| 655 |
+
|
| 656 |
+
def _make_source(self, source: dict) -> str:
|
| 657 |
+
name = source.get("name", "ุงูู
ุตุฏุฑ")
|
| 658 |
+
username = source.get("username", "")
|
| 659 |
+
link = source.get("link", "")
|
| 660 |
+
if link and username and not username.startswith("private"):
|
| 661 |
+
return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>ุงูู
ุตุฏุฑ:</strong> <a href="{link}" target="_blank" rel="noopener">{name}</a></div>'
|
| 662 |
+
return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>ุงูู
ุตุฏุฑ:</strong> {name}</div>'
|
| 663 |
+
|
| 664 |
+
def _make_keywords_section(self, keywords: str) -> str:
|
| 665 |
+
return f'<div style="margin:15px 0;padding:10px 12px;background:#f8f9fa;border-radius:4px;"><strong style="font-size:14px;">๐ท๏ธ ุงูููู
ุงุช ุงูุฏูุงููุฉ:</strong><p style="color:#666;margin:5px 0 0 0;font-size:13px;">{keywords}</p></div>'
|
| 666 |
+
|
| 667 |
+
def _make_hashtags_section(self, hashtags: List[str]) -> str:
|
| 668 |
+
tags_str = " | ".join(hashtags)
|
| 669 |
+
return f'<div style="margin:15px 0;padding:10px 12px;background:#f8f9fa;border-radius:4px;"><strong style="font-size:14px;">๐ท๏ธ ุงููุงุดุชุงูุงุช:</strong><p style="color:#666;margin:5px 0 0 0;font-size:13px;direction:rtl;text-align:right;">{tags_str}</p></div>'
|
| 670 |
+
|
| 671 |
+
def _make_schema(self, article: Dict) -> str:
|
| 672 |
+
title = article.get("title", "")
|
| 673 |
+
intro = article.get("introduction", "")
|
| 674 |
+
body = article.get("body", "")
|
| 675 |
+
text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300]
|
| 676 |
+
section = article.get("section", "")
|
| 677 |
+
is_news = section not in ("jobs", "ูุธุงุฆู")
|
| 678 |
+
schema = {
|
| 679 |
+
"@context": "https://schema.org",
|
| 680 |
+
"@type": "NewsArticle" if is_news else "Article",
|
| 681 |
+
"headline": title,
|
| 682 |
+
"description": text[:160],
|
| 683 |
+
"articleBody": text,
|
| 684 |
+
"inLanguage": "ar",
|
| 685 |
+
"author": {"@type": "Organization", "name": "ุงูู
ุฏููุฉ"},
|
| 686 |
+
"publisher": {"@type": "Organization", "name": "ุงูู
ุฏููุฉ"},
|
| 687 |
+
"datePublished": article.get("created_at", ""),
|
| 688 |
+
"dateModified": article.get("processed_at", ""),
|
| 689 |
+
}
|
| 690 |
+
schema_str = json.dumps(schema, ensure_ascii=False)
|
| 691 |
+
return f'<script type="application/ld+json">{schema_str}</script>'
|
| 692 |
+
|
| 693 |
+
def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]:
|
| 694 |
+
html = self.make_article_html(article)
|
| 695 |
+
image = None
|
| 696 |
+
media = article.get("media", [])
|
| 697 |
+
for m in media:
|
| 698 |
+
if m.get("type") == "photo":
|
| 699 |
+
image = m.get("file_id")
|
| 700 |
+
break
|
| 701 |
+
if not image and self.config:
|
| 702 |
+
section = article.get("section", "")
|
| 703 |
+
if section in ("jobs", "ูุธุงุฆู", "general"):
|
| 704 |
+
image = self.config.get("default_jobs_image", "")
|
| 705 |
+
telegram_text = self.html_to_telegram(html)
|
| 706 |
+
title = article.get("title", "")
|
| 707 |
+
if title:
|
| 708 |
+
telegram_text = f"<b>{title}</b>\n\n{telegram_text}"
|
| 709 |
+
reading_time = article.get("reading_time", 0)
|
| 710 |
+
if reading_time:
|
| 711 |
+
telegram_text += f"\nโฑ๏ธ ู
ุฏุฉ ุงููุฑุงุกุฉ: {reading_time} ุฏูููุฉ"
|
| 712 |
+
labels = article.get("labels", [])
|
| 713 |
+
if labels:
|
| 714 |
+
telegram_text += f"\n๐ท {', '.join(labels)}"
|
| 715 |
+
return image, telegram_text
|
| 716 |
+
|
| 717 |
+
@staticmethod
|
| 718 |
+
def html_to_telegram(html: str) -> str:
|
| 719 |
+
html = re.sub(r'<script[^>]*>.*?</script>', '', html, flags=re.DOTALL)
|
| 720 |
+
|
| 721 |
+
def _replace_table(m):
|
| 722 |
+
rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL)
|
| 723 |
+
lines = []
|
| 724 |
+
for row in rows:
|
| 725 |
+
cells = re.findall(r'<td[^>]*>(.*?)</td>', row, re.DOTALL)
|
| 726 |
+
if cells:
|
| 727 |
+
lines.append(' | '.join(cells))
|
| 728 |
+
return '\n'.join(lines) + '\n'
|
| 729 |
+
html = re.sub(r'<table>(.*?)</table>', _replace_table, html, flags=re.DOTALL)
|
| 730 |
+
html = re.sub(r'<img[^>]*>', '', html)
|
| 731 |
+
html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL)
|
| 732 |
+
html = re.sub(r'<li>(.*?)</li>', r'โข \1', html, flags=re.DOTALL)
|
| 733 |
+
html = re.sub(r'</?u?[ol][^>]*>', '', html)
|
| 734 |
+
html = re.sub(r'<details[^>]*>', '', html)
|
| 735 |
+
html = re.sub(r'</details>', '', html)
|
| 736 |
+
html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL)
|
| 737 |
+
html = re.sub(r'</?div[^>]*>', '', html)
|
| 738 |
+
html = re.sub(r'</?span[^>]*>', '', html)
|
| 739 |
+
html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL)
|
| 740 |
+
html = re.sub(r'<br\s*/?>', '\n', html)
|
| 741 |
+
html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html)
|
| 742 |
+
html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html)
|
| 743 |
+
html = re.sub(r'</?t[rdh][^>]*>', '', html)
|
| 744 |
+
allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'}
|
| 745 |
+
html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE)
|
| 746 |
+
html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE)
|
| 747 |
+
html = re.sub(r'\n{3,}', '\n\n', html)
|
| 748 |
+
return html.strip()
|
modules/blogger/scheduler.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import time
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Optional, Dict, Any, List
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
|
| 7 |
+
from modules.blogger.database import BloggerDatabase
|
| 8 |
+
from modules.blogger.processor import ArticleProcessor
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
POLL_INTERVAL = 600
|
| 13 |
+
SCHEDULE_START_HOUR = 9
|
| 14 |
+
SCHEDULE_END_HOUR = 23
|
| 15 |
+
SCHEDULE_INTERVAL_MIN = 30
|
| 16 |
+
SLOTS_PER_DAY = ((SCHEDULE_END_HOUR - SCHEDULE_START_HOUR) * 60) // SCHEDULE_INTERVAL_MIN + 1
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class BloggerScheduler:
|
| 20 |
+
def __init__(self, db: BloggerDatabase, processor: ArticleProcessor, publisher):
|
| 21 |
+
self.db = db
|
| 22 |
+
self.processor = processor
|
| 23 |
+
self.publisher = publisher
|
| 24 |
+
self._running = False
|
| 25 |
+
self._queue: List[Dict] = []
|
| 26 |
+
|
| 27 |
+
async def start(self):
|
| 28 |
+
self._running = True
|
| 29 |
+
logger.info("BloggerScheduler: started")
|
| 30 |
+
self._queue = self.db.get_articles_by_status("queued")
|
| 31 |
+
logger.info(f"BloggerScheduler: loaded {len(self._queue)} queued articles from DB")
|
| 32 |
+
if self._queue:
|
| 33 |
+
logger.info(f"DB Load Sample Section: {self._queue[0].get('section', 'MISSING')}")
|
| 34 |
+
while self._running:
|
| 35 |
+
try:
|
| 36 |
+
await self._cycle()
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.exception(f"BloggerScheduler: cycle error: {e}")
|
| 39 |
+
await asyncio.sleep(POLL_INTERVAL)
|
| 40 |
+
|
| 41 |
+
async def stop(self):
|
| 42 |
+
self._running = False
|
| 43 |
+
logger.info("BloggerScheduler: stopped")
|
| 44 |
+
|
| 45 |
+
async def _cycle(self):
|
| 46 |
+
logger.info("BloggerScheduler: cycle start")
|
| 47 |
+
if not self.publisher.config.is_enabled():
|
| 48 |
+
logger.info("BloggerScheduler: publisher disabled, skipping cycle")
|
| 49 |
+
return
|
| 50 |
+
channels = self.db.get_all_channels()
|
| 51 |
+
if not channels:
|
| 52 |
+
logger.info("BloggerScheduler: no channels configured, skipping cycle")
|
| 53 |
+
return
|
| 54 |
+
logger.info(f"BloggerScheduler: {len(channels)} channels, starting fetch")
|
| 55 |
+
await self._fetch_new_posts(channels)
|
| 56 |
+
logger.info("BloggerScheduler: fetch done")
|
| 57 |
+
await self._process_gemini_pending()
|
| 58 |
+
await self._process_queue()
|
| 59 |
+
logger.info("BloggerScheduler: cycle end")
|
| 60 |
+
|
| 61 |
+
async def _fetch_new_posts(self, channels: List[Dict]):
|
| 62 |
+
from bot_core import user_client
|
| 63 |
+
if not user_client:
|
| 64 |
+
logger.warning("BloggerScheduler: user_client not available for polling")
|
| 65 |
+
return
|
| 66 |
+
for ch in channels:
|
| 67 |
+
if not ch.get("enabled", True):
|
| 68 |
+
logger.info(f"BloggerScheduler: channel {ch.get('channel_id')} disabled, skip")
|
| 69 |
+
continue
|
| 70 |
+
ch_id = ch.get("channel_id", "")
|
| 71 |
+
if not ch_id:
|
| 72 |
+
continue
|
| 73 |
+
try:
|
| 74 |
+
last_id = ch.get("last_message_id", 0)
|
| 75 |
+
chat_identifier = int(ch_id) if str(ch_id).lstrip('-').isdigit() else ch_id
|
| 76 |
+
latest_id = last_id
|
| 77 |
+
any_success = False
|
| 78 |
+
logger.info(f"BloggerScheduler: polling channel {ch_id}, last_id={last_id}")
|
| 79 |
+
|
| 80 |
+
# Drive the async generator manually so a single corrupted message
|
| 81 |
+
# (e.g. Pyrogram failing to decode its entities) can be skipped
|
| 82 |
+
# without losing the rest of the batch or blocking last_message_id.
|
| 83 |
+
history_iter = user_client.get_chat_history(chat_identifier, limit=3).__aiter__()
|
| 84 |
+
while True:
|
| 85 |
+
try:
|
| 86 |
+
msg = await history_iter.__anext__()
|
| 87 |
+
except StopAsyncIteration:
|
| 88 |
+
break
|
| 89 |
+
except UnicodeDecodeError as e:
|
| 90 |
+
logger.warning(
|
| 91 |
+
f"BloggerScheduler: skipping a message in {ch_id} โ "
|
| 92 |
+
f"Pyrogram failed to decode it ({e}). Cannot recover its content; "
|
| 93 |
+
f"continuing with the rest of the batch."
|
| 94 |
+
)
|
| 95 |
+
continue
|
| 96 |
+
except Exception as e:
|
| 97 |
+
logger.warning(f"BloggerScheduler: error fetching next message in {ch_id}, skipping it: {e}")
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
if msg.id <= last_id:
|
| 101 |
+
logger.info(f"BloggerScheduler: msg {msg.id} <= last_id {last_id}, break")
|
| 102 |
+
break
|
| 103 |
+
if msg.id > latest_id:
|
| 104 |
+
latest_id = msg.id
|
| 105 |
+
# Force str() to trigger any deferred UTF-16-LE decode NOW,
|
| 106 |
+
# so the error is caught here โ not later in _fingerprint.
|
| 107 |
+
try:
|
| 108 |
+
tmp = msg.text or msg.caption or ""
|
| 109 |
+
except UnicodeDecodeError as e:
|
| 110 |
+
logger.warning(f"BloggerScheduler: msg {msg.id} text decode failed, skipping: {e}")
|
| 111 |
+
continue
|
| 112 |
+
try:
|
| 113 |
+
raw = str(tmp) if tmp else ""
|
| 114 |
+
except (UnicodeDecodeError, UnicodeEncodeError) as e:
|
| 115 |
+
logger.warning(f"BloggerScheduler: msg {msg.id} text conversion failed, skipping: {e}")
|
| 116 |
+
continue
|
| 117 |
+
if not raw.strip():
|
| 118 |
+
logger.info(f"BloggerScheduler: msg {msg.id} has no text, skip")
|
| 119 |
+
continue
|
| 120 |
+
fingerprint = self.processor._fingerprint(raw, str(msg.id))
|
| 121 |
+
if self.db.is_published(fingerprint):
|
| 122 |
+
logger.info(f"BloggerScheduler: msg {msg.id} already published, skip")
|
| 123 |
+
continue
|
| 124 |
+
article = self.db.get_article(fingerprint)
|
| 125 |
+
if article and article.get("status") in ("queued", "published"):
|
| 126 |
+
logger.info(f"BloggerScheduler: msg {msg.id} already queued/published, skip")
|
| 127 |
+
continue
|
| 128 |
+
media = []
|
| 129 |
+
if msg.photo:
|
| 130 |
+
try:
|
| 131 |
+
media.append({"type": "photo", "file_id": msg.photo.file_id})
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.warning(f"BloggerScheduler: msg {msg.id} photo access failed, skipping media: {e}")
|
| 134 |
+
else:
|
| 135 |
+
logger.info(f"BloggerScheduler: msg {msg.id} has photo")
|
| 136 |
+
elif msg.video:
|
| 137 |
+
try:
|
| 138 |
+
media.append({"type": "video", "file_id": msg.video.file_id})
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.warning(f"BloggerScheduler: msg {msg.id} video access failed, skipping media: {e}")
|
| 141 |
+
else:
|
| 142 |
+
logger.info(f"BloggerScheduler: msg {msg.id} has video")
|
| 143 |
+
chat_str = str(ch_id).replace('-100', '') if str(ch_id).lstrip('-').isdigit() else str(ch_id).lstrip('@')
|
| 144 |
+
source_url = f"https://t.me/c/{chat_str}/{msg.id}"
|
| 145 |
+
# Ingestion never calls Gemini directly: save straight to the pending
|
| 146 |
+
# queue so a Gemini cooldown/outage can never cause a message to be lost.
|
| 147 |
+
try:
|
| 148 |
+
fingerprint = self.processor.enqueue_raw_post(raw, source_url, media, channel_id=ch_id, section=ch.get("section", "general"))
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.warning(f"BloggerScheduler: msg {msg.id} enqueue failed, skipping: {e}")
|
| 151 |
+
continue
|
| 152 |
+
if fingerprint:
|
| 153 |
+
any_success = True
|
| 154 |
+
logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} saved to Gemini pending queue")
|
| 155 |
+
else:
|
| 156 |
+
logger.info(f"BloggerScheduler: msg {msg.id} from {ch_id} already known/duplicate, skip")
|
| 157 |
+
# last_message_id only depends on messages being durably captured (saved to
|
| 158 |
+
# pending or already known) โ never on whether Gemini processing succeeded,
|
| 159 |
+
# and it is always reached now even if a message in between failed to decode.
|
| 160 |
+
if latest_id > last_id:
|
| 161 |
+
self.db.save_channel(ch_id, {**ch, "last_message_id": latest_id})
|
| 162 |
+
logger.info(f"BloggerScheduler: updated last_message_id to {latest_id} for {ch_id}")
|
| 163 |
+
except Exception as e:
|
| 164 |
+
logger.warning(f"BloggerScheduler: failed to poll channel {ch_id}: {e}")
|
| 165 |
+
|
| 166 |
+
async def _process_gemini_pending(self):
|
| 167 |
+
"""Process Gemini pending queue (raw posts waiting for AI processing).
|
| 168 |
+
Runs only when Gemini keys are available (cooldown check done by caller).
|
| 169 |
+
Drains in FIFO order โ each success recovers one processed article."""
|
| 170 |
+
pending = self.db.get_gemini_pending_queue()
|
| 171 |
+
if not pending:
|
| 172 |
+
logger.info("BloggerScheduler: Gemini pending queue is empty.")
|
| 173 |
+
return
|
| 174 |
+
logger.info(f"BloggerScheduler: {len(pending)} items in Gemini pending queue, processing...")
|
| 175 |
+
while pending:
|
| 176 |
+
recovered = await self.processor._process_next_pending()
|
| 177 |
+
if not recovered:
|
| 178 |
+
break
|
| 179 |
+
recovered["status"] = "queued"
|
| 180 |
+
ch_id = recovered.get("channel_id", "")
|
| 181 |
+
if ch_id:
|
| 182 |
+
ch = self.db.get_channel(ch_id)
|
| 183 |
+
if ch:
|
| 184 |
+
section_name = ch.get("section", "general")
|
| 185 |
+
recovered["section"] = section_name
|
| 186 |
+
recovered["labels"] = list(self._get_section_labels(section_name))
|
| 187 |
+
logger.info(f"Selected Section: {section_name}")
|
| 188 |
+
logger.info(f"Section Loaded From DB: {section_name}")
|
| 189 |
+
logger.info(f"Labels from section config: {recovered.get('labels', [])}")
|
| 190 |
+
else:
|
| 191 |
+
recovered_section = recovered.get("section", "")
|
| 192 |
+
if recovered_section:
|
| 193 |
+
recovered["labels"] = list(self._get_section_labels(recovered_section))
|
| 194 |
+
logger.info(f"Channel {ch_id} not found, using pending section: {recovered_section}")
|
| 195 |
+
else:
|
| 196 |
+
logger.warning(f"Channel {ch_id} not found in DB, no section fallback")
|
| 197 |
+
else:
|
| 198 |
+
logger.warning(f"No channel_id on recovered article")
|
| 199 |
+
logger.info(f"Section Before Queue: section={recovered.get('section', 'MISSING')}, labels={recovered.get('labels', [])}")
|
| 200 |
+
self._queue.append(recovered)
|
| 201 |
+
self.db.save_article(recovered["fingerprint"], recovered)
|
| 202 |
+
logger.info(f"BloggerScheduler: recovered article '{recovered.get('title', '')[:30]}' from pending queue")
|
| 203 |
+
pending = self.db.get_gemini_pending_queue()
|
| 204 |
+
|
| 205 |
+
async def _process_queue(self):
|
| 206 |
+
now = datetime.now()
|
| 207 |
+
today = now.strftime("%Y-%m-%d")
|
| 208 |
+
current_total_min = now.hour * 60 + now.minute
|
| 209 |
+
|
| 210 |
+
# Build all slots: 09:00, 09:30, 10:00, โฆ 23:00 (29 slots)
|
| 211 |
+
slots = []
|
| 212 |
+
for hour in range(SCHEDULE_START_HOUR, SCHEDULE_END_HOUR):
|
| 213 |
+
for minute in (0, 30):
|
| 214 |
+
slots.append((hour, minute))
|
| 215 |
+
slots.append((SCHEDULE_END_HOUR, 0))
|
| 216 |
+
if not slots:
|
| 217 |
+
return
|
| 218 |
+
|
| 219 |
+
# Load persisted schedule state
|
| 220 |
+
state = self.db.get_schedule_state()
|
| 221 |
+
last_day = state.get("day", "")
|
| 222 |
+
last_slot = state.get("last_slot", -1)
|
| 223 |
+
|
| 224 |
+
# Reset for a new day
|
| 225 |
+
if last_day != today:
|
| 226 |
+
last_slot = -1
|
| 227 |
+
state["day"] = today
|
| 228 |
+
state["last_slot"] = -1
|
| 229 |
+
self.db.save_schedule_state(state)
|
| 230 |
+
logger.info(f"BloggerScheduler: new day {today}, reset schedule")
|
| 231 |
+
|
| 232 |
+
queue = [a for a in self._queue if a.get("status") == "queued"]
|
| 233 |
+
if not queue:
|
| 234 |
+
return
|
| 235 |
+
|
| 236 |
+
next_slot_idx = last_slot + 1
|
| 237 |
+
if next_slot_idx >= len(slots):
|
| 238 |
+
logger.info(f"BloggerScheduler: all {len(slots)} slots used today, carry over to tomorrow")
|
| 239 |
+
return
|
| 240 |
+
|
| 241 |
+
next_hour, next_min = slots[next_slot_idx]
|
| 242 |
+
next_total_min = next_hour * 60 + next_min
|
| 243 |
+
|
| 244 |
+
# Not time yet
|
| 245 |
+
if current_total_min < next_total_min:
|
| 246 |
+
logger.info(f"BloggerScheduler: next slot {next_hour:02d}:{next_min:02d}, current {now.hour:02d}:{now.minute:02d}, waiting")
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
# Past the slot window โ skip it to prevent catch-up burst publishing
|
| 250 |
+
slot_window_end = next_total_min + SCHEDULE_INTERVAL_MIN
|
| 251 |
+
if current_total_min >= slot_window_end:
|
| 252 |
+
logger.info(f"BloggerScheduler: slot {next_slot_idx} ({next_hour:02d}:{next_min:02d}) window already passed, skipping")
|
| 253 |
+
state["last_slot"] = next_slot_idx
|
| 254 |
+
self.db.save_schedule_state(state)
|
| 255 |
+
return
|
| 256 |
+
|
| 257 |
+
# Time to publish ONE article
|
| 258 |
+
channels = {c.get("channel_id"): c for c in self.db.get_all_channels()}
|
| 259 |
+
today_published = self._today_published_count()
|
| 260 |
+
article = queue[0]
|
| 261 |
+
|
| 262 |
+
ch_id = article.get("channel_id", "")
|
| 263 |
+
ch_config = channels.get(ch_id, {})
|
| 264 |
+
logger.info(f"Selected Article ID: {article.get('fingerprint', 'N/A')[:16]}")
|
| 265 |
+
logger.info(f"Selected Section: {article.get('section', 'MISSING')}")
|
| 266 |
+
logger.info(f"Selected Labels: {article.get('labels', 'MISSING')}")
|
| 267 |
+
logger.info(f"Selected Hashtags: {article.get('hashtags', 'MISSING')}")
|
| 268 |
+
logger.info(f"Article keys: {list(article.keys())}")
|
| 269 |
+
|
| 270 |
+
# Resolve section on the article itself so it propagates to publisher, labels, daily count
|
| 271 |
+
if not article.get("section"):
|
| 272 |
+
article["section"] = ch_config.get("section", "general")
|
| 273 |
+
logger.info(f"Section was MISSING, resolved from channel to: {article['section']}")
|
| 274 |
+
|
| 275 |
+
section = article["section"]
|
| 276 |
+
section_today = today_published.get(section, 0)
|
| 277 |
+
daily_limit = ch_config.get("daily_limit", 10)
|
| 278 |
+
logger.info(f"Incoming Section: {section}")
|
| 279 |
+
logger.info(f"Daily Limit Section: {section}")
|
| 280 |
+
logger.info(f"Daily Count: {section_today}")
|
| 281 |
+
logger.info(f"Daily Limit: {daily_limit}")
|
| 282 |
+
decision = "SKIP - limit reached" if section_today >= daily_limit else "PUBLISH"
|
| 283 |
+
logger.info(f"Decision: {decision}")
|
| 284 |
+
logger.info("Before Daily Limit")
|
| 285 |
+
if section_today >= daily_limit:
|
| 286 |
+
logger.info(f"BloggerScheduler: daily limit {daily_limit} for section {section} reached, skipping article and scheduling next slot")
|
| 287 |
+
state["last_slot"] = next_slot_idx
|
| 288 |
+
self.db.save_schedule_state(state)
|
| 289 |
+
return
|
| 290 |
+
logger.info("After Daily Limit")
|
| 291 |
+
|
| 292 |
+
logger.info("Before Publish")
|
| 293 |
+
logger.info(f"BloggerScheduler: publishing article '{article.get('title', '')[:30]}' in slot {next_hour:02d}:{next_min:02d}")
|
| 294 |
+
logger.info(f"Section Before Publisher: section={section}")
|
| 295 |
+
logger.info(f"Article dict has labels: {article.get('labels', [])}")
|
| 296 |
+
logger.info(f"Article dict has hashtags: {article.get('hashtags', 'MISSING')}")
|
| 297 |
+
html = self.processor.make_article_html(article)
|
| 298 |
+
labels = list(self._get_section_labels(section))
|
| 299 |
+
logger.info(f"Labels Sent To Blogger: {labels}")
|
| 300 |
+
blogger_article = {
|
| 301 |
+
"title": article.get("title", "ุนููุงู ุงูู
ูุงู"),
|
| 302 |
+
"content": html,
|
| 303 |
+
"labels": labels,
|
| 304 |
+
}
|
| 305 |
+
post_id = await self.publisher.publish_article(blogger_article, article.get("fingerprint"))
|
| 306 |
+
logger.info("After Publish")
|
| 307 |
+
if post_id:
|
| 308 |
+
self.db.update_article_status(article["fingerprint"], "published", {
|
| 309 |
+
"post_id": post_id,
|
| 310 |
+
"published_at": int(time.time()),
|
| 311 |
+
})
|
| 312 |
+
self.db.increment_daily_count(section)
|
| 313 |
+
logger.info(f"BloggerScheduler: published '{article.get('title', '')[:30]}' (post_id={post_id})")
|
| 314 |
+
else:
|
| 315 |
+
self.db.update_article_status(article["fingerprint"], "failed", {
|
| 316 |
+
"failed_at": int(time.time()),
|
| 317 |
+
})
|
| 318 |
+
logger.warning(f"BloggerScheduler: failed to publish '{article.get('title', '')[:30]}'")
|
| 319 |
+
|
| 320 |
+
article["status"] = "published" if post_id else "failed"
|
| 321 |
+
logger.info("Before Queue Pop")
|
| 322 |
+
self._queue = [a for a in self._queue if a.get("fingerprint") != article["fingerprint"]]
|
| 323 |
+
logger.info("After Queue Pop")
|
| 324 |
+
|
| 325 |
+
# Mark this slot as used
|
| 326 |
+
state["last_slot"] = next_slot_idx
|
| 327 |
+
self.db.save_schedule_state(state)
|
| 328 |
+
logger.info(f"BloggerScheduler: slot {next_slot_idx} used, next at slot {next_slot_idx + 1}")
|
| 329 |
+
|
| 330 |
+
def _can_publish_now(self, ch_config: Dict, current_hour: int, today_published: Dict) -> bool:
|
| 331 |
+
if not ch_config.get("enabled", True):
|
| 332 |
+
logger.info(f"BloggerScheduler: channel disabled")
|
| 333 |
+
return False
|
| 334 |
+
start_hour = ch_config.get("start_hour", 9)
|
| 335 |
+
end_hour = ch_config.get("end_hour", 23)
|
| 336 |
+
if current_hour < start_hour or current_hour >= end_hour:
|
| 337 |
+
logger.info(f"BloggerScheduler: current hour {current_hour} outside window {start_hour}-{end_hour}")
|
| 338 |
+
return False
|
| 339 |
+
daily_limit = ch_config.get("daily_limit", 10)
|
| 340 |
+
section = ch_config.get("section", "general")
|
| 341 |
+
section_count = today_published.get(section, 0)
|
| 342 |
+
if section_count >= daily_limit:
|
| 343 |
+
logger.info(f"BloggerScheduler: daily limit {daily_limit} reached for section {section}")
|
| 344 |
+
return False
|
| 345 |
+
return True
|
| 346 |
+
|
| 347 |
+
def _today_published_count(self) -> Dict:
|
| 348 |
+
today = time.strftime("%Y-%m-%d")
|
| 349 |
+
stats = self.db.get_stats()
|
| 350 |
+
daily = stats.get("daily", {})
|
| 351 |
+
return daily.get(today, {})
|
| 352 |
+
|
| 353 |
+
def _get_section_labels(self, section_name: str) -> list:
|
| 354 |
+
sections = self.db.get_all_sections()
|
| 355 |
+
for sdata in sections.values():
|
| 356 |
+
if sdata.get("name") == section_name:
|
| 357 |
+
labels = sdata.get("labels", [])
|
| 358 |
+
if labels:
|
| 359 |
+
return list(labels)
|
| 360 |
+
return [section_name]
|
| 361 |
+
if section_name and section_name != "general":
|
| 362 |
+
return [section_name]
|
| 363 |
+
return []
|
| 364 |
+
|
| 365 |
+
def add_to_queue(self, article: Dict):
|
| 366 |
+
article["status"] = "queued"
|
| 367 |
+
self._queue.append(article)
|
| 368 |
+
self.db.save_article(article["fingerprint"], article)
|
| 369 |
+
logger.info(f"BloggerScheduler: manually queued article '{article.get('title', '')[:30]}'")
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from pyrogram import Client, filters
|
| 5 |
+
from pyrogram.handlers import MessageHandler
|
| 6 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 7 |
+
|
| 8 |
+
from modules.blogger.publisher import BloggerPublisher
|
| 9 |
+
from modules.blogger.scheduler import SLOTS_PER_DAY
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
_publisher = None
|
| 14 |
+
|
| 15 |
+
# Navigation stack per user
|
| 16 |
+
def get_publisher():
|
| 17 |
+
global _publisher
|
| 18 |
+
if _publisher is None:
|
| 19 |
+
_publisher = BloggerPublisher()
|
| 20 |
+
return _publisher
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _grid_buttons(buttons, max_cols=2):
|
| 24 |
+
rows = []
|
| 25 |
+
pending = []
|
| 26 |
+
for item in buttons:
|
| 27 |
+
if isinstance(item, list):
|
| 28 |
+
if pending:
|
| 29 |
+
rows.append(pending)
|
| 30 |
+
pending = []
|
| 31 |
+
rows.append(item)
|
| 32 |
+
else:
|
| 33 |
+
pending.append(item)
|
| 34 |
+
if len(pending) >= max_cols:
|
| 35 |
+
rows.append(pending)
|
| 36 |
+
pending = []
|
| 37 |
+
if pending:
|
| 38 |
+
rows.append(pending)
|
| 39 |
+
return rows
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def safe_edit(callback, text, reply_markup=None):
|
| 43 |
+
try:
|
| 44 |
+
await callback.edit_message_text(text, reply_markup=reply_markup)
|
| 45 |
+
except Exception:
|
| 46 |
+
try:
|
| 47 |
+
await callback.answer()
|
| 48 |
+
except Exception:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _nav_row(uid: int, back_callback: str = None):
|
| 53 |
+
"""ุตู ุฃุฒุฑุงุฑ ููุงุณู: ุงููุงุฆู
ุฉ ุงูุฑุฆูุณูุฉ (ููู
ูููู ุงูุนุงู
) + ุฑุฌูุน."""
|
| 54 |
+
back_target = back_callback or _get_back_target(uid, "blogger_menu")
|
| 55 |
+
return [
|
| 56 |
+
InlineKeyboardButton("๐ ุงููุงุฆู
ุฉ ุงูุฑุฆูุณูุฉ", callback_data="main_menu"),
|
| 57 |
+
InlineKeyboardButton("๐ ุฑุฌูุน", callback_data=back_target),
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Navigation stack for proper back-button behavior
|
| 62 |
+
_nav_stack: dict[int, list[str]] = {}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _push_nav(uid: int, callback_data: str):
|
| 66 |
+
stack = _nav_stack.get(uid, [])
|
| 67 |
+
# Back navigation: pop current page, don't push target back
|
| 68 |
+
if len(stack) >= 2 and callback_data == stack[-2]:
|
| 69 |
+
stack.pop()
|
| 70 |
+
_nav_stack[uid] = stack
|
| 71 |
+
return
|
| 72 |
+
# Avoid duplicate consecutive entries
|
| 73 |
+
if stack and stack[-1] == callback_data:
|
| 74 |
+
return
|
| 75 |
+
stack.append(callback_data)
|
| 76 |
+
_nav_stack[uid] = stack
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _get_back_target(uid: int, default: str = "blogger_menu") -> str:
|
| 80 |
+
stack = _nav_stack.get(uid, [])
|
| 81 |
+
if len(stack) >= 2:
|
| 82 |
+
return stack[-2]
|
| 83 |
+
if len(stack) == 1:
|
| 84 |
+
return "main_menu"
|
| 85 |
+
return default
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _clear_nav(uid: int):
|
| 89 |
+
_nav_stack.pop(uid, None)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
async def blogger_main_menu(client, callback):
|
| 93 |
+
uid = callback.from_user.id
|
| 94 |
+
_push_nav(uid, "blogger_menu")
|
| 95 |
+
pub = get_publisher()
|
| 96 |
+
cfg = pub.config.get_all()
|
| 97 |
+
enabled = "โ
ู
ูุนู" if pub.config.is_enabled() else "โ ู
ุชููู"
|
| 98 |
+
configured = "โ
ุชู
" if pub.client.is_configured() else "โ ุบูุฑ ู
ูุชู
ู"
|
| 99 |
+
blog_id = cfg.get("blog_id", "") or "ุบูุฑ ู
ุญุฏุฏ"
|
| 100 |
+
queue_count = len([a for a in pub.db.get_articles_by_status("queued")])
|
| 101 |
+
text = (
|
| 102 |
+
f"๐ **Blogger Publisher**\n\n"
|
| 103 |
+
f"ุงูุญุงูุฉ: {enabled}\n"
|
| 104 |
+
f"ุงูุฅุนุฏุงุฏุงุช: {configured}\n"
|
| 105 |
+
f"Blog ID: `{blog_id}`\n"
|
| 106 |
+
f"๐ฅ ุงูู
ูุงูุงุช ูู Queue: {queue_count}\n\n"
|
| 107 |
+
f"ุงุฎุชุฑ ู
ู ุงููุงุฆู
ุฉ:"
|
| 108 |
+
)
|
| 109 |
+
buttons = [
|
| 110 |
+
InlineKeyboardButton("๐ ุงูู
ูุงูุงุช", callback_data="blogger_articles"),
|
| 111 |
+
InlineKeyboardButton("๐ ุฅุนุฏุงุฏุงุช ุงููุดุฑ", callback_data="blogger_settings"),
|
| 112 |
+
InlineKeyboardButton("๐ ุฅุฏุงุฑุฉ ุงูุฃูุณุงู
", callback_data="blogger_sections_main"),
|
| 113 |
+
InlineKeyboardButton("๐บ ุฅุฏุงุฑุฉ ุงููููุงุช", callback_data="blogger_channels"),
|
| 114 |
+
InlineKeyboardButton("๐ ุฌุฏููุฉ ุงููุดุฑ", callback_data="blogger_schedule_info"),
|
| 115 |
+
InlineKeyboardButton("๐ ู
ุนุงููุฉ ุขุฎุฑ ู
ูุงู", callback_data="blogger_preview_last"),
|
| 116 |
+
InlineKeyboardButton("๐ผ ุฅุนุฏุงุฏุงุช ุงูุตูุฑุฉ", callback_data="blogger_set_default_image"),
|
| 117 |
+
InlineKeyboardButton("๐ ุงูุฅุญุตุงุฆูุงุช", callback_data="blogger_stats"),
|
| 118 |
+
InlineKeyboardButton("โ๏ธ ุงูุฅุนุฏุงุฏุงุช ุงูู
ุชูุฏู
ุฉ", callback_data="blogger_advanced"),
|
| 119 |
+
]
|
| 120 |
+
rows = _grid_buttons(buttons, 2)
|
| 121 |
+
rows.append(_nav_row(uid, "main_menu"))
|
| 122 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
async def blogger_settings_menu(client, callback):
|
| 126 |
+
uid = callback.from_user.id
|
| 127 |
+
_push_nav(uid, "blogger_settings")
|
| 128 |
+
pub = get_publisher()
|
| 129 |
+
cfg = pub.config.get_all()
|
| 130 |
+
env_keys = pub.config.env_keys()
|
| 131 |
+
def val(key, env_label, display=None):
|
| 132 |
+
if key in env_keys:
|
| 133 |
+
return f"๐ {env_label} (ู
ู ุงูุจูุฆุฉ)"
|
| 134 |
+
v = cfg.get(key, "")
|
| 135 |
+
if display:
|
| 136 |
+
return display(v)
|
| 137 |
+
return f"`{v}`" if v else "โ ูุงุฑุบ"
|
| 138 |
+
text = (
|
| 139 |
+
f"โ๏ธ **ุฅุนุฏุงุฏุงุช Blogger**\n\n"
|
| 140 |
+
f"Blog ID: {val('blog_id', 'ู
ุญููุธ', lambda v: f'`{v}`')}\n"
|
| 141 |
+
f"Client ID: {val('client_id', 'ู
ุญููุธ', lambda v: f'`{v[:15]}...`') if 'client_id' not in env_keys else '๐ ู
ุญููุธ (ู
ู ุงูุจูุฆุฉ)'}\n"
|
| 142 |
+
f"Client Secret: {val('client_secret', 'ู
ุญููุธ', lambda v: 'โ
ู
ุญููุธ')}\n"
|
| 143 |
+
f"Refresh Token: {val('refresh_token', 'ู
ุญููุธ', lambda v: 'โ
ู
ุญููุธ')}\n"
|
| 144 |
+
f"ุงููุดุฑ ูู
ุณูุฏุฉ: {'โ
' if cfg.get('publish_as_draft') else 'โ'}\n"
|
| 145 |
+
f"ุตูุฑุฉ ุงููุธุงุฆู ุงูุงูุชุฑุงุถูุฉ: {'โ
ู
ุญุฏุฏุฉ' if cfg.get('default_jobs_image') else 'โ ุบูุฑ ู
ุญุฏุฏุฉ'}\n\n"
|
| 146 |
+
)
|
| 147 |
+
if env_keys:
|
| 148 |
+
text += "๐ ุงูููู
ู
ู ุงูุจูุฆุฉ ูุง ูู
ูู ุชุนุฏูููุง ู
ู ููุง.\n"
|
| 149 |
+
else:
|
| 150 |
+
text += "ูุชุนููู ุฃู ุชุบููุฑ ุฃู ููู
ุฉุ ุงุถุบุท ุนูู ุงูุฒุฑ ุงูู
ูุงุณุจ."
|
| 151 |
+
buttons = []
|
| 152 |
+
if "blog_id" not in env_keys:
|
| 153 |
+
buttons.append(InlineKeyboardButton("๐ Blog ID", callback_data="blogger_set_blog_id"))
|
| 154 |
+
if "client_id" not in env_keys:
|
| 155 |
+
buttons.append(InlineKeyboardButton("๐ Client ID", callback_data="blogger_set_client_id"))
|
| 156 |
+
if "client_secret" not in env_keys:
|
| 157 |
+
buttons.append(InlineKeyboardButton("๐ Client Secret", callback_data="blogger_set_client_secret"))
|
| 158 |
+
if "refresh_token" not in env_keys:
|
| 159 |
+
buttons.append(InlineKeyboardButton("๐ Refresh Token", callback_data="blogger_set_refresh_token"))
|
| 160 |
+
if "publish_as_draft" not in env_keys:
|
| 161 |
+
buttons.append(InlineKeyboardButton(f"{'โ
' if cfg.get('publish_as_draft') else 'โ'} ู
ุณูุฏุฉ", callback_data="blogger_toggle_draft"))
|
| 162 |
+
if "default_jobs_image" not in env_keys:
|
| 163 |
+
buttons.append(InlineKeyboardButton("๐ผ ุตูุฑุฉ ุงูุชุฑุงุถูุฉ ูููุธุงุฆู", callback_data="blogger_set_default_image"))
|
| 164 |
+
buttons.append(InlineKeyboardButton("๐งช ุงุฎุชุจุงุฑ", callback_data="blogger_test"))
|
| 165 |
+
if not buttons:
|
| 166 |
+
buttons.append(InlineKeyboardButton("๐งช ุงุฎุชุจุงุฑ", callback_data="blogger_test"))
|
| 167 |
+
rows = _grid_buttons(buttons, 2)
|
| 168 |
+
rows.append(_nav_row(uid))
|
| 169 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
async def blogger_channels_menu(client, callback):
|
| 173 |
+
uid = callback.from_user.id
|
| 174 |
+
_push_nav(uid, "blogger_channels")
|
| 175 |
+
pub = get_publisher()
|
| 176 |
+
channels = pub.db.get_all_channels()
|
| 177 |
+
text = f"๐ข **ูููุงุช Blogger**\n\nุนุฏุฏ ุงููููุงุช: {len(channels)}\n\n"
|
| 178 |
+
if channels:
|
| 179 |
+
for ch in channels:
|
| 180 |
+
section = ch.get("section", "ุบูุฑ ู
ุญุฏุฏ")
|
| 181 |
+
daily = ch.get("daily_limit", 0)
|
| 182 |
+
enabled = "โ
" if ch.get("enabled", True) else "โ"
|
| 183 |
+
start_h = ch.get("start_hour", 9)
|
| 184 |
+
end_h = ch.get("end_hour", 23)
|
| 185 |
+
text += f"{enabled} {ch.get('name', ch.get('channel_id', '?'))}\n"
|
| 186 |
+
text += f" ๐ {section} | ๐ {daily}/ููู
| ๐ {start_h}:00-{end_h}:00\n"
|
| 187 |
+
else:
|
| 188 |
+
text += "ูุง ุชูุฌุฏ ูููุงุช ุจุนุฏ.\nุฃุถู ููุงุฉ ุชูููุฌุฑุงู
ูู
ุตุฏุฑ ูููุดุฑ."
|
| 189 |
+
buttons = [
|
| 190 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ููุงุฉ", callback_data="blogger_add_channel"),
|
| 191 |
+
]
|
| 192 |
+
if channels:
|
| 193 |
+
buttons.append(InlineKeyboardButton("๐ ุญุฐู ููุงุฉ", callback_data="blogger_del_channel"))
|
| 194 |
+
for ch in channels:
|
| 195 |
+
ch_id = ch.get("channel_id", "")
|
| 196 |
+
name = ch.get("name", ch_id)
|
| 197 |
+
buttons.append(InlineKeyboardButton(f"โ๏ธ {name[:22]}", callback_data=f"blogger_edit_ch_{ch_id}"))
|
| 198 |
+
buttons.append(InlineKeyboardButton("๐ ุฅุฏุงุฑุฉ ุงูุฃูุณุงู
", callback_data="blogger_sections"))
|
| 199 |
+
rows = _grid_buttons(buttons, 2)
|
| 200 |
+
rows.append(_nav_row(uid))
|
| 201 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
async def blogger_add_channel_prompt(client, callback):
|
| 205 |
+
from bot_core import user_states
|
| 206 |
+
uid = callback.from_user.id
|
| 207 |
+
user_states.pop(uid, None)
|
| 208 |
+
user_states[uid] = {"state": "blogger_add_channel_id"}
|
| 209 |
+
await safe_edit(callback, "ุฃุฑุณู ู
ุนุฑู ุงูููุงุฉ (ID) ุฃู ุงูููุฒุฑ (@username):\n\nู
ุซุงู: @my_channel ุฃู -1001234567890", InlineKeyboardMarkup([_nav_row(uid, "blogger_channels")]))
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
async def blogger_add_channel_section_prompt(client, message, ch_id, ch_name):
|
| 213 |
+
from bot_core import user_states
|
| 214 |
+
uid = message.from_user.id
|
| 215 |
+
user_states.pop(uid, None)
|
| 216 |
+
user_states[uid] = {"state": "blogger_add_ch_section", "ch_id": ch_id, "ch_name": ch_name}
|
| 217 |
+
await message.reply("ุฃุฑุณู ุงุณู
ุงููุณู
ูู ุงูู
ุฏููุฉ:\nู
ุซุงู: ูุธุงุฆู, ุฃุฎุจุงุฑ, ู
ูุงูุตุงุช")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
async def blogger_add_channel_limit_prompt(client, message, ch_id, section):
|
| 221 |
+
from bot_core import user_states
|
| 222 |
+
uid = message.from_user.id
|
| 223 |
+
user_states.pop(uid, None)
|
| 224 |
+
user_states[uid] = {"state": "blogger_add_ch_limit", "ch_id": ch_id, "section": section}
|
| 225 |
+
await message.reply("ุฃุฑุณู ุงูุญุฏ ุงูููู
ู ูุนุฏุฏ ุงูู
ูุดูุฑุงุช:\nู
ุซุงู: 30")
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
async def blogger_del_channel_menu(client, callback):
|
| 229 |
+
pub = get_publisher()
|
| 230 |
+
channels = pub.db.get_all_channels()
|
| 231 |
+
if not channels:
|
| 232 |
+
await callback.answer("ูุง ุชูุฌุฏ ูููุงุช.", show_alert=True)
|
| 233 |
+
return
|
| 234 |
+
text = "๐ **ุญุฐู ููุงุฉ Blogger**\n\nุงุฎุชุฑ ุงูููุงุฉ ููุญุฐู:"
|
| 235 |
+
buttons = []
|
| 236 |
+
for ch in channels:
|
| 237 |
+
name = ch.get("name", ch.get("channel_id", "?"))
|
| 238 |
+
ch_id = ch.get("channel_id", "")
|
| 239 |
+
buttons.append([InlineKeyboardButton(f"๐ {name}", callback_data=f"blogger_del_ch_{ch_id}")])
|
| 240 |
+
uid = callback.from_user.id
|
| 241 |
+
buttons.append(_nav_row(uid, "blogger_channels"))
|
| 242 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
async def blogger_confirm_del_channel(client, callback):
|
| 246 |
+
ch_id = callback.data.split("_")[-1]
|
| 247 |
+
pub = get_publisher()
|
| 248 |
+
pub.db.delete_channel(ch_id)
|
| 249 |
+
await callback.answer("โ
ุชู
ุญุฐู ุงูููุงุฉ.")
|
| 250 |
+
await blogger_channels_menu(client, callback)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
async def blogger_edit_channel_menu(client, callback):
|
| 254 |
+
uid = callback.from_user.id
|
| 255 |
+
ch_id = callback.data.split("_")[-1]
|
| 256 |
+
pub = get_publisher()
|
| 257 |
+
ch = pub.db.get_channel(ch_id)
|
| 258 |
+
if not ch:
|
| 259 |
+
await callback.answer("ุบูุฑ ู
ูุฌูุฏุฉ.")
|
| 260 |
+
return
|
| 261 |
+
_push_nav(uid, f"blogger_edit_ch_{ch_id}")
|
| 262 |
+
enabled = "โ
" if ch.get("enabled", True) else "โ"
|
| 263 |
+
sections = pub.db.get_all_sections()
|
| 264 |
+
current_section = ch.get("section", "ุบูุฑ ู
ุญุฏุฏ")
|
| 265 |
+
text = (
|
| 266 |
+
f"โ๏ธ **ุฅุนุฏุงุฏุงุช ููุงุฉ Blogger**\n\n"
|
| 267 |
+
f"ุงูุงุณู
: {ch.get('name', ch_id)}\n"
|
| 268 |
+
f"ID: `{ch_id}`\n"
|
| 269 |
+
f"ุงูุญุงูุฉ: {enabled}\n"
|
| 270 |
+
f"ุงููุณู
ุงูุญุงูู: **{current_section}** ๐ ุชุบููุฑ ุงููุณู
\n"
|
| 271 |
+
f"ุงูุญุฏ ุงูููู
ู: {ch.get('daily_limit', 10)}\n"
|
| 272 |
+
f"ุณุงุนุงุช ุงููุดุฑ: {ch.get('start_hour', 9)}:00 - {ch.get('end_hour', 23)}:00\n"
|
| 273 |
+
)
|
| 274 |
+
buttons = [
|
| 275 |
+
InlineKeyboardButton(f"{'โ
' if ch.get('enabled', True) else 'โ'} ุชูุนูู/ุชุนุทูู", callback_data=f"blogger_toggle_ch_{ch_id}"),
|
| 276 |
+
InlineKeyboardButton(f"๐ ุชุบููุฑ ุงููุณู
", callback_data=f"blogger_ch_section_{ch_id}"),
|
| 277 |
+
InlineKeyboardButton(f"๐ ุชุบููุฑ ุงูุญุฏ ุงูููู
ู", callback_data=f"blogger_ch_limit_{ch_id}"),
|
| 278 |
+
InlineKeyboardButton(f"๐ ุชุบููุฑ ุณุงุนุงุช ุงููุดุฑ", callback_data=f"blogger_ch_hours_{ch_id}"),
|
| 279 |
+
InlineKeyboardButton(f"๐ ู
ุนุงููุฉ ู
ูุดูุฑ", callback_data=f"blogger_preview_ch_{ch_id}"),
|
| 280 |
+
InlineKeyboardButton(f"๐ ู
ุนุงูุฌุฉ ููุฑูุฉ", callback_data=f"blogger_process_{ch_id}"),
|
| 281 |
+
]
|
| 282 |
+
rows = _grid_buttons(buttons, 2)
|
| 283 |
+
rows.append(_nav_row(uid, "blogger_channels"))
|
| 284 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
async def blogger_toggle_channel_handler(client, callback):
|
| 288 |
+
uid = callback.from_user.id
|
| 289 |
+
ch_id = callback.data.split("_")[-1]
|
| 290 |
+
pub = get_publisher()
|
| 291 |
+
ch = pub.db.get_channel(ch_id)
|
| 292 |
+
if ch:
|
| 293 |
+
new_state = not ch.get("enabled", True)
|
| 294 |
+
ch["enabled"] = new_state
|
| 295 |
+
pub.db.save_channel(ch_id, ch)
|
| 296 |
+
await callback.answer("โ
ุชู
ุงูุชุจุฏูู.")
|
| 297 |
+
callback.data = f"blogger_edit_ch_{ch_id}"
|
| 298 |
+
await blogger_edit_channel_menu(client, callback)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
async def blogger_manual_process(client, callback):
|
| 302 |
+
ch_id = callback.data.split("_")[-1]
|
| 303 |
+
pub = get_publisher()
|
| 304 |
+
ch = pub.db.get_channel(ch_id)
|
| 305 |
+
if not ch:
|
| 306 |
+
await callback.answer("ุบูุฑ ู
ูุฌูุฏุฉ.")
|
| 307 |
+
return
|
| 308 |
+
await callback.answer("ุฌุงุฑู ุงูู
ุนุงูุฌุฉ...")
|
| 309 |
+
try:
|
| 310 |
+
before = len(pub.db.get_all_channels())
|
| 311 |
+
await pub.scheduler._fetch_new_posts([ch])
|
| 312 |
+
await callback.answer("โ
ุชู
ุช ู
ุนุงูุฌุฉ ุงูู
ูุดูุฑุงุช ูุฌุฏููุชูุง.", show_alert=True)
|
| 313 |
+
except Exception as e:
|
| 314 |
+
logger.exception(f"Blogger manual process error: {e}")
|
| 315 |
+
await callback.answer(f"โ ูุดู: {str(e)[:50]}", show_alert=True)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
async def blogger_preview_channel(client, callback):
|
| 319 |
+
ch_id = callback.data.split("_")[-1]
|
| 320 |
+
pub = get_publisher()
|
| 321 |
+
ch = pub.db.get_channel(ch_id)
|
| 322 |
+
if not ch:
|
| 323 |
+
await callback.answer("ุบูุฑ ู
ูุฌูุฏุฉ.")
|
| 324 |
+
return
|
| 325 |
+
await callback.answer("ุฌุงุฑู ุชุฌููุฒ ุงูู
ุนุงููุฉ...")
|
| 326 |
+
from bot_core import user_client
|
| 327 |
+
if not user_client:
|
| 328 |
+
await callback.answer("โ ุงูุจูุช ุงูุดุฎุตู ุบูุฑ ู
ุชุตู.", show_alert=True)
|
| 329 |
+
return
|
| 330 |
+
try:
|
| 331 |
+
chat_identifier = int(ch_id) if str(ch_id).lstrip('-').isdigit() else ch_id
|
| 332 |
+
msg = None
|
| 333 |
+
async for m in user_client.get_chat_history(chat_identifier, limit=1):
|
| 334 |
+
msg = m
|
| 335 |
+
break
|
| 336 |
+
if not msg:
|
| 337 |
+
await callback.answer("ูุง ุชูุฌุฏ ุฑุณุงุฆู ูู ุงูููุงุฉ.", show_alert=True)
|
| 338 |
+
return
|
| 339 |
+
try:
|
| 340 |
+
tmp = msg.text or msg.caption or ""
|
| 341 |
+
except UnicodeDecodeError:
|
| 342 |
+
await callback.answer("โ ุชุนุฐุฑ ูุฑุงุกุฉ ุงูุฑุณุงูุฉ (ุชุฑู
ูุฒ ุชุงูู).", show_alert=True)
|
| 343 |
+
return
|
| 344 |
+
try:
|
| 345 |
+
raw = str(tmp) if tmp else ""
|
| 346 |
+
except (UnicodeDecodeError, UnicodeEncodeError):
|
| 347 |
+
await callback.answer("โ ุชุนุฐุฑ ูุฑุงุกุฉ ุงูุฑุณุงูุฉ (ุชุฑู
ูุฒ ุชุงูู).", show_alert=True)
|
| 348 |
+
return
|
| 349 |
+
if not raw.strip():
|
| 350 |
+
await callback.answer("ุงูุฑุณุงูุฉ ุงูุฃุฎูุฑุฉ ูุงุฑุบุฉ.", show_alert=True)
|
| 351 |
+
return
|
| 352 |
+
fingerprint = pub.processor._fingerprint(raw, str(msg.id))
|
| 353 |
+
article = pub.db.get_article(fingerprint)
|
| 354 |
+
if not article:
|
| 355 |
+
article_data = await pub.processor.process_raw_post(raw, f"preview_{ch_id}_{msg.id}", channel_id=ch_id)
|
| 356 |
+
if not article_data:
|
| 357 |
+
await callback.answer("โ ูุดูุช ุงูู
ุนุงูุฌุฉ.", show_alert=True)
|
| 358 |
+
return
|
| 359 |
+
article_data["channel_id"] = ch_id
|
| 360 |
+
section_name = ch.get("section", "general")
|
| 361 |
+
article_data["section"] = section_name
|
| 362 |
+
article_data["labels"] = list(pub.scheduler._get_section_labels(section_name))
|
| 363 |
+
pub.db.save_article(fingerprint, article_data)
|
| 364 |
+
article = article_data
|
| 365 |
+
image_source, telegram_text = pub.processor.make_preview_data(article)
|
| 366 |
+
if len(telegram_text) > 4096:
|
| 367 |
+
telegram_text = telegram_text[:4093] + "..."
|
| 368 |
+
buttons = [
|
| 369 |
+
InlineKeyboardButton("๐ค ูุดุฑ ุงูุขู", callback_data=f"blogger_publish_now_{fingerprint}"),
|
| 370 |
+
InlineKeyboardButton("๐พ ูู
ุณูุฏุฉ", callback_data=f"blogger_publish_draft_{fingerprint}"),
|
| 371 |
+
InlineKeyboardButton("๐ ุญุฐู", callback_data=f"blogger_discard_{fingerprint}"),
|
| 372 |
+
]
|
| 373 |
+
rows = _grid_buttons(buttons, 2)
|
| 374 |
+
rows.append(_nav_row(callback.from_user.id, f"blogger_edit_ch_{ch_id}"))
|
| 375 |
+
markup = InlineKeyboardMarkup(rows)
|
| 376 |
+
had_image = bool(image_source)
|
| 377 |
+
if had_image:
|
| 378 |
+
try:
|
| 379 |
+
await client.send_photo(
|
| 380 |
+
callback.from_user.id,
|
| 381 |
+
photo=image_source,
|
| 382 |
+
caption="๐ **ู
ุนุงููุฉ ุงูู
ูุดูุฑ**",
|
| 383 |
+
)
|
| 384 |
+
except Exception as e:
|
| 385 |
+
logger.warning(f"Failed to send preview photo: {e}")
|
| 386 |
+
telegram_text = f"โ ๏ธ ุงูุตูุฑุฉ ุบูุฑ ู
ุชููุฑุฉ\n\n{telegram_text}"
|
| 387 |
+
sent = await client.send_message(
|
| 388 |
+
callback.from_user.id,
|
| 389 |
+
telegram_text,
|
| 390 |
+
reply_markup=markup,
|
| 391 |
+
)
|
| 392 |
+
try:
|
| 393 |
+
await callback.message.delete()
|
| 394 |
+
except Exception:
|
| 395 |
+
pass
|
| 396 |
+
await callback.answer("โ
ุชู
ุฅุฑุณุงู ุงูู
ุนุงููุฉ", show_alert=True)
|
| 397 |
+
except Exception as e:
|
| 398 |
+
logger.exception(f"Blogger preview error: {e}")
|
| 399 |
+
await callback.answer(f"โ ุฎุทุฃ: {str(e)[:50]}", show_alert=True)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
async def blogger_publish_article_now(client, callback):
|
| 403 |
+
import re
|
| 404 |
+
fingerprint = callback.data[len("blogger_publish_now_"):]
|
| 405 |
+
pub = get_publisher()
|
| 406 |
+
article = pub.db.get_article(fingerprint)
|
| 407 |
+
if not article:
|
| 408 |
+
await callback.answer("ุงูู
ูุดูุฑ ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 409 |
+
return
|
| 410 |
+
html = pub.processor.make_article_html(article)
|
| 411 |
+
section = article.get("section", "")
|
| 412 |
+
labels = list(pub.scheduler._get_section_labels(section))
|
| 413 |
+
blogger_article = {
|
| 414 |
+
"title": article.get("title", "ุนููุงู ุงูู
ูุงู"),
|
| 415 |
+
"content": html,
|
| 416 |
+
"labels": labels,
|
| 417 |
+
}
|
| 418 |
+
await callback.answer("ุฌุงุฑู ุงููุดุฑ...")
|
| 419 |
+
post_id = await pub.publish_article(blogger_article, fingerprint)
|
| 420 |
+
if post_id:
|
| 421 |
+
pub.db.update_article_status(fingerprint, "published", {"post_id": post_id, "published_at": int(time.time())})
|
| 422 |
+
await callback.answer("โ
ุชู
ุงููุดุฑ ุจูุฌุงุญ!", show_alert=True)
|
| 423 |
+
else:
|
| 424 |
+
await callback.answer("โ ูุดู ุงููุดุฑ.", show_alert=True)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
async def blogger_publish_article_draft(client, callback):
|
| 428 |
+
fingerprint = callback.data[len("blogger_publish_draft_"):]
|
| 429 |
+
pub = get_publisher()
|
| 430 |
+
article = pub.db.get_article(fingerprint)
|
| 431 |
+
if not article:
|
| 432 |
+
await callback.answer("ุงูู
ูุดูุฑ ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 433 |
+
return
|
| 434 |
+
html = pub.processor.make_article_html(article)
|
| 435 |
+
section = article.get("section", "")
|
| 436 |
+
labels = list(pub.scheduler._get_section_labels(section))
|
| 437 |
+
blogger_article = {
|
| 438 |
+
"title": article.get("title", "ุนููุงู ุงูู
ูุงู"),
|
| 439 |
+
"content": html,
|
| 440 |
+
"labels": labels,
|
| 441 |
+
}
|
| 442 |
+
await callback.answer("ุฌุงุฑู ุงููุดุฑ ูู
ุณูุฏุฉ...")
|
| 443 |
+
post_id = await pub.publish_article(blogger_article, fingerprint, draft=True)
|
| 444 |
+
if post_id:
|
| 445 |
+
pub.db.update_article_status(fingerprint, "draft", {"post_id": post_id, "published_at": int(time.time())})
|
| 446 |
+
await callback.answer("โ
ุชู
ุงููุดุฑ ูู
ุณูุฏุฉ!", show_alert=True)
|
| 447 |
+
else:
|
| 448 |
+
await callback.answer("โ ูุดู ุงููุดุฑ.", show_alert=True)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
async def blogger_discard_article(client, callback):
|
| 452 |
+
fingerprint = callback.data[len("blogger_discard_"):]
|
| 453 |
+
pub = get_publisher()
|
| 454 |
+
article = pub.db.get_article(fingerprint)
|
| 455 |
+
if article:
|
| 456 |
+
pub.db.update_article_status(fingerprint, "discarded", {"discarded_at": int(time.time())})
|
| 457 |
+
await callback.answer("๐ ุชู
ุงูุญูุธ ููุฅูุบุงุก.", show_alert=True)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
async def blogger_ch_section_prompt(client, callback):
|
| 461 |
+
from bot_core import user_states
|
| 462 |
+
ch_id = callback.data.split("_")[-1]
|
| 463 |
+
uid = callback.from_user.id
|
| 464 |
+
pub = get_publisher()
|
| 465 |
+
sections = pub.db.get_all_sections()
|
| 466 |
+
buttons = []
|
| 467 |
+
if sections:
|
| 468 |
+
for sid, sdata in sections.items():
|
| 469 |
+
sname = sdata.get("name", sid)
|
| 470 |
+
buttons.append(InlineKeyboardButton(sname, callback_data=f"blogger_ch_sec_set_{ch_id}_{sid}"))
|
| 471 |
+
buttons.append(InlineKeyboardButton("โ ุฅุถุงูุฉ ูุณู
ุฌุฏูุฏ", callback_data=f"blogger_ch_sec_new_{ch_id}"))
|
| 472 |
+
rows = _grid_buttons(buttons, 2)
|
| 473 |
+
rows.append(_nav_row(uid, f"blogger_edit_ch_{ch_id}"))
|
| 474 |
+
ch = pub.db.get_channel(ch_id)
|
| 475 |
+
current = ch.get("section", "ุบูุฑ ู
ุญุฏุฏ") if ch else "ุบูุฑ ู
ุญุฏุฏ"
|
| 476 |
+
await safe_edit(callback, f"๐ **ุงุฎุชุฑ ุงููุณู
**\nุงููุณู
ุงูุญุงูู: {current}\nุฃู ุฃุถู ูุณู
ุงู ุฌุฏูุฏุงู:", InlineKeyboardMarkup(rows))
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
async def blogger_ch_sec_set(client, callback):
|
| 480 |
+
parts = callback.data.split("_")
|
| 481 |
+
ch_id = parts[-2]
|
| 482 |
+
sid = parts[-1]
|
| 483 |
+
pub = get_publisher()
|
| 484 |
+
sections = pub.db.get_all_sections()
|
| 485 |
+
sdata = sections.get(sid)
|
| 486 |
+
if not sdata:
|
| 487 |
+
await callback.answer("ุงููุณู
ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 488 |
+
return
|
| 489 |
+
section_name = sdata.get("name", sid)
|
| 490 |
+
ch = pub.db.get_channel(ch_id)
|
| 491 |
+
if ch:
|
| 492 |
+
ch["section"] = section_name
|
| 493 |
+
pub.db.save_channel(ch_id, ch)
|
| 494 |
+
await callback.answer(f"โ
ุชู
ุชุนููู ุงููุณู
: {section_name}")
|
| 495 |
+
callback.data = f"blogger_edit_ch_{ch_id}"
|
| 496 |
+
await blogger_edit_channel_menu(client, callback)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
async def blogger_ch_sec_new(client, callback):
|
| 500 |
+
from bot_core import user_states
|
| 501 |
+
ch_id = callback.data.split("_")[-1]
|
| 502 |
+
uid = callback.from_user.id
|
| 503 |
+
user_states[uid] = {"state": "blogger_ch_sec_new_input", "ch_id": ch_id}
|
| 504 |
+
await safe_edit(callback, "ุฃุฑุณู ุงุณู
ุงููุณู
ุงูุฌุฏูุฏ:", InlineKeyboardMarkup([_nav_row(uid, f"blogger_ch_section_{ch_id}")]))
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def blogger_ch_limit_prompt(client, callback):
|
| 508 |
+
from bot_core import user_states
|
| 509 |
+
ch_id = callback.data.split("_")[-1]
|
| 510 |
+
uid = callback.from_user.id
|
| 511 |
+
user_states[uid] = {"state": "blogger_ch_limit_input", "ch_id": ch_id}
|
| 512 |
+
await safe_edit(callback, "ุฃุฑุณู ุงูุญุฏ ุงูููู
ู ุงูุฌุฏูุฏ:\nู
ุซุงู: 30", InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
async def blogger_ch_hours_prompt(client, callback):
|
| 516 |
+
from bot_core import user_states
|
| 517 |
+
ch_id = callback.data.split("_")[-1]
|
| 518 |
+
uid = callback.from_user.id
|
| 519 |
+
user_states[uid] = {"state": "blogger_ch_hours_input", "ch_id": ch_id}
|
| 520 |
+
await safe_edit(callback, "ุฃุฑุณู ุณุงุนุงุช ุงููุดุฑ ุจุงูุชูุณูู:\n`start_hour-end_hour`\nู
ุซุงู: 9-23", InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
async def blogger_sections_main_menu(client, callback):
|
| 524 |
+
uid = callback.from_user.id
|
| 525 |
+
_push_nav(uid, "blogger_sections_main")
|
| 526 |
+
pub = get_publisher()
|
| 527 |
+
sections = pub.db.get_all_sections()
|
| 528 |
+
text = f"๐ **ุฅุฏุงุฑุฉ ุงูุฃูุณุงู
**\n\nุนุฏุฏ ุงูุฃูุณุงู
: {len(sections)}"
|
| 529 |
+
buttons = [
|
| 530 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ูุณู
", callback_data="blogger_section_add"),
|
| 531 |
+
InlineKeyboardButton("๐ ูุงุฆู
ุฉ ุงูุฃูุณุงู
", callback_data="blogger_sections"),
|
| 532 |
+
]
|
| 533 |
+
rows = _grid_buttons(buttons, 2)
|
| 534 |
+
rows.append(_nav_row(uid))
|
| 535 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
async def blogger_section_add_prompt(client, callback):
|
| 539 |
+
uid = callback.from_user.id
|
| 540 |
+
_push_nav(uid, "blogger_section_add_prompt")
|
| 541 |
+
from bot_core import user_states
|
| 542 |
+
user_states.pop(uid, None)
|
| 543 |
+
user_states[uid] = {"state": "blogger_section_add_name"}
|
| 544 |
+
await safe_edit(callback, "ุฃุฑุณู ุงุณู
ุงููุณู
ุงูุฌุฏูุฏ:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
async def blogger_section_detail_menu(client, callback):
|
| 548 |
+
uid = callback.from_user.id
|
| 549 |
+
_push_nav(uid, f"blogger_section_detail_{callback.data.split('_')[-1]}")
|
| 550 |
+
sid = callback.data.split("_")[-1]
|
| 551 |
+
pub = get_publisher()
|
| 552 |
+
sections = pub.db.get_all_sections()
|
| 553 |
+
sdata = sections.get(sid)
|
| 554 |
+
if not sdata:
|
| 555 |
+
await callback.answer("ุงููุณู
ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 556 |
+
return
|
| 557 |
+
name = sdata.get("name", sid)
|
| 558 |
+
labels = sdata.get("labels", [])
|
| 559 |
+
label_text = "ุ ".join(labels) if labels else "ูุง ุชูุฌุฏ ุชุณู
ูุงุช"
|
| 560 |
+
text = (
|
| 561 |
+
f"๐ **{name}**\n\n"
|
| 562 |
+
f"ุงูุฑูู
ุงูุชุนุฑููู: `{sid}`\n"
|
| 563 |
+
f"๐ท๏ธ ุงูุชุณู
ูุงุช: {label_text}\n"
|
| 564 |
+
)
|
| 565 |
+
buttons = [
|
| 566 |
+
InlineKeyboardButton("โ
ุงุฎุชูุงุฑ ุงููุณู
", callback_data=f"blogger_sec_pick_{sid}"),
|
| 567 |
+
InlineKeyboardButton("โ๏ธ ุชุนุฏูู ุงูุงุณู
", callback_data=f"blogger_section_edit_{sid}"),
|
| 568 |
+
InlineKeyboardButton("๐ท๏ธ ุฅุฏุงุฑุฉ ุงูุชุณู
ูุงุช", callback_data=f"blogger_sec_labels_{sid}"),
|
| 569 |
+
InlineKeyboardButton("๐ ุญุฐู ุงููุณู
", callback_data=f"blogger_section_del_{sid}"),
|
| 570 |
+
]
|
| 571 |
+
rows = _grid_buttons(buttons, 2)
|
| 572 |
+
rows.append(_nav_row(uid))
|
| 573 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
async def blogger_sec_pick(client, callback):
|
| 577 |
+
sid = callback.data.split("_")[-1]
|
| 578 |
+
pub = get_publisher()
|
| 579 |
+
sections = pub.db.get_all_sections()
|
| 580 |
+
sdata = sections.get(sid)
|
| 581 |
+
if not sdata:
|
| 582 |
+
await callback.answer("ุงููุณู
ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 583 |
+
return
|
| 584 |
+
section_name = sdata.get("name", sid)
|
| 585 |
+
channels = pub.db.get_all_channels()
|
| 586 |
+
text = f"โ
ุงุฎุชุฑ ุงูููุงุฉ ูุชุนููู ุงููุณู
**{section_name}**:"
|
| 587 |
+
buttons = []
|
| 588 |
+
for ch in channels:
|
| 589 |
+
ch_id = ch.get("channel_id", "")
|
| 590 |
+
ch_name = ch.get("name", ch_id)
|
| 591 |
+
buttons.append([InlineKeyboardButton(f"๐ข {ch_name}", callback_data=f"blogger_sec_set_ch_{sid}_{ch_id}")])
|
| 592 |
+
uid = callback.from_user.id
|
| 593 |
+
buttons.append(_nav_row(uid))
|
| 594 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
async def blogger_sec_set_ch(client, callback):
|
| 598 |
+
parts = callback.data.split("_")
|
| 599 |
+
sid = parts[-2]
|
| 600 |
+
ch_id = parts[-1]
|
| 601 |
+
pub = get_publisher()
|
| 602 |
+
sections = pub.db.get_all_sections()
|
| 603 |
+
sdata = sections.get(sid)
|
| 604 |
+
if not sdata:
|
| 605 |
+
await callback.answer("ุงููุณู
ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 606 |
+
return
|
| 607 |
+
section_name = sdata.get("name", sid)
|
| 608 |
+
ch = pub.db.get_channel(ch_id)
|
| 609 |
+
if ch:
|
| 610 |
+
ch["section"] = section_name
|
| 611 |
+
pub.db.save_channel(ch_id, ch)
|
| 612 |
+
await callback.answer(f"โ
ุชู
ุชุนููู ุงููุณู
{section_name} ููููุงุฉ")
|
| 613 |
+
await blogger_section_detail_menu(client, callback)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
async def blogger_sec_labels_menu(client, callback):
|
| 617 |
+
uid = callback.from_user.id
|
| 618 |
+
_push_nav(uid, f"blogger_sec_labels_{callback.data.split('_')[-1]}")
|
| 619 |
+
sid = callback.data.split("_")[-1]
|
| 620 |
+
pub = get_publisher()
|
| 621 |
+
sections = pub.db.get_all_sections()
|
| 622 |
+
sdata = sections.get(sid)
|
| 623 |
+
if not sdata:
|
| 624 |
+
await callback.answer("ุงููุณู
ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 625 |
+
return
|
| 626 |
+
name = sdata.get("name", sid)
|
| 627 |
+
labels = sdata.get("labels", [])
|
| 628 |
+
text = f"๐ท๏ธ **ุชุณู
ูุงุช {name}**\n\n"
|
| 629 |
+
if labels:
|
| 630 |
+
text += "ุงูุชุณู
ูุงุช ุงูุญุงููุฉ:\n"
|
| 631 |
+
for i, label in enumerate(labels, 1):
|
| 632 |
+
text += f"{i}. {label}\n"
|
| 633 |
+
else:
|
| 634 |
+
text += "ูุง ุชูุฌุฏ ุชุณู
ูุงุช.\n"
|
| 635 |
+
text += "\nุงุฎุชุฑ ุชุณู
ูุฉ ูุญุฐููุง ุฃู ุฃุถู ุชุณู
ูุฉ ุฌุฏูุฏุฉ:"
|
| 636 |
+
buttons = [
|
| 637 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ุชุณู
ูุฉ", callback_data=f"blogger_sec_add_label_{sid}"),
|
| 638 |
+
]
|
| 639 |
+
for label in labels:
|
| 640 |
+
short = label[:20]
|
| 641 |
+
buttons.append(InlineKeyboardButton(f"๐ {short}", callback_data=f"blogger_sec_del_label_{sid}_{label}"))
|
| 642 |
+
rows = _grid_buttons(buttons, 2)
|
| 643 |
+
rows.append(_nav_row(uid))
|
| 644 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
async def blogger_sec_add_label_prompt(client, callback):
|
| 648 |
+
uid = callback.from_user.id
|
| 649 |
+
_push_nav(uid, f"blogger_sec_add_label_{callback.data.split('_')[-1]}")
|
| 650 |
+
sid = callback.data.split("_")[-1]
|
| 651 |
+
from bot_core import user_states
|
| 652 |
+
user_states[uid] = {"state": "blogger_sec_add_label_input", "sid": sid}
|
| 653 |
+
await safe_edit(callback, "ุฃุฑุณู ุงูุชุณู
ูุฉ ุงูุฌุฏูุฏุฉ:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
async def blogger_sec_del_label(client, callback):
|
| 657 |
+
parts = callback.data.split("_")
|
| 658 |
+
sid = parts[-2]
|
| 659 |
+
label = parts[-1]
|
| 660 |
+
pub = get_publisher()
|
| 661 |
+
sections = pub.db.get_all_sections()
|
| 662 |
+
sdata = sections.get(sid)
|
| 663 |
+
if sdata:
|
| 664 |
+
labels = sdata.get("labels", [])
|
| 665 |
+
if label in labels:
|
| 666 |
+
labels.remove(label)
|
| 667 |
+
sdata["labels"] = labels
|
| 668 |
+
pub.db.add_section(sid, sdata)
|
| 669 |
+
await callback.answer(f"โ
ุชู
ุญุฐู ุงูุชุณู
ูุฉ: {label}")
|
| 670 |
+
await blogger_sec_labels_menu(client, callback)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
async def blogger_advanced_menu(client, callback):
|
| 674 |
+
uid = callback.from_user.id
|
| 675 |
+
_push_nav(uid, "blogger_advanced")
|
| 676 |
+
pub = get_publisher()
|
| 677 |
+
cfg = pub.config.get_all()
|
| 678 |
+
text = (
|
| 679 |
+
f"โ๏ธ **ุงูุฅุนุฏุงุฏุงุช ุงูู
ุชูุฏู
ุฉ**\n\n"
|
| 680 |
+
f"๐ ู
ูุงุชูุญ Gemini: {len(pub.db.get_all_ai_keys())}\n"
|
| 681 |
+
f"๐ ุณุฌู ุงูุนู
ููุงุช: ู
ุชุงุญ\n"
|
| 682 |
+
f"๐งช ุงุฎุชุจุงุฑ ุงูุงุชุตุงู: ู
ุชุงุญ\n"
|
| 683 |
+
)
|
| 684 |
+
buttons = [
|
| 685 |
+
InlineKeyboardButton("๐ ู
ูุงุชูุญ Gemini", callback_data="blogger_ai_keys"),
|
| 686 |
+
InlineKeyboardButton("๐ ุณุฌู ุงูุนู
ููุงุช", callback_data="blogger_logs"),
|
| 687 |
+
InlineKeyboardButton("๐งช ุงุฎุชุจุงุฑ ุงูุงุชุตุงู", callback_data="blogger_test"),
|
| 688 |
+
InlineKeyboardButton(f"{'โ
' if pub.config.is_enabled() else 'โ'} ุชุดุบูู/ุฅููุงู", callback_data="blogger_toggle"),
|
| 689 |
+
]
|
| 690 |
+
rows = _grid_buttons(buttons, 2)
|
| 691 |
+
rows.append(_nav_row(uid))
|
| 692 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
async def blogger_schedule_info(client, callback):
|
| 696 |
+
uid = callback.from_user.id
|
| 697 |
+
_push_nav(uid, "blogger_schedule_info")
|
| 698 |
+
pub = get_publisher()
|
| 699 |
+
state = pub.db.get_schedule_state()
|
| 700 |
+
today = time.strftime("%Y-%m-%d")
|
| 701 |
+
last_slot = state.get("last_slot", -1) if state.get("day") == today else -1
|
| 702 |
+
slots_total = SLOTS_PER_DAY
|
| 703 |
+
used = last_slot + 1
|
| 704 |
+
remaining = max(0, slots_total - used)
|
| 705 |
+
queue = len([a for a in pub.db.get_articles_by_status("queued")])
|
| 706 |
+
text = (
|
| 707 |
+
f"๐ **ุฌุฏููุฉ ุงููุดุฑ**\n\n"
|
| 708 |
+
f"โฐ ููุช ุงูุจุฏุก: 09:00 ุตุจุงุญุงู\n"
|
| 709 |
+
f"โฐ ููุช ุงูุงูุชูุงุก: 23:00 ู
ุณุงุกู\n"
|
| 710 |
+
f"โฑ๏ธ ุงููุงุตู ุจูู ุงูู
ูุงูุงุช: 30 ุฏูููุฉ\n"
|
| 711 |
+
f"๐ ุงููุชุฑุงุช ุงูู
ุชุงุญุฉ ุงูููู
: {slots_total}\n"
|
| 712 |
+
f"โ
ุงููุชุฑุงุช ุงูู
ุณุชุฎุฏู
ุฉ: {used}\n"
|
| 713 |
+
f"๐
ุงููุชุฑุงุช ุงูู
ุชุจููุฉ: {remaining}\n"
|
| 714 |
+
f"๐ฅ ุงูู
ูุงูุงุช ูู Queue: {queue}\n"
|
| 715 |
+
)
|
| 716 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([_nav_row(uid)]))
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
async def blogger_preview_last(client, callback):
|
| 720 |
+
uid = callback.from_user.id
|
| 721 |
+
_push_nav(uid, "blogger_preview_last")
|
| 722 |
+
pub = get_publisher()
|
| 723 |
+
articles = pub.db.get_articles_by_status("queued")
|
| 724 |
+
if not articles:
|
| 725 |
+
await safe_edit(callback, "๐ญ **ู
ุนุงููุฉ ุขุฎุฑ ู
ูุดูุฑ**\n\nูุง ุชูุฌุฏ ู
ูุดูุฑุงุช ุจุงูุชุธุงุฑ ุงููุดุฑ.", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 726 |
+
return
|
| 727 |
+
article = articles[-1]
|
| 728 |
+
fingerprint = article.get("fingerprint", "")
|
| 729 |
+
if not fingerprint:
|
| 730 |
+
await safe_edit(callback, "โ ูุง ูู
ูู ุนุฑุถ ุงูู
ุนุงููุฉ.", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 731 |
+
return
|
| 732 |
+
title = article.get("title", "ุจุฏูู ุนููุงู")
|
| 733 |
+
section = article.get("section", "ุนุงู
")
|
| 734 |
+
labels = article.get("labels", [])
|
| 735 |
+
status = article.get("status", "ุบูุฑ ู
ุนุฑูู")
|
| 736 |
+
key_used = article.get("gemini_key", article.get("_session_kid", "ุบูุฑ ู
ุญุฏุฏ"))
|
| 737 |
+
publish_time = article.get("scheduled_time", "ุญุณุจ ุงูุฌุฏููุฉ")
|
| 738 |
+
created_at = article.get("created_at", 0)
|
| 739 |
+
if created_at:
|
| 740 |
+
created_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(created_at))
|
| 741 |
+
else:
|
| 742 |
+
created_str = "ุบูุฑ ู
ุนุฑูู"
|
| 743 |
+
label_text = "ุ ".join(labels) if labels else "ูุง ุชูุฌุฏ"
|
| 744 |
+
info = (
|
| 745 |
+
f"๐ **ู
ุนุงููุฉ ุขุฎุฑ ู
ูุดูุฑ ูู Queue**\n\n"
|
| 746 |
+
f"๐ **ุงูุนููุงู:** {title}\n"
|
| 747 |
+
f"๐ **ุงููุณู
:** {section}\n"
|
| 748 |
+
f"๐ท๏ธ **ุงูุชุณู
ูุงุช:** {label_text}\n"
|
| 749 |
+
f"๐ **ุชุงุฑูุฎ ุงูุฅุถุงูุฉ:** {created_str}\n"
|
| 750 |
+
f"โฐ **ููุช ุงููุดุฑ:** {publish_time}\n"
|
| 751 |
+
f"๐ **ุงูู
ูุชุงุญ:** {key_used}\n"
|
| 752 |
+
f"๐ **ุงูุญุงูุฉ:** {status}\n\n"
|
| 753 |
+
f"---\n"
|
| 754 |
+
)
|
| 755 |
+
html = pub.processor.make_article_html(article)
|
| 756 |
+
preview_text = pub.processor.html_to_telegram(html)
|
| 757 |
+
full_text = info + preview_text
|
| 758 |
+
if len(full_text) > 4096:
|
| 759 |
+
full_text = full_text[:4093] + "..."
|
| 760 |
+
image_source = None
|
| 761 |
+
media = article.get("media", [])
|
| 762 |
+
for m in media:
|
| 763 |
+
if m.get("type") == "photo":
|
| 764 |
+
image_source = m.get("file_id")
|
| 765 |
+
break
|
| 766 |
+
if not image_source:
|
| 767 |
+
image_source = pub.config.get("default_jobs_image", "")
|
| 768 |
+
buttons = [
|
| 769 |
+
InlineKeyboardButton("๐ค ูุดุฑ ุงูุขู", callback_data=f"blogger_publish_now_{fingerprint}"),
|
| 770 |
+
InlineKeyboardButton("๐พ ูู
ุณูุฏุฉ", callback_data=f"blogger_publish_draft_{fingerprint}"),
|
| 771 |
+
InlineKeyboardButton("๐ ุญุฐู", callback_data=f"blogger_discard_{fingerprint}"),
|
| 772 |
+
]
|
| 773 |
+
rows = _grid_buttons(buttons, 2)
|
| 774 |
+
rows.append(_nav_row(uid))
|
| 775 |
+
markup = InlineKeyboardMarkup(rows)
|
| 776 |
+
if image_source:
|
| 777 |
+
try:
|
| 778 |
+
await client.send_photo(callback.from_user.id, photo=image_source, caption=f"๐ **{title[:30]}**")
|
| 779 |
+
except Exception as e:
|
| 780 |
+
logger.warning(f"Failed to send preview photo: {e}")
|
| 781 |
+
await client.send_message(callback.from_user.id, full_text, reply_markup=markup)
|
| 782 |
+
try:
|
| 783 |
+
await callback.message.delete()
|
| 784 |
+
except Exception:
|
| 785 |
+
pass
|
| 786 |
+
await callback.answer("โ
ุชู
ุฅุฑุณุงู ุงูู
ุนุงููุฉ", show_alert=True)
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
async def blogger_sections_menu(client, callback):
|
| 790 |
+
uid = callback.from_user.id
|
| 791 |
+
_push_nav(uid, "blogger_sections")
|
| 792 |
+
pub = get_publisher()
|
| 793 |
+
sections = pub.db.get_all_sections()
|
| 794 |
+
text = f"๐ **ูุงุฆู
ุฉ ุงูุฃูุณุงู
**\n\nุนุฏุฏ ุงูุฃูุณุงู
: {len(sections)}"
|
| 795 |
+
if sections:
|
| 796 |
+
text += "\n\nุงุฎุชุฑ ูุณู
ุงู ูุนุฑุถ ุงูุชูุงุตูู:"
|
| 797 |
+
else:
|
| 798 |
+
text += "\n\nูุง ุชูุฌุฏ ุฃูุณุงู
ุจุนุฏ.\nูู
ููู ุฅุถุงูุฉ ูุณู
ุฌุฏูุฏ."
|
| 799 |
+
buttons = []
|
| 800 |
+
for sid, sdata in sections.items():
|
| 801 |
+
name = sdata.get("name", sid)
|
| 802 |
+
buttons.append([InlineKeyboardButton(f"๐ {name}", callback_data=f"blogger_section_detail_{sid}")])
|
| 803 |
+
buttons.append(_nav_row(uid))
|
| 804 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
async def blogger_section_edit(client, callback):
|
| 808 |
+
uid = callback.from_user.id
|
| 809 |
+
_push_nav(uid, f"blogger_section_edit_{callback.data.split('_')[-1]}")
|
| 810 |
+
sid = callback.data.split("_")[-1]
|
| 811 |
+
from bot_core import user_states
|
| 812 |
+
user_states[uid] = {"state": "blogger_section_rename", "sid": sid}
|
| 813 |
+
await safe_edit(callback, "ุฃุฑุณู ุงูุงุณู
ุงูุฌุฏูุฏ ูููุณู
:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
async def blogger_section_del(client, callback):
|
| 817 |
+
sid = callback.data.split("_")[-1]
|
| 818 |
+
pub = get_publisher()
|
| 819 |
+
pub.db.delete_section(sid)
|
| 820 |
+
await callback.answer("โ
ุชู
ุญุฐู ุงููุณู
.")
|
| 821 |
+
await blogger_sections_main_menu(client, callback)
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
async def blogger_stats_menu(client, callback):
|
| 825 |
+
uid = callback.from_user.id
|
| 826 |
+
_push_nav(uid, "blogger_stats")
|
| 827 |
+
pub = get_publisher()
|
| 828 |
+
stats = pub.db.get_stats()
|
| 829 |
+
text = (
|
| 830 |
+
f"๐ **ุฅุญุตุงุฆูุงุช Blogger**\n\n"
|
| 831 |
+
f"โ
ุงูู
ูุดูุฑุงุช: {stats.get('total_published', 0)}\n"
|
| 832 |
+
f"โ ุงููุงุดูุฉ: {stats.get('total_failed', 0)}"
|
| 833 |
+
)
|
| 834 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([_nav_row(uid)]))
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
async def blogger_logs_menu(client, callback):
|
| 838 |
+
uid = callback.from_user.id
|
| 839 |
+
_push_nav(uid, "blogger_logs")
|
| 840 |
+
pub = get_publisher()
|
| 841 |
+
logs = pub.db.get_logs(20)
|
| 842 |
+
text = "๐ **ุขุฎุฑ ุงูุนู
ููุงุช**\n\n"
|
| 843 |
+
if not logs:
|
| 844 |
+
text += "ูุง ุชูุฌุฏ ุนู
ููุงุช."
|
| 845 |
+
else:
|
| 846 |
+
for entry in logs:
|
| 847 |
+
ts = entry.get("time", 0)
|
| 848 |
+
tstr = time.strftime("%H:%M", time.localtime(ts)) if ts else "?"
|
| 849 |
+
st = "โ
" if entry.get("status") == "success" else "โ"
|
| 850 |
+
title = entry.get("title", "")[:30]
|
| 851 |
+
text += f"{st} [{tstr}] {title}\n"
|
| 852 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([_nav_row(uid)]))
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
async def blogger_test_handler(client, callback):
|
| 856 |
+
uid = callback.from_user.id
|
| 857 |
+
_push_nav(uid, "blogger_test")
|
| 858 |
+
pub = get_publisher()
|
| 859 |
+
if not pub.client.is_configured():
|
| 860 |
+
await safe_edit(
|
| 861 |
+
callback,
|
| 862 |
+
"โ ุงูุฅุนุฏุงุฏุงุช ุบูุฑ ู
ูุชู
ูุฉ. ุฃุถู Blog ID ู Client ID ู Secret ู Refresh Token ุฃููุงู.",
|
| 863 |
+
InlineKeyboardMarkup([_nav_row(uid)])
|
| 864 |
+
)
|
| 865 |
+
return
|
| 866 |
+
await callback.answer("ุฌุงุฑู ุงุฎุชุจุงุฑ ุงูุงุชุตุงู...")
|
| 867 |
+
ok = await pub.test_connection()
|
| 868 |
+
if ok:
|
| 869 |
+
await safe_edit(
|
| 870 |
+
callback,
|
| 871 |
+
"โ
**ุชู
ุงูุงุชุตุงู ุจูุฌุงุญ**\n\nBlogger ูุนู
ู ุจุดูู ุตุญูุญ.",
|
| 872 |
+
InlineKeyboardMarkup([_nav_row(uid)])
|
| 873 |
+
)
|
| 874 |
+
else:
|
| 875 |
+
await safe_edit(
|
| 876 |
+
callback,
|
| 877 |
+
"โ **ูุดู ุงูุงุชุตุงู**\n\nุชุญูู ู
ู ุงูุฅุนุฏุงุฏุงุช ูุฑุงุฌุน ุงูุณุฌู.",
|
| 878 |
+
InlineKeyboardMarkup([_nav_row(uid)])
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
async def blogger_toggle_handler(client, callback):
|
| 883 |
+
uid = callback.from_user.id
|
| 884 |
+
pub = get_publisher()
|
| 885 |
+
new_state = not pub.config.is_enabled()
|
| 886 |
+
pub.config.set("enabled", new_state)
|
| 887 |
+
status = "โ
ุชู
ุงูุชูุนูู" if new_state else "โ ุชู
ุงูุฅููุงู"
|
| 888 |
+
await callback.answer(status, show_alert=True)
|
| 889 |
+
await blogger_main_menu(client, callback)
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
async def blogger_toggle_draft_handler(client, callback):
|
| 893 |
+
uid = callback.from_user.id
|
| 894 |
+
pub = get_publisher()
|
| 895 |
+
current = pub.config.get("publish_as_draft", False)
|
| 896 |
+
pub.config.set("publish_as_draft", not current)
|
| 897 |
+
await callback.answer("ุชู
ุงูุชุญุฏูุซ.")
|
| 898 |
+
await blogger_settings_menu(client, callback)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
async def set_blog_id_prompt(client, callback):
|
| 902 |
+
uid = callback.from_user.id
|
| 903 |
+
_push_nav(uid, "blogger_set_blog_id")
|
| 904 |
+
from bot_core import user_states
|
| 905 |
+
user_states.pop(uid, None)
|
| 906 |
+
user_states[uid] = {"state": "blogger_set_blog_id"}
|
| 907 |
+
await safe_edit(callback, "ุฃุฑุณู Blog ID ุงูุฎุงุต ุจู
ุฏููุชู:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
async def set_client_id_prompt(client, callback):
|
| 911 |
+
uid = callback.from_user.id
|
| 912 |
+
_push_nav(uid, "blogger_set_client_id")
|
| 913 |
+
from bot_core import user_states
|
| 914 |
+
user_states.pop(uid, None)
|
| 915 |
+
user_states[uid] = {"state": "blogger_set_client_id"}
|
| 916 |
+
await safe_edit(callback, "ุฃุฑุณู Client ID ู
ู Google Cloud Console:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
async def set_client_secret_prompt(client, callback):
|
| 920 |
+
uid = callback.from_user.id
|
| 921 |
+
_push_nav(uid, "blogger_set_client_secret")
|
| 922 |
+
from bot_core import user_states
|
| 923 |
+
user_states.pop(uid, None)
|
| 924 |
+
user_states[uid] = {"state": "blogger_set_client_secret"}
|
| 925 |
+
await safe_edit(callback, "ุฃุฑุณู Client Secret:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
async def set_refresh_token_prompt(client, callback):
|
| 929 |
+
uid = callback.from_user.id
|
| 930 |
+
_push_nav(uid, "blogger_set_refresh_token")
|
| 931 |
+
from bot_core import user_states
|
| 932 |
+
user_states.pop(uid, None)
|
| 933 |
+
user_states[uid] = {"state": "blogger_set_refresh_token"}
|
| 934 |
+
await safe_edit(callback, "ุฃุฑุณู Refresh Token:", InlineKeyboardMarkup([_nav_row(uid)]))
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
async def set_default_image_prompt(client, callback):
|
| 938 |
+
uid = callback.from_user.id
|
| 939 |
+
_push_nav(uid, "blogger_set_default_image")
|
| 940 |
+
pub = get_publisher()
|
| 941 |
+
current = pub.config.get("default_jobs_image", "")
|
| 942 |
+
if current:
|
| 943 |
+
text = (
|
| 944 |
+
f"๐ผ **ุฅุนุฏุงุฏุงุช ุงูุตูุฑุฉ ุงูุงูุชุฑุงุถูุฉ**\n\n"
|
| 945 |
+
f"โ
ููุฌุฏ ุฑุงุจุท ุตูุฑุฉ ู
ุญููุธ:\n"
|
| 946 |
+
f"`{current[:80]}{'...' if len(current) > 80 else ''}`\n\n"
|
| 947 |
+
f"ุงุฎุชุฑ ู
ู ุงูุฎูุงุฑุงุช ุฃุฏูุงู:"
|
| 948 |
+
)
|
| 949 |
+
buttons = [
|
| 950 |
+
InlineKeyboardButton("๐ ู
ุนุงููุฉ ุงูุตูุฑุฉ", callback_data="blogger_preview_image"),
|
| 951 |
+
InlineKeyboardButton("โ๏ธ ุชุนุฏูู ุงูุฑุงุจุท", callback_data="blogger_edit_image"),
|
| 952 |
+
InlineKeyboardButton("๐ ุญุฐู ุงูุตูุฑุฉ", callback_data="blogger_delete_image"),
|
| 953 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ุตูุฑุฉ ุฌุฏูุฏุฉ", callback_data="blogger_add_image"),
|
| 954 |
+
]
|
| 955 |
+
else:
|
| 956 |
+
text = "๐ผ **ุฅุนุฏุงุฏุงุช ุงูุตูุฑุฉ ุงูุงูุชุฑุงุถูุฉ**\n\nโ ูุง ุชูุฌุฏ ุตูุฑุฉ.\n\nูู
ููู ุฅุถุงูุฉ ุตูุฑุฉ ุงูุชุฑุงุถูุฉ ููู
ูุงูุงุช:"
|
| 957 |
+
buttons = [
|
| 958 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ุตูุฑุฉ", callback_data="blogger_add_image"),
|
| 959 |
+
]
|
| 960 |
+
rows = _grid_buttons(buttons, 2)
|
| 961 |
+
rows.append(_nav_row(uid))
|
| 962 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
async def blogger_preview_image_handler(client, callback):
|
| 966 |
+
pub = get_publisher()
|
| 967 |
+
current = pub.config.get("default_jobs_image", "")
|
| 968 |
+
if not current:
|
| 969 |
+
await callback.answer("โ ูุง ุชูุฌุฏ ุตูุฑุฉ.", show_alert=True)
|
| 970 |
+
return
|
| 971 |
+
if not current.startswith(("http://", "https://")):
|
| 972 |
+
await callback.answer("โ ุงูุฑุงุจุท ุงูู
ุฎุฒู ุบูุฑ ุตุงูุญ. ูุฌุจ ุฃู ูุจุฏุฃ ุจู http:// ุฃู https://", show_alert=True)
|
| 973 |
+
return
|
| 974 |
+
try:
|
| 975 |
+
await client.send_photo(callback.from_user.id, photo=current, caption="๐ผ **ุงูุตูุฑุฉ ุงูุงูุชุฑุงุถูุฉ ุงูุญุงููุฉ**")
|
| 976 |
+
await callback.answer("โ
ุชู
ุฅุฑุณุงู ุงูุตูุฑุฉ")
|
| 977 |
+
except Exception as e:
|
| 978 |
+
logger.warning(f"Failed to send image: {e}")
|
| 979 |
+
await callback.answer(f"โ ูุดู ุฅุฑุณุงู ุงูุตูุฑุฉ: {str(e)[:30]}", show_alert=True)
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
async def blogger_edit_image_prompt(client, callback):
|
| 983 |
+
from bot_core import user_states
|
| 984 |
+
user_states.pop(callback.from_user.id, None)
|
| 985 |
+
user_states[callback.from_user.id] = {"state": "blogger_set_default_image"}
|
| 986 |
+
await safe_edit(callback, "ุฃุฑุณู ุงูุฑุงุจุท ุงูุฌุฏูุฏ ููุตูุฑุฉ ุงูุงูุชุฑุงุถูุฉ:", InlineKeyboardMarkup([_nav_row(callback.from_user.id, "blogger_set_default_image")]))
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
async def blogger_add_image_prompt(client, callback):
|
| 990 |
+
from bot_core import user_states
|
| 991 |
+
user_states.pop(callback.from_user.id, None)
|
| 992 |
+
user_states[callback.from_user.id] = {"state": "blogger_set_default_image"}
|
| 993 |
+
await safe_edit(callback, "ุฃุฑุณู ุฑุงุจุท ุงูุตูุฑุฉ ุงูุฌุฏูุฏุฉ:", InlineKeyboardMarkup([_nav_row(callback.from_user.id, "blogger_set_default_image")]))
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
async def blogger_delete_image_handler(client, callback):
|
| 997 |
+
pub = get_publisher()
|
| 998 |
+
pub.config.set("default_jobs_image", "")
|
| 999 |
+
await callback.answer("โ
ุชู
ุญุฐู ุงูุตูุฑุฉ.", show_alert=True)
|
| 1000 |
+
await set_default_image_prompt(client, callback)
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
async def blogger_test_ai_key_handler(client, callback):
|
| 1004 |
+
pub = get_publisher()
|
| 1005 |
+
prefix = "blogger_test_ai_key_"
|
| 1006 |
+
kid = callback.data[len(prefix):]
|
| 1007 |
+
keys = dict(pub.db.get_all_ai_keys())
|
| 1008 |
+
for ekid, ekdata in pub.ai.key_manager.get_all_keys_summary().items():
|
| 1009 |
+
if ekdata.get("_source") == "env":
|
| 1010 |
+
keys[ekid] = ekdata
|
| 1011 |
+
kdata = keys.get(kid)
|
| 1012 |
+
if not kdata:
|
| 1013 |
+
await callback.answer("ุงูู
ูุชุงุญ ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1014 |
+
return
|
| 1015 |
+
api_key = kdata.get("key", "")
|
| 1016 |
+
if not api_key:
|
| 1017 |
+
await callback.answer("ุงูู
ูุชุงุญ ูุงุฑุบ.", show_alert=True)
|
| 1018 |
+
return
|
| 1019 |
+
await callback.answer("ุฌุงุฑู ุงุฎุชุจุงุฑ ุงูู
ูุชุงุญ...")
|
| 1020 |
+
import httpx
|
| 1021 |
+
from modules.blogger.ai_manager import (
|
| 1022 |
+
PROVIDER_CONFIGS, get_models, invalidate_model_cache,
|
| 1023 |
+
_gemini_chat, _openai_chat, _discover_gemini_models,
|
| 1024 |
+
)
|
| 1025 |
+
provider = kdata.get("_provider", "gemini")
|
| 1026 |
+
key_preview = api_key[:8] + "..."
|
| 1027 |
+
last_err = ""
|
| 1028 |
+
async with httpx.AsyncClient(timeout=30) as hc:
|
| 1029 |
+
try:
|
| 1030 |
+
if provider == "gemini":
|
| 1031 |
+
models = await _discover_gemini_models(hc, api_key)
|
| 1032 |
+
if not models:
|
| 1033 |
+
models = ["gemini-2.0-flash"]
|
| 1034 |
+
for model in models:
|
| 1035 |
+
code, data = await _gemini_chat(hc, api_key, model, "ูู ู
ุฑุญุจุง ุจุงูุนุฑุจูุฉ")
|
| 1036 |
+
if code == 200:
|
| 1037 |
+
txt = data if isinstance(data, str) else ""
|
| 1038 |
+
await callback.answer(f"โ
{model}: {txt[:80]}" if txt else f"โ
{model}: ุฑุฏ ูุงุฑุบ", show_alert=True)
|
| 1039 |
+
await blogger_ai_keys_menu(client, callback)
|
| 1040 |
+
return
|
| 1041 |
+
err_msg = data.get("message", str(data)) if isinstance(data, dict) else str(data)
|
| 1042 |
+
last_err = f"{code}: {err_msg[:60]}"
|
| 1043 |
+
else:
|
| 1044 |
+
base_url = PROVIDER_CONFIGS[provider]["api_base"]
|
| 1045 |
+
models = await get_models(provider, hc, api_key, force=True) if provider != "gemini" else []
|
| 1046 |
+
if not models:
|
| 1047 |
+
models = ["llama-3.1-8b-instant"]
|
| 1048 |
+
for model in models:
|
| 1049 |
+
code, data = await _openai_chat(hc, base_url, api_key, model, "ูู ู
ุฑุญุจุง ุจุงูุนุฑุจูุฉ")
|
| 1050 |
+
if code == 200:
|
| 1051 |
+
txt = data if isinstance(data, str) else ""
|
| 1052 |
+
await callback.answer(f"โ
{model}: {txt[:80]}" if txt else f"โ
{model}: ุฑุฏ ูุงุฑุบ", show_alert=True)
|
| 1053 |
+
await blogger_ai_keys_menu(client, callback)
|
| 1054 |
+
return
|
| 1055 |
+
err_msg = data.get("message", str(data)) if isinstance(data, dict) else str(data)
|
| 1056 |
+
last_err = f"{code}: {err_msg[:60]}"
|
| 1057 |
+
except Exception as e:
|
| 1058 |
+
last_err = str(e)[:60]
|
| 1059 |
+
await callback.answer(f"โ {provider}: ุฌู
ูุน ุงูู
ูุฏููุงุช ูุดูุช: {last_err}", show_alert=True)
|
| 1060 |
+
await blogger_ai_keys_menu(client, callback)
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
async def blogger_ai_keys_menu(client, callback):
|
| 1064 |
+
uid = callback.from_user.id
|
| 1065 |
+
pub = get_publisher()
|
| 1066 |
+
db_keys = pub.db.get_all_ai_keys()
|
| 1067 |
+
env_keys = {k: v for k, v in pub.ai.key_manager.get_all_keys_summary().items() if v.get("_source") == "env"}
|
| 1068 |
+
text = "๐ **ู
ูุงุชูุญ Gemini**\n\n"
|
| 1069 |
+
if not db_keys and not env_keys:
|
| 1070 |
+
text += "ูุง ุชูุฌุฏ ู
ูุงุชูุญ ุจุนุฏ.\nุฃุถู ู
ูุชุงุญุงู ุฌุฏูุฏุงู."
|
| 1071 |
+
else:
|
| 1072 |
+
if env_keys:
|
| 1073 |
+
text += "๐ **ู
ูุงุชูุญ ุงูุจูุฆุฉ (ู
ุญู
ูุฉ)**\n"
|
| 1074 |
+
for kid, kdata in env_keys.items():
|
| 1075 |
+
name = kdata.get("name", kid)
|
| 1076 |
+
usage = kdata.get("usage_count", 0)
|
| 1077 |
+
errors = kdata.get("error_count", 0)
|
| 1078 |
+
text += f"๐ `{name}`\n"
|
| 1079 |
+
text += f" ๐ {usage} ุทูุจ | โ {errors} ุฎุทุฃ\n"
|
| 1080 |
+
text += "\n"
|
| 1081 |
+
if db_keys:
|
| 1082 |
+
text += f"๐ **ู
ูุงุชูุญ ุงูุชุทุจูู**\n"
|
| 1083 |
+
for kid, kdata in db_keys.items():
|
| 1084 |
+
name = kdata.get("name", kid)
|
| 1085 |
+
status = "โ
" if kdata.get("enabled", True) else "โ"
|
| 1086 |
+
usage = kdata.get("usage_count", 0)
|
| 1087 |
+
errors = kdata.get("error_count", 0)
|
| 1088 |
+
last = kdata.get("last_used", 0)
|
| 1089 |
+
last_str = time.strftime("%H:%M", time.localtime(last)) if last else "ูู
ูุณุชุฎุฏู
"
|
| 1090 |
+
text += f"{status} **{name}**\n"
|
| 1091 |
+
text += f" ๐ {usage} ุทูุจ | โ {errors} ุฎุทุฃ | ๐ {last_str}\n"
|
| 1092 |
+
buttons = [
|
| 1093 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ู
ูุชุงุญ", callback_data="blogger_add_ai_key"),
|
| 1094 |
+
]
|
| 1095 |
+
all_keys = dict(db_keys)
|
| 1096 |
+
for kid, kdata in env_keys.items():
|
| 1097 |
+
all_keys[kid] = kdata
|
| 1098 |
+
if all_keys:
|
| 1099 |
+
if db_keys:
|
| 1100 |
+
buttons.append(InlineKeyboardButton("๐ ุญุฐู ู
ูุชุงุญ", callback_data="blogger_del_ai_key"))
|
| 1101 |
+
buttons.append(InlineKeyboardButton("๐ ุชุจุฏูู ุญุงูุฉ", callback_data="blogger_toggle_ai_key"))
|
| 1102 |
+
for kid, kdata in all_keys.items():
|
| 1103 |
+
name = kdata.get("name", kid)[:12]
|
| 1104 |
+
buttons.append(InlineKeyboardButton(f"๐งช ุงุฎุชุจุงุฑ {name}", callback_data=f"blogger_test_ai_key_{kid}"))
|
| 1105 |
+
rows = _grid_buttons(buttons, 2)
|
| 1106 |
+
rows.append(_nav_row(uid, "blogger_menu"))
|
| 1107 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
async def blogger_add_ai_key_prompt(client, callback):
|
| 1111 |
+
from bot_core import user_states
|
| 1112 |
+
uid = callback.from_user.id
|
| 1113 |
+
user_states.pop(uid, None)
|
| 1114 |
+
user_states[uid] = {"state": "blogger_add_ai_key"}
|
| 1115 |
+
await safe_edit(callback, "ุฃุฑุณู ู
ูุชุงุญ Gemini API:\n\nู
ุซุงู: AIzaSy...", InlineKeyboardMarkup([_nav_row(uid, "blogger_ai_keys")]))
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
async def blogger_del_ai_key_menu(client, callback):
|
| 1119 |
+
uid = callback.from_user.id
|
| 1120 |
+
pub = get_publisher()
|
| 1121 |
+
keys = pub.db.get_all_ai_keys()
|
| 1122 |
+
if not keys:
|
| 1123 |
+
await callback.answer("ูุง ุชูุฌุฏ ู
ูุงุชูุญ.", show_alert=True)
|
| 1124 |
+
return
|
| 1125 |
+
text = "๐ **ุญุฐู ู
ูุชุงุญ Gemini**\n\nุงุฎุชุฑ ุงูู
ูุชุงุญ ููุญุฐู:"
|
| 1126 |
+
buttons = []
|
| 1127 |
+
for kid, kdata in keys.items():
|
| 1128 |
+
name = kdata.get("name", kid)
|
| 1129 |
+
buttons.append([InlineKeyboardButton(f"๐ {name}", callback_data=f"blogger_del_ai_key_{kid}")])
|
| 1130 |
+
buttons.append(_nav_row(uid, "blogger_ai_keys"))
|
| 1131 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
async def blogger_confirm_del_ai_key(client, callback):
|
| 1135 |
+
key_id = callback.data.split("_")[-1]
|
| 1136 |
+
pub = get_publisher()
|
| 1137 |
+
pub.db.delete_ai_key(key_id)
|
| 1138 |
+
await callback.answer("โ
ุชู
ุงูุญุฐู.")
|
| 1139 |
+
await blogger_ai_keys_menu(client, callback)
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
async def blogger_toggle_ai_key_menu(client, callback):
|
| 1143 |
+
uid = callback.from_user.id
|
| 1144 |
+
pub = get_publisher()
|
| 1145 |
+
keys = pub.db.get_all_ai_keys()
|
| 1146 |
+
if not keys:
|
| 1147 |
+
await callback.answer("ูุง ุชูุฌุฏ ู
ูุงุชูุญ.", show_alert=True)
|
| 1148 |
+
return
|
| 1149 |
+
text = "๐ **ุชุจุฏูู ุญุงูุฉ ู
ูุชุงุญ Gemini**\n\nุงุฎุชุฑ ุงูู
ูุชุงุญ ูุชูุนูู/ุชุนุทูู:"
|
| 1150 |
+
buttons = []
|
| 1151 |
+
for kid, kdata in keys.items():
|
| 1152 |
+
name = kdata.get("name", kid)
|
| 1153 |
+
st = "โ
" if kdata.get("enabled", True) else "โ"
|
| 1154 |
+
buttons.append([InlineKeyboardButton(f"{st} {name}", callback_data=f"blogger_toggle_ai_key_{kid}")])
|
| 1155 |
+
buttons.append(_nav_row(uid, "blogger_ai_keys"))
|
| 1156 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
async def blogger_confirm_toggle_ai_key(client, callback):
|
| 1160 |
+
key_id = callback.data.split("_")[-1]
|
| 1161 |
+
pub = get_publisher()
|
| 1162 |
+
keys = pub.db.get_all_ai_keys()
|
| 1163 |
+
current = keys.get(key_id, {}).get("enabled", True) if key_id in keys else True
|
| 1164 |
+
pub.db.set_ai_key_enabled(key_id, not current)
|
| 1165 |
+
await callback.answer("โ
ุชู
ุงูุชุจุฏูู.")
|
| 1166 |
+
await blogger_toggle_ai_key_menu(client, callback)
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
async def handle_blogger_text_input(client, message):
|
| 1170 |
+
from bot_core import is_admin, user_states
|
| 1171 |
+
if not is_admin(message.from_user.id):
|
| 1172 |
+
return
|
| 1173 |
+
uid = message.from_user.id
|
| 1174 |
+
if uid not in user_states:
|
| 1175 |
+
return
|
| 1176 |
+
state = user_states[uid].get("state", "")
|
| 1177 |
+
if not state.startswith("blogger_"):
|
| 1178 |
+
return
|
| 1179 |
+
text = message.text.strip()
|
| 1180 |
+
pub = get_publisher()
|
| 1181 |
+
try:
|
| 1182 |
+
if state == "blogger_set_blog_id":
|
| 1183 |
+
pub.config.set("blog_id", text)
|
| 1184 |
+
await message.reply("โ
ุชู
ุญูุธ Blog ID.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_settings")]))
|
| 1185 |
+
user_states.pop(uid, None)
|
| 1186 |
+
elif state == "blogger_set_client_id":
|
| 1187 |
+
pub.config.set("client_id", text)
|
| 1188 |
+
await message.reply("โ
ุชู
ุญูุธ Client ID.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_settings")]))
|
| 1189 |
+
user_states.pop(uid, None)
|
| 1190 |
+
elif state == "blogger_set_client_secret":
|
| 1191 |
+
pub.config.set("client_secret", text)
|
| 1192 |
+
await message.reply("โ
ุชู
ุญูุธ Client Secret.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_settings")]))
|
| 1193 |
+
user_states.pop(uid, None)
|
| 1194 |
+
elif state == "blogger_set_refresh_token":
|
| 1195 |
+
pub.config.set("refresh_token", text)
|
| 1196 |
+
await message.reply("โ
ุชู
ุญูุธ Refresh Token.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_settings")]))
|
| 1197 |
+
user_states.pop(uid, None)
|
| 1198 |
+
elif state == "blogger_set_default_image":
|
| 1199 |
+
url = text.strip()
|
| 1200 |
+
pub.config.set("default_jobs_image", url)
|
| 1201 |
+
await message.reply("โ
ุชู
ุญูุธ ุตูุฑุฉ ุงููุธุงุฆู ุงูุงูุชุฑุงุถูุฉ." if url else "โ
ุชู
ุฅูุบุงุก ุงูุตูุฑุฉ ุงูุงูุชุฑุงุถูุฉ.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_set_default_image")]))
|
| 1202 |
+
user_states.pop(uid, None)
|
| 1203 |
+
elif state == "blogger_add_ai_key":
|
| 1204 |
+
name = text[:30]
|
| 1205 |
+
kid = str(int(time.time()))
|
| 1206 |
+
pub.db.add_ai_key(kid, {"name": name, "key": text})
|
| 1207 |
+
await message.reply(f"โ
ุชู
ุฅุถุงูุฉ ุงูู
ูุชุงุญ '{name}'.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_ai_keys")]))
|
| 1208 |
+
user_states.pop(uid, None)
|
| 1209 |
+
elif state == "blogger_add_channel_id":
|
| 1210 |
+
raw = text.strip()
|
| 1211 |
+
ch_id = raw
|
| 1212 |
+
ch_name = raw
|
| 1213 |
+
import re
|
| 1214 |
+
m = re.search(r'(?:https?://)?(?:t\.me/|telegram\.me/)(\w+)', raw)
|
| 1215 |
+
if m:
|
| 1216 |
+
ch_id = "@" + m.group(1)
|
| 1217 |
+
ch_name = ch_id
|
| 1218 |
+
elif raw.startswith("@"):
|
| 1219 |
+
ch_id = raw
|
| 1220 |
+
ch_name = raw
|
| 1221 |
+
try:
|
| 1222 |
+
from bot_core import user_client
|
| 1223 |
+
if user_client:
|
| 1224 |
+
chat = await user_client.get_chat(ch_id)
|
| 1225 |
+
ch_name = chat.title or chat.username or ch_id
|
| 1226 |
+
ch_id = str(chat.id)
|
| 1227 |
+
except Exception as e:
|
| 1228 |
+
logger.warning(f"Blogger: could not resolve channel name for {ch_id}: {e}")
|
| 1229 |
+
user_states[uid] = {"state": "blogger_add_ch_section", "ch_id": ch_id, "ch_name": ch_name}
|
| 1230 |
+
bk = InlineKeyboardMarkup([_nav_row(uid, "blogger_channels")])
|
| 1231 |
+
await message.reply(f"โ
ุชู
ุงูุชุนุฑู ุนูู ุงูููุงุฉ: {ch_name}\nุฃุฑุณู ุงุณู
ุงููุณู
ูู ุงูู
ุฏููุฉ:\nู
ุซุงู: ูุธุงุฆู, ุฃุฎุจุงุฑ, ู
ูุงูุตุงุช", reply_markup=bk)
|
| 1232 |
+
elif state == "blogger_add_ch_section":
|
| 1233 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1234 |
+
ch_name = user_states[uid].get("ch_name", ch_id)
|
| 1235 |
+
section = text.strip()
|
| 1236 |
+
if not section:
|
| 1237 |
+
await message.reply("โ ุงุณู
ุงููุณู
ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1238 |
+
return
|
| 1239 |
+
existing = pub.db.get_all_sections()
|
| 1240 |
+
found = any(sdata.get("name") == section for sdata in existing.values())
|
| 1241 |
+
if not found:
|
| 1242 |
+
sid = str(int(time.time()))
|
| 1243 |
+
pub.db.add_section(sid, {"name": section, "created_at": int(time.time())})
|
| 1244 |
+
logger.info(f"Blogger: auto-created section '{section}' (id={sid})")
|
| 1245 |
+
user_states[uid] = {"state": "blogger_add_ch_limit", "ch_id": ch_id, "ch_name": ch_name, "section": section}
|
| 1246 |
+
bk = InlineKeyboardMarkup([_nav_row(uid, "blogger_channels")])
|
| 1247 |
+
await message.reply(f"โ
ุงููุณู
: {section}\nุฃุฑุณู ุงูุญุฏ ุงูููู
ู ูุนุฏุฏ ุงูู
ูุดูุฑุงุช:\nู
ุซุงู: 30", reply_markup=bk)
|
| 1248 |
+
elif state == "blogger_section_rename":
|
| 1249 |
+
sid = user_states[uid].get("sid", "")
|
| 1250 |
+
name = text.strip()
|
| 1251 |
+
if not name:
|
| 1252 |
+
await message.reply("โ ุงูุงุณู
ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1253 |
+
return
|
| 1254 |
+
pub.db.add_section(sid, {"name": name, "updated_at": int(time.time())})
|
| 1255 |
+
await message.reply(f"โ
ุชู
ุชุญุฏูุซ ุงุณู
ุงููุณู
ุฅูู '{name}'.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_section_detail_{sid}")]))
|
| 1256 |
+
user_states.pop(uid, None)
|
| 1257 |
+
elif state == "blogger_ch_sec_new_input":
|
| 1258 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1259 |
+
name = text.strip()
|
| 1260 |
+
if not name:
|
| 1261 |
+
await message.reply("โ ุงุณู
ุงููุณู
ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1262 |
+
return
|
| 1263 |
+
sid = str(int(time.time()))
|
| 1264 |
+
pub.db.add_section(sid, {"name": name, "created_at": int(time.time())})
|
| 1265 |
+
ch = pub.db.get_channel(ch_id)
|
| 1266 |
+
if ch:
|
| 1267 |
+
ch["section"] = name
|
| 1268 |
+
pub.db.save_channel(ch_id, ch)
|
| 1269 |
+
await message.reply(f"โ
ุชู
ุฅุถุงูุฉ ุงููุณู
'{name}' ูุชุนูููู ููููุงุฉ.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 1270 |
+
user_states.pop(uid, None)
|
| 1271 |
+
elif state == "blogger_ch_section_input":
|
| 1272 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1273 |
+
section = text.strip()
|
| 1274 |
+
if not section:
|
| 1275 |
+
await message.reply("โ ุงุณู
ุงููุณู
ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1276 |
+
return
|
| 1277 |
+
ch = pub.db.get_channel(ch_id)
|
| 1278 |
+
if ch:
|
| 1279 |
+
ch["section"] = section
|
| 1280 |
+
pub.db.save_channel(ch_id, ch)
|
| 1281 |
+
await message.reply("โ
ุชู
ุชุญุฏูุซ ุงููุณู
.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 1282 |
+
user_states.pop(uid, None)
|
| 1283 |
+
elif state == "blogger_section_add_name":
|
| 1284 |
+
name = text.strip()
|
| 1285 |
+
if not name:
|
| 1286 |
+
await message.reply("โ ุงุณู
ุงููุณู
ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1287 |
+
return
|
| 1288 |
+
sid = str(int(time.time()))
|
| 1289 |
+
pub.db.add_section(sid, {"name": name, "created_at": int(time.time())})
|
| 1290 |
+
await message.reply(f"โ
ุชู
ุฅูุดุงุก ุงููุณู
'{name}'.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_sections_main")]))
|
| 1291 |
+
user_states.pop(uid, None)
|
| 1292 |
+
elif state == "blogger_ch_limit_input":
|
| 1293 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1294 |
+
try:
|
| 1295 |
+
limit = int(text.strip())
|
| 1296 |
+
except ValueError:
|
| 1297 |
+
await message.reply("โ ุงูุฑุฌุงุก ุฅุฑุณุงู ุฑูู
ุตุญูุญ.\nู
ุซุงู: 30")
|
| 1298 |
+
return
|
| 1299 |
+
ch = pub.db.get_channel(ch_id)
|
| 1300 |
+
if ch:
|
| 1301 |
+
ch["daily_limit"] = limit
|
| 1302 |
+
pub.db.save_channel(ch_id, ch)
|
| 1303 |
+
await message.reply(f"โ
ุชู
ุชุญุฏูุซ ุงูุญุฏ ุงูููู
ู ุฅูู {limit}.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 1304 |
+
user_states.pop(uid, None)
|
| 1305 |
+
elif state == "blogger_ch_hours_input":
|
| 1306 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1307 |
+
import re
|
| 1308 |
+
m = re.match(r'(\d+)\s*[-\s]\s*(\d+)', text.strip())
|
| 1309 |
+
if not m:
|
| 1310 |
+
await message.reply("โ ุงูุชูุณูู ุฎุทุฃ. ุฃุฑุณู ู
ุซู: `9-23`")
|
| 1311 |
+
return
|
| 1312 |
+
start_h, end_h = int(m.group(1)), int(m.group(2))
|
| 1313 |
+
if not (0 <= start_h < 24 and 0 <= end_h < 24):
|
| 1314 |
+
await message.reply("โ ุงูุณุงุนุงุช ูุฌุจ ุฃู ุชููู ุจูู 0 ู 23.")
|
| 1315 |
+
return
|
| 1316 |
+
ch = pub.db.get_channel(ch_id)
|
| 1317 |
+
if ch:
|
| 1318 |
+
ch["start_hour"] = start_h
|
| 1319 |
+
ch["end_hour"] = end_h
|
| 1320 |
+
pub.db.save_channel(ch_id, ch)
|
| 1321 |
+
await message.reply(f"โ
ุชู
ุชุญุฏูุซ ุณุงุนุงุช ุงููุดุฑ: {start_h}:00 - {end_h}:00.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_edit_ch_{ch_id}")]))
|
| 1322 |
+
user_states.pop(uid, None)
|
| 1323 |
+
elif state == "blogger_add_ch_limit":
|
| 1324 |
+
ch_id = user_states[uid].get("ch_id", "")
|
| 1325 |
+
ch_name = user_states[uid].get("ch_name", ch_id)
|
| 1326 |
+
section = user_states[uid].get("section", "ุนุงู
")
|
| 1327 |
+
try:
|
| 1328 |
+
daily_limit = int(text.strip())
|
| 1329 |
+
except ValueError:
|
| 1330 |
+
await message.reply("โ ุงูุฑุฌุงุก ุฅุฑุณุงู ุฑูู
ุตุญูุญ.\nู
ุซุงู: 30")
|
| 1331 |
+
return
|
| 1332 |
+
channel_data = {
|
| 1333 |
+
"channel_id": ch_id,
|
| 1334 |
+
"name": ch_name,
|
| 1335 |
+
"section": section,
|
| 1336 |
+
"daily_limit": daily_limit,
|
| 1337 |
+
"enabled": True,
|
| 1338 |
+
"start_hour": 9,
|
| 1339 |
+
"end_hour": 23,
|
| 1340 |
+
"last_message_id": 0,
|
| 1341 |
+
"added_at": int(time.time()),
|
| 1342 |
+
}
|
| 1343 |
+
pub.db.save_channel(ch_id, channel_data)
|
| 1344 |
+
bk = InlineKeyboardMarkup([_nav_row(uid, "blogger_channels")])
|
| 1345 |
+
await message.reply(f"โ
ุชู
ุฅุถุงูุฉ ุงูููุงุฉ ุจูุฌุงุญ:\n{ch_name} โ {section} ({daily_limit}/ููู
)", reply_markup=bk)
|
| 1346 |
+
user_states.pop(uid, None)
|
| 1347 |
+
elif state == "blogger_sec_add_label_input":
|
| 1348 |
+
sid = user_states[uid].get("sid", "")
|
| 1349 |
+
label = text.strip()
|
| 1350 |
+
if not label:
|
| 1351 |
+
await message.reply("โ ุงูุชุณู
ูุฉ ูุง ูู
ูู ุฃู ุชููู ูุงุฑุบุฉ.")
|
| 1352 |
+
return
|
| 1353 |
+
sections = pub.db.get_all_sections()
|
| 1354 |
+
sdata = sections.get(sid)
|
| 1355 |
+
if sdata:
|
| 1356 |
+
labels = sdata.get("labels", [])
|
| 1357 |
+
if label not in labels:
|
| 1358 |
+
labels.append(label)
|
| 1359 |
+
sdata["labels"] = labels
|
| 1360 |
+
pub.db.add_section(sid, sdata)
|
| 1361 |
+
await message.reply(f"โ
ุชู
ุฅุถุงูุฉ ุงูุชุณู
ูุฉ '{label}'.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_sec_labels_{sid}")]))
|
| 1362 |
+
user_states.pop(uid, None)
|
| 1363 |
+
elif state.startswith("blogger_article_edit_val_"):
|
| 1364 |
+
import re
|
| 1365 |
+
parts = state.split("_", 5)
|
| 1366 |
+
fingerprint = parts[-2]
|
| 1367 |
+
field = parts[-1]
|
| 1368 |
+
article = pub.db.get_article(fingerprint)
|
| 1369 |
+
if not article:
|
| 1370 |
+
await message.reply("โ ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.")
|
| 1371 |
+
user_states.pop(uid, None)
|
| 1372 |
+
return
|
| 1373 |
+
article[field] = text.strip()
|
| 1374 |
+
pub.db.save_article(fingerprint, article)
|
| 1375 |
+
field_names = {
|
| 1376 |
+
"title": "ุงูุนููุงู", "body": "ุงูู
ุญุชูู", "introduction": "ุงูู
ูุฏู
ุฉ",
|
| 1377 |
+
"conclusion": "ุงูุฎุงุชู
ุฉ", "summary": "ุงูู
ูุฎุต", "section": "ุงููุณู
",
|
| 1378 |
+
}
|
| 1379 |
+
far = field_names.get(field, field)
|
| 1380 |
+
await message.reply(f"โ
ุชู
ุชุญุฏูุซ {far}.", reply_markup=InlineKeyboardMarkup([_nav_row(uid, f"blogger_article_detail_{fingerprint}")]))
|
| 1381 |
+
user_states.pop(uid, None)
|
| 1382 |
+
elif state == "blogger_article_add_title":
|
| 1383 |
+
title = text.strip()
|
| 1384 |
+
if not title:
|
| 1385 |
+
await message.reply("โ ุงูุนููุงู ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1386 |
+
return
|
| 1387 |
+
user_states[uid] = {"state": "blogger_article_add_body", "article_data": {"title": title}}
|
| 1388 |
+
await message.reply("โ
ุชู
ุญูุธ ุงูุนููุงู.\nุฃุฑุณู ู
ุญุชูู ุงูู
ูุงู (ุงููุต ุงูุฃุณุงุณู):", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_articles")]))
|
| 1389 |
+
elif state == "blogger_article_add_body":
|
| 1390 |
+
body = text.strip()
|
| 1391 |
+
state_data = user_states.get(uid, {})
|
| 1392 |
+
article_data = state_data.get("article_data", {})
|
| 1393 |
+
article_data["body"] = body
|
| 1394 |
+
if not body:
|
| 1395 |
+
await message.reply("โ ุงูู
ุญุชูู ูุง ูู
ูู ุฃู ูููู ูุงุฑุบุงู.")
|
| 1396 |
+
return
|
| 1397 |
+
pub2 = get_publisher()
|
| 1398 |
+
sections = pub2.db.get_all_sections()
|
| 1399 |
+
user_states[uid] = {"state": "blogger_article_add_section_pick", "article_data": article_data}
|
| 1400 |
+
if sections:
|
| 1401 |
+
buttons = []
|
| 1402 |
+
for sid, sdata in sections.items():
|
| 1403 |
+
sname = sdata.get("name", sid)
|
| 1404 |
+
buttons.append(InlineKeyboardButton(sname, callback_data=f"blogger_article_add_section_{sname}"))
|
| 1405 |
+
rows = _grid_buttons(buttons, 2)
|
| 1406 |
+
rows.append(_nav_row(uid, "blogger_articles"))
|
| 1407 |
+
await message.reply("ุงุฎุชุฑ ุงููุณู
:", reply_markup=InlineKeyboardMarkup(rows))
|
| 1408 |
+
else:
|
| 1409 |
+
article_data["section"] = "ุนุงู
"
|
| 1410 |
+
user_states[uid] = {"state": "blogger_article_add_confirm", "article_data": article_data}
|
| 1411 |
+
text = (
|
| 1412 |
+
"โ **ุชุฃููุฏ ุงูู
ูุงู ุงูุฌุฏูุฏ**\n\n"
|
| 1413 |
+
f"ุงูุนููุงู: {article_data.get('title', 'โ')}\n"
|
| 1414 |
+
f"ุงููุณู
: ุนุงู
\n"
|
| 1415 |
+
f"ุทูู ุงูู
ุญุชูู: {len(body)} ุญุฑู\n\n"
|
| 1416 |
+
"ูู ุชุฑูุฏ ุฅุถุงูุฉ ูุฐุง ุงูู
ูุงู ุฅูู Queueุ"
|
| 1417 |
+
)
|
| 1418 |
+
btns = [
|
| 1419 |
+
InlineKeyboardButton("โ
ุฅุถุงูุฉ ุฅูู Queue", callback_data="blogger_article_add_finish"),
|
| 1420 |
+
InlineKeyboardButton("โ ุฅูุบุงุก", callback_data="blogger_articles"),
|
| 1421 |
+
]
|
| 1422 |
+
await message.reply(text, reply_markup=InlineKeyboardMarkup([btns]))
|
| 1423 |
+
else:
|
| 1424 |
+
return
|
| 1425 |
+
except Exception as e:
|
| 1426 |
+
logger.exception(f"Blogger input error: {e}")
|
| 1427 |
+
await message.reply(f"โ ูุดู: {e}", reply_markup=InlineKeyboardMarkup([_nav_row(uid, "blogger_menu")]))
|
| 1428 |
+
user_states.pop(uid, None)
|
| 1429 |
+
|
| 1430 |
+
|
| 1431 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 1432 |
+
# Article Management UI
|
| 1433 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 1434 |
+
|
| 1435 |
+
STATUS_EMOJI = {
|
| 1436 |
+
"queued": "โณ", "published": "โ
", "draft": "๐",
|
| 1437 |
+
"failed_permanent": "โ", "gemini_pending": "๐ค",
|
| 1438 |
+
"processing": "โ๏ธ", "discarded": "๐", "processed": "๐",
|
| 1439 |
+
}
|
| 1440 |
+
STATUS_AR = {
|
| 1441 |
+
"all": "ุงููู", "queued": "ูู Queue", "published": "ู
ูุดูุฑ",
|
| 1442 |
+
"draft": "ู
ุณูุฏุฉ", "processed": "ู
ุนุงูุฌ", "failed_permanent": "ูุงุดู",
|
| 1443 |
+
"gemini_pending": "ุจุฅูุชุธุงุฑ AI", "discarded": "ู
ูู
ู",
|
| 1444 |
+
}
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def _article_summary(a: dict) -> str:
|
| 1448 |
+
title = (a.get("title") or "(ุจุฏูู ุนููุงู)")[:45]
|
| 1449 |
+
status = a.get("status", "unknown")
|
| 1450 |
+
emoji = STATUS_EMOJI.get(status, "โ")
|
| 1451 |
+
sec = a.get("section", "")
|
| 1452 |
+
sec_tag = f" [{sec}]" if sec else ""
|
| 1453 |
+
return f"{emoji} {title}{sec_tag}"
|
| 1454 |
+
|
| 1455 |
+
|
| 1456 |
+
async def blogger_articles_menu(client, callback, page: int = 0):
|
| 1457 |
+
uid = callback.from_user.id
|
| 1458 |
+
_push_nav(uid, "blogger_articles")
|
| 1459 |
+
pub = get_publisher()
|
| 1460 |
+
filter_status = callback.data.split("_")[-1] if callback.data.startswith("blogger_articles_filter_") else "all"
|
| 1461 |
+
all_articles = pub.db.get_all_articles()
|
| 1462 |
+
if filter_status != "all":
|
| 1463 |
+
all_articles = [a for a in all_articles if a.get("status") == filter_status]
|
| 1464 |
+
all_articles.sort(key=lambda a: a.get("created_at", 0), reverse=True)
|
| 1465 |
+
per_page = 8
|
| 1466 |
+
total = len(all_articles)
|
| 1467 |
+
max_page = max(0, (total - 1) // per_page) if total else 0
|
| 1468 |
+
page = max(0, min(page, max_page))
|
| 1469 |
+
start, end = page * per_page, (page + 1) * per_page
|
| 1470 |
+
page_articles = all_articles[start:end]
|
| 1471 |
+
|
| 1472 |
+
counts = {}
|
| 1473 |
+
for a in pub.db.get_all_articles():
|
| 1474 |
+
s = a.get("status", "unknown")
|
| 1475 |
+
counts[s] = counts.get(s, 0) + 1
|
| 1476 |
+
counts["all"] = sum(counts.values())
|
| 1477 |
+
|
| 1478 |
+
text_parts = [f"๐ **ุฅุฏุงุฑุฉ ุงูู
ูุงูุงุช**\n"]
|
| 1479 |
+
filter_labels = []
|
| 1480 |
+
for key in ("all", "processed", "queued", "published", "draft", "gemini_pending", "failed_permanent", "discarded"):
|
| 1481 |
+
c = counts.get(key, 0)
|
| 1482 |
+
if c or key == "all":
|
| 1483 |
+
ar = STATUS_AR.get(key, key)
|
| 1484 |
+
marker = "โซ๏ธ" if key != filter_status else "๐น"
|
| 1485 |
+
filter_labels.append(f"{marker} {ar} ({c})")
|
| 1486 |
+
|
| 1487 |
+
text_parts.append(" | ".join(filter_labels))
|
| 1488 |
+
text_parts.append(f"\n๐ ุงูุตูุญุฉ {page + 1}/{max_page + 1} โ {total} ู
ูุงู")
|
| 1489 |
+
|
| 1490 |
+
if not page_articles:
|
| 1491 |
+
text_parts.append("\nูุง ุชูุฌุฏ ู
ูุงูุงุช.")
|
| 1492 |
+
else:
|
| 1493 |
+
for i, a in enumerate(page_articles, 1):
|
| 1494 |
+
fp = a.get("fingerprint", "")
|
| 1495 |
+
summary = _article_summary(a)
|
| 1496 |
+
text_parts.append(f"\n{i}. {summary}")
|
| 1497 |
+
|
| 1498 |
+
filter_row = []
|
| 1499 |
+
for key in ("all", "processed", "queued", "published"):
|
| 1500 |
+
ar = STATUS_AR.get(key, key)
|
| 1501 |
+
selected = "๐น" if key == filter_status else "โซ๏ธ"
|
| 1502 |
+
filter_row.append(InlineKeyboardButton(f"{selected}{ar}", callback_data=f"blogger_articles_filter_{key}"))
|
| 1503 |
+
|
| 1504 |
+
nav_row_btns = []
|
| 1505 |
+
if page > 0:
|
| 1506 |
+
nav_row_btns.append(InlineKeyboardButton("โฌ
๏ธ ุงูุณุงุจู", callback_data=f"blogger_articles_page_{page - 1}_{filter_status}"))
|
| 1507 |
+
if page < max_page:
|
| 1508 |
+
nav_row_btns.append(InlineKeyboardButton("ุงูุชุงูู โก๏ธ", callback_data=f"blogger_articles_page_{page + 1}_{filter_status}"))
|
| 1509 |
+
|
| 1510 |
+
article_buttons = []
|
| 1511 |
+
for a in page_articles:
|
| 1512 |
+
fp = a.get("fingerprint", "")
|
| 1513 |
+
title = (a.get("title") or "(ุจุฏูู ุนููุงู)")[:35]
|
| 1514 |
+
article_buttons.append(InlineKeyboardButton(title, callback_data=f"blogger_article_detail_{fp}"))
|
| 1515 |
+
|
| 1516 |
+
rows = _grid_buttons(filter_row, 4)
|
| 1517 |
+
if article_buttons:
|
| 1518 |
+
rows.extend([[b] for b in article_buttons])
|
| 1519 |
+
if nav_row_btns:
|
| 1520 |
+
rows.append(nav_row_btns)
|
| 1521 |
+
rows.append([
|
| 1522 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ู
ูุงู", callback_data="blogger_article_add"),
|
| 1523 |
+
InlineKeyboardButton("๐ ุชุญุฏูุซ", callback_data=f"blogger_articles_refresh_{filter_status}"),
|
| 1524 |
+
])
|
| 1525 |
+
rows.append(_nav_row(uid, "blogger_menu"))
|
| 1526 |
+
await safe_edit(callback, "\n".join(text_parts), InlineKeyboardMarkup(rows))
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
async def blogger_articles_refresh(client, callback):
|
| 1530 |
+
await blogger_articles_menu(client, callback)
|
| 1531 |
+
|
| 1532 |
+
|
| 1533 |
+
async def blogger_articles_page(client, callback):
|
| 1534 |
+
import re
|
| 1535 |
+
parts = callback.data.split("_")
|
| 1536 |
+
page = int(parts[-2])
|
| 1537 |
+
filter_status = parts[-1] if len(parts) > 3 else "all"
|
| 1538 |
+
uid = callback.from_user.id
|
| 1539 |
+
_push_nav(uid, "blogger_articles")
|
| 1540 |
+
pub = get_publisher()
|
| 1541 |
+
all_articles = pub.db.get_all_articles()
|
| 1542 |
+
if filter_status != "all":
|
| 1543 |
+
all_articles = [a for a in all_articles if a.get("status") == filter_status]
|
| 1544 |
+
all_articles.sort(key=lambda a: a.get("created_at", 0), reverse=True)
|
| 1545 |
+
per_page = 8
|
| 1546 |
+
total = len(all_articles)
|
| 1547 |
+
max_page = max(0, (total - 1) // per_page) if total else 0
|
| 1548 |
+
page = max(0, min(page, max_page))
|
| 1549 |
+
start, end = page * per_page, (page + 1) * per_page
|
| 1550 |
+
page_articles = all_articles[start:end]
|
| 1551 |
+
|
| 1552 |
+
counts = {}
|
| 1553 |
+
for a in pub.db.get_all_articles():
|
| 1554 |
+
s = a.get("status", "unknown")
|
| 1555 |
+
counts[s] = counts.get(s, 0) + 1
|
| 1556 |
+
counts["all"] = sum(counts.values())
|
| 1557 |
+
|
| 1558 |
+
text_parts = [f"๐ **ุฅุฏุงุฑุฉ ุงูู
ูุงูุงุช**\n"]
|
| 1559 |
+
filter_labels = []
|
| 1560 |
+
for key in ("all", "processed", "queued", "published", "draft", "gemini_pending", "failed_permanent", "discarded"):
|
| 1561 |
+
c = counts.get(key, 0)
|
| 1562 |
+
if c or key == "all":
|
| 1563 |
+
ar = STATUS_AR.get(key, key)
|
| 1564 |
+
marker = "โซ๏ธ" if key != filter_status else "๐น"
|
| 1565 |
+
filter_labels.append(f"{marker} {ar} ({c})")
|
| 1566 |
+
text_parts.append(" | ".join(filter_labels))
|
| 1567 |
+
text_parts.append(f"\n๐ ุงูุตูุญุฉ {page + 1}/{max_page + 1} โ {total} ู
ูุงู")
|
| 1568 |
+
if not page_articles:
|
| 1569 |
+
text_parts.append("\nูุง ุชูุฌุฏ ู
ูุงูุงุช.")
|
| 1570 |
+
else:
|
| 1571 |
+
for i, a in enumerate(page_articles, 1):
|
| 1572 |
+
summary = _article_summary(a)
|
| 1573 |
+
text_parts.append(f"\n{i}. {summary}")
|
| 1574 |
+
|
| 1575 |
+
filter_row = []
|
| 1576 |
+
for key in ("all", "processed", "queued", "published"):
|
| 1577 |
+
ar = STATUS_AR.get(key, key)
|
| 1578 |
+
selected = "๐น" if key == filter_status else "โซ๏ธ"
|
| 1579 |
+
filter_row.append(InlineKeyboardButton(f"{selected}{ar}", callback_data=f"blogger_articles_filter_{key}"))
|
| 1580 |
+
|
| 1581 |
+
nav_row_btns = []
|
| 1582 |
+
if page > 0:
|
| 1583 |
+
nav_row_btns.append(InlineKeyboardButton("โฌ
๏ธ ุงูุณุงุจู", callback_data=f"blogger_articles_page_{page - 1}_{filter_status}"))
|
| 1584 |
+
if page < max_page:
|
| 1585 |
+
nav_row_btns.append(InlineKeyboardButton("ุงูุชุงูู โก๏ธ", callback_data=f"blogger_articles_page_{page + 1}_{filter_status}"))
|
| 1586 |
+
|
| 1587 |
+
article_buttons = []
|
| 1588 |
+
for a in page_articles:
|
| 1589 |
+
fp = a.get("fingerprint", "")
|
| 1590 |
+
title = (a.get("title") or "(ุจุฏูู ุนููุงู)")[:35]
|
| 1591 |
+
article_buttons.append(InlineKeyboardButton(title, callback_data=f"blogger_article_detail_{fp}"))
|
| 1592 |
+
|
| 1593 |
+
rows = _grid_buttons(filter_row, 4)
|
| 1594 |
+
if article_buttons:
|
| 1595 |
+
rows.extend([[b] for b in article_buttons])
|
| 1596 |
+
if nav_row_btns:
|
| 1597 |
+
rows.append(nav_row_btns)
|
| 1598 |
+
rows.append([
|
| 1599 |
+
InlineKeyboardButton("โ ุฅุถุงูุฉ ู
ูุงู", callback_data="blogger_article_add"),
|
| 1600 |
+
InlineKeyboardButton("๐ ุชุญุฏูุซ", callback_data=f"blogger_articles_refresh_{filter_status}"),
|
| 1601 |
+
])
|
| 1602 |
+
rows.append(_nav_row(uid, "blogger_menu"))
|
| 1603 |
+
await safe_edit(callback, "\n".join(text_parts), InlineKeyboardMarkup(rows))
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
async def blogger_article_detail(client, callback):
|
| 1607 |
+
fingerprint = callback.data[len("blogger_article_detail_"):]
|
| 1608 |
+
uid = callback.from_user.id
|
| 1609 |
+
pub = get_publisher()
|
| 1610 |
+
article = pub.db.get_article(fingerprint)
|
| 1611 |
+
if not article:
|
| 1612 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1613 |
+
return
|
| 1614 |
+
title = article.get("title", "(ุจุฏูู ุนููุงู)")
|
| 1615 |
+
status = article.get("status", "unknown")
|
| 1616 |
+
emoji = STATUS_EMOJI.get(status, "โ")
|
| 1617 |
+
status_ar = STATUS_AR.get(status, status)
|
| 1618 |
+
section = article.get("section", "โ")
|
| 1619 |
+
created = article.get("created_at", 0)
|
| 1620 |
+
if created:
|
| 1621 |
+
created_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(created))
|
| 1622 |
+
else:
|
| 1623 |
+
created_str = "โ"
|
| 1624 |
+
processed_at = article.get("processed_at", 0)
|
| 1625 |
+
processed_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(processed_at)) if processed_at else "โ"
|
| 1626 |
+
published_at = article.get("published_at", 0)
|
| 1627 |
+
published_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(published_at)) if published_at else "โ"
|
| 1628 |
+
error = article.get("error", "")
|
| 1629 |
+
body_len = len(article.get("body", "") or "")
|
| 1630 |
+
|
| 1631 |
+
text = (
|
| 1632 |
+
f"๐ **{title}**\n\n"
|
| 1633 |
+
f"ุงูุญุงูุฉ: {emoji} {status_ar}\n"
|
| 1634 |
+
f"ุงููุณู
: {section}\n"
|
| 1635 |
+
f"ุชุงุฑูุฎ ุงูุฅูุดุงุก: {created_str}\n"
|
| 1636 |
+
)
|
| 1637 |
+
if status in ("processed", "queued", "published", "draft"):
|
| 1638 |
+
text += f"ุชุงุฑูุฎ ุงูู
ุนุงูุฌุฉ: {processed_str}\n"
|
| 1639 |
+
if status in ("published", "draft"):
|
| 1640 |
+
text += f"ุชุงุฑูุฎ ุงููุดุฑ: {published_str}\n"
|
| 1641 |
+
text += f"ุทูู ุงูู
ุญุชูู: {body_len} ุญุฑู\n"
|
| 1642 |
+
if error:
|
| 1643 |
+
text += f"\nโ ๏ธ ุฎุทุฃ: {error[:200]}"
|
| 1644 |
+
|
| 1645 |
+
buttons = []
|
| 1646 |
+
if status in ("processed", "queued"):
|
| 1647 |
+
buttons.append(InlineKeyboardButton("๐ค ูุดุฑ ุงูุขู", callback_data=f"blogger_publish_now_{fingerprint}"))
|
| 1648 |
+
buttons.append(InlineKeyboardButton("๐ ู
ุณูุฏุฉ", callback_data=f"blogger_publish_draft_{fingerprint}"))
|
| 1649 |
+
if status == "queued":
|
| 1650 |
+
buttons.append(InlineKeyboardButton("โฌ๏ธ ุฑูุน", callback_data=f"blogger_article_move_up_{fingerprint}"))
|
| 1651 |
+
buttons.append(InlineKeyboardButton("โฌ๏ธ ุฎูุถ", callback_data=f"blogger_article_move_down_{fingerprint}"))
|
| 1652 |
+
buttons.append(InlineKeyboardButton("๐ ู
ุนุงููุฉ", callback_data=f"blogger_article_preview_{fingerprint}"))
|
| 1653 |
+
buttons.append(InlineKeyboardButton("โ๏ธ ุชุนุฏูู", callback_data=f"blogger_article_edit_{fingerprint}"))
|
| 1654 |
+
buttons.append(InlineKeyboardButton("๐ ุญุฐู", callback_data=f"blogger_article_delete_{fingerprint}"))
|
| 1655 |
+
buttons.append(InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="blogger_articles"))
|
| 1656 |
+
|
| 1657 |
+
rows = _grid_buttons(buttons, 2)
|
| 1658 |
+
rows.append(_nav_row(uid, "blogger_articles"))
|
| 1659 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
async def blogger_article_preview(client, callback):
|
| 1663 |
+
fingerprint = callback.data[len("blogger_article_preview_"):]
|
| 1664 |
+
uid = callback.from_user.id
|
| 1665 |
+
pub = get_publisher()
|
| 1666 |
+
article = pub.db.get_article(fingerprint)
|
| 1667 |
+
if not article:
|
| 1668 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1669 |
+
return
|
| 1670 |
+
html = pub.processor.make_article_html(article)
|
| 1671 |
+
telegram_text = pub.processor.html_to_telegram(html)
|
| 1672 |
+
max_len = 4000
|
| 1673 |
+
if len(telegram_text) > max_len:
|
| 1674 |
+
telegram_text = telegram_text[:max_len] + "\n\n...(ู
ุฎุชุตุฑ)"
|
| 1675 |
+
await safe_edit(callback, f"๐ **ู
ุนุงููุฉ ุงูู
ูุงู**\n\n{telegram_text}", InlineKeyboardMarkup([_nav_row(uid, f"blogger_article_detail_{fingerprint}")]))
|
| 1676 |
+
|
| 1677 |
+
|
| 1678 |
+
async def blogger_article_delete(client, callback):
|
| 1679 |
+
fingerprint = callback.data[len("blogger_article_delete_"):]
|
| 1680 |
+
uid = callback.from_user.id
|
| 1681 |
+
pub = get_publisher()
|
| 1682 |
+
article = pub.db.get_article(fingerprint)
|
| 1683 |
+
if not article:
|
| 1684 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1685 |
+
return
|
| 1686 |
+
title = article.get("title", "(ุจุฏูู ุนููุงู)")[:40]
|
| 1687 |
+
text = f"๐ **ุชุฃููุฏ ุญุฐู ุงูู
ูุงู**\n\nูู ุฃูุช ู
ุชุฃูุฏ ู
ู ุญุฐู:\nใ{title}ใ\n\nุณูุชู
ุญุฐู ุงูู
ูุงู ุจุดูู ุฏุงุฆู
."
|
| 1688 |
+
buttons = [
|
| 1689 |
+
InlineKeyboardButton("โ
ูุนู
ุ ุงุญุฐู", callback_data=f"blogger_article_delete_confirm_{fingerprint}"),
|
| 1690 |
+
InlineKeyboardButton("โ ุฅูุบุงุก", callback_data=f"blogger_article_detail_{fingerprint}"),
|
| 1691 |
+
]
|
| 1692 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([buttons]))
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
async def blogger_article_delete_confirm(client, callback):
|
| 1696 |
+
fingerprint = callback.data[len("blogger_article_delete_confirm_"):]
|
| 1697 |
+
uid = callback.from_user.id
|
| 1698 |
+
pub = get_publisher()
|
| 1699 |
+
article = pub.db.get_article(fingerprint)
|
| 1700 |
+
if not article:
|
| 1701 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1702 |
+
return
|
| 1703 |
+
pub.db.delete_article(fingerprint)
|
| 1704 |
+
pub.db.remove_pending_by_fingerprint(fingerprint)
|
| 1705 |
+
pub.db.mark_published(fingerprint)
|
| 1706 |
+
await callback.answer("โ
ุชู
ุญุฐู ุงูู
ูุงู.", show_alert=True)
|
| 1707 |
+
await blogger_articles_menu(client, callback)
|
| 1708 |
+
|
| 1709 |
+
|
| 1710 |
+
async def blogger_article_edit(client, callback):
|
| 1711 |
+
fingerprint = callback.data[len("blogger_article_edit_"):]
|
| 1712 |
+
uid = callback.from_user.id
|
| 1713 |
+
pub = get_publisher()
|
| 1714 |
+
article = pub.db.get_article(fingerprint)
|
| 1715 |
+
if not article:
|
| 1716 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1717 |
+
return
|
| 1718 |
+
fields = {
|
| 1719 |
+
"title": "ุงูุนููุงู",
|
| 1720 |
+
"body": "ุงูู
ุญุชูู",
|
| 1721 |
+
"introduction": "ุงูู
ูุฏู
ุฉ",
|
| 1722 |
+
"conclusion": "ุงูุฎุงุชู
ุฉ",
|
| 1723 |
+
"summary": "ุงูู
ูุฎุต",
|
| 1724 |
+
"section": "ุงููุณู
",
|
| 1725 |
+
}
|
| 1726 |
+
title = article.get("title", "(ุจุฏูู ุนููุงู)")[:30]
|
| 1727 |
+
text = f"โ๏ธ **ุชุนุฏูู ุงูู
ูุงู**\nใ{title}ใ\n\nุงุฎุชุฑ ุงูุญูู ุงูุฐู ุชุฑูุฏ ุชุนุฏููู:"
|
| 1728 |
+
buttons = []
|
| 1729 |
+
for fkey, far in fields.items():
|
| 1730 |
+
current = article.get(fkey, "")
|
| 1731 |
+
preview = str(current)[:25] if current else "ูุงุฑุบ"
|
| 1732 |
+
buttons.append(InlineKeyboardButton(f"{far}: {preview}", callback_data=f"blogger_article_edit_field_{fingerprint}_{fkey}"))
|
| 1733 |
+
rows = _grid_buttons(buttons, 1)
|
| 1734 |
+
rows.append(_nav_row(uid, f"blogger_article_detail_{fingerprint}"))
|
| 1735 |
+
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 1736 |
+
|
| 1737 |
+
|
| 1738 |
+
async def blogger_article_edit_field(client, callback):
|
| 1739 |
+
import re
|
| 1740 |
+
parts = callback.data.split("_", 5)
|
| 1741 |
+
fingerprint = parts[-2]
|
| 1742 |
+
field = parts[-1]
|
| 1743 |
+
uid = callback.from_user.id
|
| 1744 |
+
pub = get_publisher()
|
| 1745 |
+
article = pub.db.get_article(fingerprint)
|
| 1746 |
+
if not article:
|
| 1747 |
+
await callback.answer("ุงูู
ูุงู ุบูุฑ ู
ูุฌูุฏ.", show_alert=True)
|
| 1748 |
+
return
|
| 1749 |
+
|
| 1750 |
+
field_names = {
|
| 1751 |
+
"title": "ุงูุนููุงู", "body": "ุงูู
ุญุชูู", "introduction": "ุงูู
ูุฏู
ุฉ",
|
| 1752 |
+
"conclusion": "ุงูุฎุงุชู
ุฉ", "summary": "ุงูู
ูุฎุต", "section": "ุงููุณู
",
|
| 1753 |
+
}
|
| 1754 |
+
far = field_names.get(field, field)
|
| 1755 |
+
current = article.get(field, "")
|
| 1756 |
+
current_preview = str(current)[:100] if current else "(ูุงุฑุบ)"
|
| 1757 |
+
|
| 1758 |
+
from bot_core import user_states
|
| 1759 |
+
user_states[uid] = {"state": f"blogger_article_edit_val_{fingerprint}_{field}"}
|
| 1760 |
+
|
| 1761 |
+
text = f"โ๏ธ **ุชุนุฏูู {far}**\n\nุงูููู
ุฉ ุงูุญุงููุฉ:\n`{current_preview}`\n\nุฃุฑุณู ุงูููู
ุฉ ุงูุฌุฏูุฏุฉ:"
|
| 1762 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([_nav_row(uid, f"blogger_article_edit_{fingerprint}")]))
|
| 1763 |
+
|
| 1764 |
+
|
| 1765 |
+
async def blogger_article_move_up(client, callback):
|
| 1766 |
+
fingerprint = callback.data[len("blogger_article_move_up_"):]
|
| 1767 |
+
uid = callback.from_user.id
|
| 1768 |
+
pub = get_publisher()
|
| 1769 |
+
await _reorder_article(pub, fingerprint, -1)
|
| 1770 |
+
await callback.answer("โ
ุชู
ุฑูุน ุงูู
ูุงู.", show_alert=True)
|
| 1771 |
+
await blogger_article_detail(client, callback)
|
| 1772 |
+
|
| 1773 |
+
|
| 1774 |
+
async def blogger_article_move_down(client, callback):
|
| 1775 |
+
fingerprint = callback.data[len("blogger_article_move_down_"):]
|
| 1776 |
+
uid = callback.from_user.id
|
| 1777 |
+
pub = get_publisher()
|
| 1778 |
+
await _reorder_article(pub, fingerprint, 1)
|
| 1779 |
+
await callback.answer("โ
ุชู
ุฎูุถ ุงูู
ูุงู.", show_alert=True)
|
| 1780 |
+
await blogger_article_detail(client, callback)
|
| 1781 |
+
|
| 1782 |
+
|
| 1783 |
+
async def _reorder_article(pub, fingerprint: str, direction: int):
|
| 1784 |
+
queue = [a for a in pub.db.get_articles_by_status("queued")
|
| 1785 |
+
if a.get("fingerprint") and a.get("fingerprint") != fingerprint]
|
| 1786 |
+
article = pub.db.get_article(fingerprint)
|
| 1787 |
+
if not article:
|
| 1788 |
+
return
|
| 1789 |
+
idx = next((i for i, a in enumerate(queue) if a.get("fingerprint") == fingerprint), -1)
|
| 1790 |
+
if idx == -1:
|
| 1791 |
+
if direction == -1:
|
| 1792 |
+
queue.insert(0, article)
|
| 1793 |
+
else:
|
| 1794 |
+
queue.append(article)
|
| 1795 |
+
else:
|
| 1796 |
+
target = idx + direction
|
| 1797 |
+
if 0 <= target < len(queue):
|
| 1798 |
+
queue.pop(idx)
|
| 1799 |
+
queue.insert(target, article)
|
| 1800 |
+
elif target < 0:
|
| 1801 |
+
queue.insert(0, queue.pop(idx))
|
| 1802 |
+
else:
|
| 1803 |
+
queue.append(queue.pop(idx))
|
| 1804 |
+
for a in queue:
|
| 1805 |
+
a["status"] = "queued"
|
| 1806 |
+
pub.db.save_article(a.get("fingerprint", ""), a)
|
| 1807 |
+
pub.scheduler._queue = queue
|
| 1808 |
+
|
| 1809 |
+
|
| 1810 |
+
async def blogger_article_add(client, callback):
|
| 1811 |
+
uid = callback.from_user.id
|
| 1812 |
+
from bot_core import user_states
|
| 1813 |
+
user_states[uid] = {"state": "blogger_article_add_title", "article_data": {}}
|
| 1814 |
+
text = "โ **ุฅุถุงูุฉ ู
ูุงู ุฌุฏูุฏ**\n\nุฃุฑุณู ุนููุงู ุงูู
ูุงู:"
|
| 1815 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([_nav_row(uid, "blogger_articles")]))
|
| 1816 |
+
|
| 1817 |
+
|
| 1818 |
+
async def blogger_article_add_section(client, callback):
|
| 1819 |
+
parts = callback.data.split("_", 1)
|
| 1820 |
+
section = parts[-1]
|
| 1821 |
+
uid = callback.from_user.id
|
| 1822 |
+
from bot_core import user_states
|
| 1823 |
+
state_data = user_states.get(uid, {})
|
| 1824 |
+
state_data["article_data"] = state_data.get("article_data", {})
|
| 1825 |
+
state_data["article_data"]["section"] = section
|
| 1826 |
+
state_data["state"] = "blogger_article_add_confirm"
|
| 1827 |
+
user_states[uid] = state_data
|
| 1828 |
+
pub = get_publisher()
|
| 1829 |
+
ad = state_data["article_data"]
|
| 1830 |
+
text = (
|
| 1831 |
+
"โ **ุชุฃููุฏ ุงูู
ูุงู ุงูุฌุฏูุฏ**\n\n"
|
| 1832 |
+
f"ุงูุนููุงู: {ad.get('title', 'โ')}\n"
|
| 1833 |
+
f"ุงููุณู
: {ad.get('section', 'โ')}\n"
|
| 1834 |
+
f"ุทูู ุงูู
ุญุชูู: {len(ad.get('body', ''))} ุญุฑู\n\n"
|
| 1835 |
+
"ูู ุชุฑูุฏ ุฅุถุงูุฉ ูุฐุง ุงูู
ูุงู ุฅูู Queueุ"
|
| 1836 |
+
)
|
| 1837 |
+
buttons = [
|
| 1838 |
+
InlineKeyboardButton("โ
ุฅุถุงูุฉ ุฅูู Queue", callback_data="blogger_article_add_finish"),
|
| 1839 |
+
InlineKeyboardButton("โ ุฅูุบุงุก", callback_data="blogger_articles"),
|
| 1840 |
+
]
|
| 1841 |
+
await safe_edit(callback, text, InlineKeyboardMarkup([buttons]))
|
| 1842 |
+
|
| 1843 |
+
|
| 1844 |
+
async def blogger_article_add_finish(client, callback):
|
| 1845 |
+
uid = callback.from_user.id
|
| 1846 |
+
from bot_core import user_states
|
| 1847 |
+
state_data = user_states.get(uid, {})
|
| 1848 |
+
article_data = state_data.get("article_data", {})
|
| 1849 |
+
if not article_data.get("title"):
|
| 1850 |
+
await callback.answer("โ ุงูุนููุงู ู
ุทููุจ.", show_alert=True)
|
| 1851 |
+
return
|
| 1852 |
+
pub = get_publisher()
|
| 1853 |
+
import hashlib, time
|
| 1854 |
+
raw = article_data.get("title", "") + article_data.get("body", "")
|
| 1855 |
+
fingerprint = hashlib.md5(raw.encode("utf-8")).hexdigest()
|
| 1856 |
+
existing = pub.db.get_article(fingerprint)
|
| 1857 |
+
if existing:
|
| 1858 |
+
await callback.answer("โ ุงูู
ูุงู ู
ูุฌูุฏ ู
ุณุจูุงู.", show_alert=True)
|
| 1859 |
+
return
|
| 1860 |
+
article = {
|
| 1861 |
+
"fingerprint": fingerprint,
|
| 1862 |
+
"title": article_data.get("title", ""),
|
| 1863 |
+
"body": article_data.get("body", ""),
|
| 1864 |
+
"section": article_data.get("section", "ุนุงู
"),
|
| 1865 |
+
"status": "queued",
|
| 1866 |
+
"created_at": int(time.time()),
|
| 1867 |
+
"source_url": "",
|
| 1868 |
+
"media": [],
|
| 1869 |
+
}
|
| 1870 |
+
pub.db.save_article(fingerprint, article)
|
| 1871 |
+
pub.scheduler.add_to_queue(article)
|
| 1872 |
+
user_states.pop(uid, None)
|
| 1873 |
+
await callback.answer("โ
ุชู
ุฅุถุงูุฉ ุงูู
ูุงู ุฅูู Queue!", show_alert=True)
|
| 1874 |
+
await blogger_articles_menu(client, callback)
|
| 1875 |
+
user_states.pop(uid, None)
|
| 1876 |
+
|
| 1877 |
+
|
| 1878 |
+
BLOGGER_CALLBACKS = {
|
| 1879 |
+
"blogger_menu": blogger_main_menu,
|
| 1880 |
+
"blogger_settings": blogger_settings_menu,
|
| 1881 |
+
"blogger_channels": blogger_channels_menu,
|
| 1882 |
+
"blogger_ai_keys": blogger_ai_keys_menu,
|
| 1883 |
+
"blogger_stats": blogger_stats_menu,
|
| 1884 |
+
"blogger_logs": blogger_logs_menu,
|
| 1885 |
+
"blogger_test": blogger_test_handler,
|
| 1886 |
+
"blogger_toggle": blogger_toggle_handler,
|
| 1887 |
+
"blogger_toggle_draft": blogger_toggle_draft_handler,
|
| 1888 |
+
"blogger_set_blog_id": set_blog_id_prompt,
|
| 1889 |
+
"blogger_set_client_id": set_client_id_prompt,
|
| 1890 |
+
"blogger_set_client_secret": set_client_secret_prompt,
|
| 1891 |
+
"blogger_set_refresh_token": set_refresh_token_prompt,
|
| 1892 |
+
"blogger_set_default_image": set_default_image_prompt,
|
| 1893 |
+
"blogger_preview_image": blogger_preview_image_handler,
|
| 1894 |
+
"blogger_edit_image": blogger_edit_image_prompt,
|
| 1895 |
+
"blogger_add_image": blogger_add_image_prompt,
|
| 1896 |
+
"blogger_delete_image": blogger_delete_image_handler,
|
| 1897 |
+
"blogger_add_ai_key": blogger_add_ai_key_prompt,
|
| 1898 |
+
"blogger_toggle_ai_key": blogger_toggle_ai_key_menu,
|
| 1899 |
+
"blogger_del_ai_key": blogger_del_ai_key_menu,
|
| 1900 |
+
"blogger_add_channel": blogger_add_channel_prompt,
|
| 1901 |
+
"blogger_del_channel": blogger_del_channel_menu,
|
| 1902 |
+
"blogger_sections": blogger_sections_menu,
|
| 1903 |
+
"blogger_sections_main": blogger_sections_main_menu,
|
| 1904 |
+
"blogger_section_add": blogger_section_add_prompt,
|
| 1905 |
+
"blogger_advanced": blogger_advanced_menu,
|
| 1906 |
+
"blogger_schedule_info": blogger_schedule_info,
|
| 1907 |
+
"blogger_preview_last": blogger_preview_last,
|
| 1908 |
+
"blogger_articles": blogger_articles_menu,
|
| 1909 |
+
"blogger_article_add": blogger_article_add,
|
| 1910 |
+
"blogger_article_add_finish": blogger_article_add_finish,
|
| 1911 |
+
}
|
| 1912 |
+
|
| 1913 |
+
DYNAMIC_PREFIXES = {
|
| 1914 |
+
"blogger_del_ai_key_": "blogger_confirm_del_ai_key",
|
| 1915 |
+
"blogger_toggle_ai_key_": "blogger_confirm_toggle_ai_key",
|
| 1916 |
+
"blogger_test_ai_key_": "blogger_test_ai_key_handler",
|
| 1917 |
+
"blogger_del_ch_": "blogger_confirm_del_channel",
|
| 1918 |
+
"blogger_edit_ch_": "blogger_edit_channel_menu",
|
| 1919 |
+
"blogger_toggle_ch_": "blogger_toggle_channel_handler",
|
| 1920 |
+
"blogger_process_": "blogger_manual_process",
|
| 1921 |
+
"blogger_preview_ch_": "blogger_preview_channel",
|
| 1922 |
+
"blogger_publish_now_": "blogger_publish_article_now",
|
| 1923 |
+
"blogger_publish_draft_": "blogger_publish_article_draft",
|
| 1924 |
+
"blogger_discard_": "blogger_discard_article",
|
| 1925 |
+
"blogger_ch_section_": "blogger_ch_section_prompt",
|
| 1926 |
+
"blogger_ch_sec_set_": "blogger_ch_sec_set",
|
| 1927 |
+
"blogger_ch_sec_new_": "blogger_ch_sec_new",
|
| 1928 |
+
"blogger_ch_limit_": "blogger_ch_limit_prompt",
|
| 1929 |
+
"blogger_ch_hours_": "blogger_ch_hours_prompt",
|
| 1930 |
+
"blogger_section_edit_": "blogger_section_edit",
|
| 1931 |
+
"blogger_section_del_": "blogger_section_del",
|
| 1932 |
+
"blogger_section_detail_": "blogger_section_detail_menu",
|
| 1933 |
+
"blogger_sec_pick_": "blogger_sec_pick",
|
| 1934 |
+
"blogger_sec_set_ch_": "blogger_sec_set_ch",
|
| 1935 |
+
"blogger_sec_labels_": "blogger_sec_labels_menu",
|
| 1936 |
+
"blogger_sec_add_label_": "blogger_sec_add_label_prompt",
|
| 1937 |
+
"blogger_sec_del_label_": "blogger_sec_del_label",
|
| 1938 |
+
"blogger_articles_filter_": "blogger_articles_menu",
|
| 1939 |
+
"blogger_articles_refresh_": "blogger_articles_refresh",
|
| 1940 |
+
"blogger_articles_page_": "blogger_articles_page",
|
| 1941 |
+
"blogger_article_detail_": "blogger_article_detail",
|
| 1942 |
+
"blogger_article_preview_": "blogger_article_preview",
|
| 1943 |
+
"blogger_article_delete_": "blogger_article_delete",
|
| 1944 |
+
"blogger_article_delete_confirm_": "blogger_article_delete_confirm",
|
| 1945 |
+
"blogger_article_edit_": "blogger_article_edit",
|
| 1946 |
+
"blogger_article_edit_field_": "blogger_article_edit_field",
|
| 1947 |
+
"blogger_article_move_up_": "blogger_article_move_up",
|
| 1948 |
+
"blogger_article_move_down_": "blogger_article_move_down",
|
| 1949 |
+
"blogger_article_add_section_": "blogger_article_add_section",
|
| 1950 |
+
}
|
| 1951 |
+
|
| 1952 |
+
|
| 1953 |
+
def register_blogger_handlers(app):
|
| 1954 |
+
# No separate MessageHandler needed: handle_text_input in bot_core.py
|
| 1955 |
+
# already delegates to handle_blogger_text_input for blogger_* states.
|
| 1956 |
+
# Registering a separate MessageHandler with the same filter would
|
| 1957 |
+
# BLOCK handle_text_input from receiving non-blogger states due to
|
| 1958 |
+
# Pyrogram's dispatch (break on first handler match within a group).
|
| 1959 |
+
logger.info("Blogger UI handlers registered")
|