Spaces:
Running
Running
Delete modules/blogger
Browse files- modules/blogger/__init__.py +0 -13
- modules/blogger/__pycache__/__init__.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/blogger_client.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/config.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/database.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/gemini.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/processor.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/prompts.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/publisher.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/scheduler.cpython-314.pyc +0 -0
- modules/blogger/__pycache__/ui.cpython-314.pyc +0 -0
- modules/blogger/blogger_client.py +0 -136
- modules/blogger/config.py +0 -38
- modules/blogger/database.py +0 -213
- modules/blogger/gemini.py +0 -174
- modules/blogger/processor.py +0 -194
- modules/blogger/prompts.py +0 -125
- modules/blogger/publisher.py +0 -79
- modules/blogger/scheduler.py +0 -166
- modules/blogger/ui.py +0 -665
modules/blogger/__init__.py
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
from modules.blogger.database import BloggerDatabase
|
| 2 |
-
from modules.blogger.config import BloggerConfig
|
| 3 |
-
from modules.blogger.blogger_client import BloggerClient
|
| 4 |
-
from modules.blogger.publisher import BloggerPublisher
|
| 5 |
-
from modules.blogger.ui import register_blogger_handlers
|
| 6 |
-
|
| 7 |
-
__all__ = [
|
| 8 |
-
"BloggerDatabase",
|
| 9 |
-
"BloggerConfig",
|
| 10 |
-
"BloggerClient",
|
| 11 |
-
"BloggerPublisher",
|
| 12 |
-
"register_blogger_handlers",
|
| 13 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/__pycache__/__init__.cpython-314.pyc
DELETED
|
Binary file (510 Bytes)
|
|
|
modules/blogger/__pycache__/blogger_client.cpython-314.pyc
DELETED
|
Binary file (10.3 kB)
|
|
|
modules/blogger/__pycache__/config.cpython-314.pyc
DELETED
|
Binary file (2.56 kB)
|
|
|
modules/blogger/__pycache__/database.cpython-314.pyc
DELETED
|
Binary file (14.8 kB)
|
|
|
modules/blogger/__pycache__/gemini.cpython-314.pyc
DELETED
|
Binary file (14.6 kB)
|
|
|
modules/blogger/__pycache__/processor.cpython-314.pyc
DELETED
|
Binary file (13.4 kB)
|
|
|
modules/blogger/__pycache__/prompts.cpython-314.pyc
DELETED
|
Binary file (5.54 kB)
|
|
|
modules/blogger/__pycache__/publisher.cpython-314.pyc
DELETED
|
Binary file (6.28 kB)
|
|
|
modules/blogger/__pycache__/scheduler.cpython-314.pyc
DELETED
|
Binary file (11.6 kB)
|
|
|
modules/blogger/__pycache__/ui.cpython-314.pyc
DELETED
|
Binary file (33.3 kB)
|
|
|
modules/blogger/blogger_client.py
DELETED
|
@@ -1,136 +0,0 @@
|
|
| 1 |
-
import time
|
| 2 |
-
import hashlib
|
| 3 |
-
import logging
|
| 4 |
-
from typing import Optional, Dict, Any
|
| 5 |
-
|
| 6 |
-
import httpx
|
| 7 |
-
|
| 8 |
-
from modules.blogger.config import BLOGGER_TOKEN_URL, BLOGGER_API_BASE
|
| 9 |
-
from modules.publish_target import PublishTarget
|
| 10 |
-
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class BloggerClient(PublishTarget):
|
| 15 |
-
def __init__(self, db):
|
| 16 |
-
self.db = db
|
| 17 |
-
self._access_token = None
|
| 18 |
-
self._token_expires_at = 0
|
| 19 |
-
self._http = httpx.AsyncClient(timeout=30.0)
|
| 20 |
-
|
| 21 |
-
def is_configured(self):
|
| 22 |
-
cfg = self.db.get_config()
|
| 23 |
-
return bool(cfg.get("blog_id") and cfg.get("client_id") and cfg.get("client_secret") and cfg.get("refresh_token"))
|
| 24 |
-
|
| 25 |
-
async def authenticate(self) -> bool:
|
| 26 |
-
cfg = self.db.get_config()
|
| 27 |
-
if not cfg.get("client_id") or not cfg.get("client_secret") or not cfg.get("refresh_token"):
|
| 28 |
-
logger.warning("Blogger: missing credentials")
|
| 29 |
-
return False
|
| 30 |
-
try:
|
| 31 |
-
resp = await self._http.post(
|
| 32 |
-
BLOGGER_TOKEN_URL,
|
| 33 |
-
data={
|
| 34 |
-
"client_id": cfg["client_id"],
|
| 35 |
-
"client_secret": cfg["client_secret"],
|
| 36 |
-
"refresh_token": cfg["refresh_token"],
|
| 37 |
-
"grant_type": "refresh_token",
|
| 38 |
-
},
|
| 39 |
-
)
|
| 40 |
-
data = resp.json()
|
| 41 |
-
if resp.is_error or "access_token" not in data:
|
| 42 |
-
logger.error(f"Blogger auth failed: {data.get('error_description', data)}")
|
| 43 |
-
return False
|
| 44 |
-
self._access_token = data["access_token"]
|
| 45 |
-
self._token_expires_at = time.time() + data.get("expires_in", 3600) - 60
|
| 46 |
-
logger.info("Blogger: authenticated successfully")
|
| 47 |
-
return True
|
| 48 |
-
except Exception as e:
|
| 49 |
-
logger.exception(f"Blogger auth error: {e}")
|
| 50 |
-
return False
|
| 51 |
-
|
| 52 |
-
async def _ensure_token(self) -> Optional[str]:
|
| 53 |
-
if self._access_token and time.time() < self._token_expires_at:
|
| 54 |
-
return self._access_token
|
| 55 |
-
ok = await self.authenticate()
|
| 56 |
-
return self._access_token if ok else None
|
| 57 |
-
|
| 58 |
-
async def _api_request(self, method, path, json_data=None, params=None):
|
| 59 |
-
token = await self._ensure_token()
|
| 60 |
-
if not token:
|
| 61 |
-
return None, "auth_failed"
|
| 62 |
-
url = f"{BLOGGER_API_BASE}{path}"
|
| 63 |
-
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
| 64 |
-
try:
|
| 65 |
-
resp = await self._http.request(method, url, headers=headers, json=json_data, params=params)
|
| 66 |
-
data = resp.json()
|
| 67 |
-
if resp.is_error:
|
| 68 |
-
error_msg = data.get("error", {}).get("message", str(resp.status_code))
|
| 69 |
-
logger.error(f"Blogger API error {resp.status_code}: {error_msg}")
|
| 70 |
-
return None, error_msg
|
| 71 |
-
return data, None
|
| 72 |
-
except httpx.TimeoutException:
|
| 73 |
-
logger.error("Blogger API timeout")
|
| 74 |
-
return None, "timeout"
|
| 75 |
-
except Exception as e:
|
| 76 |
-
logger.exception(f"Blogger API request failed: {e}")
|
| 77 |
-
return None, str(e)
|
| 78 |
-
|
| 79 |
-
async def test_connection(self) -> bool:
|
| 80 |
-
cfg = self.db.get_config()
|
| 81 |
-
blog_id = cfg.get("blog_id", "self")
|
| 82 |
-
data, err = await self._api_request("GET", f"/blogs/{blog_id}")
|
| 83 |
-
if err:
|
| 84 |
-
logger.error(f"Blogger connection test failed: {err}")
|
| 85 |
-
return False
|
| 86 |
-
logger.info(f"Blogger connection OK: {data.get('name', 'unknown')}")
|
| 87 |
-
return True
|
| 88 |
-
|
| 89 |
-
async def publish(self, article: Dict[str, Any]) -> Optional[str]:
|
| 90 |
-
cfg = self.db.get_config()
|
| 91 |
-
blog_id = cfg.get("blog_id", "self")
|
| 92 |
-
is_draft = cfg.get("publish_as_draft", False)
|
| 93 |
-
body = {
|
| 94 |
-
"kind": "blogger#post",
|
| 95 |
-
"title": article.get("title", ""),
|
| 96 |
-
"content": article.get("content", ""),
|
| 97 |
-
}
|
| 98 |
-
labels = article.get("labels", [])
|
| 99 |
-
if labels:
|
| 100 |
-
body["labels"] = labels
|
| 101 |
-
if is_draft:
|
| 102 |
-
body["status"] = "draft"
|
| 103 |
-
data, err = await self._api_request("POST", f"/blogs/{blog_id}/posts", json_data=body)
|
| 104 |
-
if err:
|
| 105 |
-
return None
|
| 106 |
-
post_id = data.get("id")
|
| 107 |
-
if post_id:
|
| 108 |
-
logger.info(f"Blogger: published post {post_id}")
|
| 109 |
-
return str(post_id) if post_id else None
|
| 110 |
-
|
| 111 |
-
async def get_post_url(self, post_id: str) -> Optional[str]:
|
| 112 |
-
cfg = self.db.get_config()
|
| 113 |
-
blog_id = cfg.get("blog_id", "self")
|
| 114 |
-
data, err = await self._api_request("GET", f"/blogs/{blog_id}/posts/{post_id}")
|
| 115 |
-
if err or not data:
|
| 116 |
-
return None
|
| 117 |
-
return data.get("url")
|
| 118 |
-
|
| 119 |
-
async def update_post(self, post_id: str, article: Dict[str, Any]) -> bool:
|
| 120 |
-
cfg = self.db.get_config()
|
| 121 |
-
blog_id = cfg.get("blog_id", "self")
|
| 122 |
-
body = {
|
| 123 |
-
"kind": "blogger#post",
|
| 124 |
-
"title": article.get("title", ""),
|
| 125 |
-
"content": article.get("content", ""),
|
| 126 |
-
}
|
| 127 |
-
labels = article.get("labels", [])
|
| 128 |
-
if labels:
|
| 129 |
-
body["labels"] = labels
|
| 130 |
-
data, err = await self._api_request("PUT", f"/blogs/{blog_id}/posts/{post_id}", json_data=body)
|
| 131 |
-
if err:
|
| 132 |
-
return False
|
| 133 |
-
return True
|
| 134 |
-
|
| 135 |
-
async def close(self):
|
| 136 |
-
await self._http.aclose()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/config.py
DELETED
|
@@ -1,38 +0,0 @@
|
|
| 1 |
-
import logging
|
| 2 |
-
|
| 3 |
-
logger = logging.getLogger(__name__)
|
| 4 |
-
|
| 5 |
-
DEFAULT_BLOGGER_CONFIG = {
|
| 6 |
-
"blog_id": "",
|
| 7 |
-
"client_id": "",
|
| 8 |
-
"client_secret": "",
|
| 9 |
-
"refresh_token": "",
|
| 10 |
-
"publish_as_draft": False,
|
| 11 |
-
"enabled": False,
|
| 12 |
-
}
|
| 13 |
-
|
| 14 |
-
BLOGGER_API_SCOPE = "https://www.googleapis.com/auth/blogger"
|
| 15 |
-
BLOGGER_TOKEN_URL = "https://oauth2.googleapis.com/token"
|
| 16 |
-
BLOGGER_API_BASE = "https://www.googleapis.com/blogger/v3"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
class BloggerConfig:
|
| 20 |
-
def __init__(self, db):
|
| 21 |
-
self.db = db
|
| 22 |
-
|
| 23 |
-
def get(self, key, default=None):
|
| 24 |
-
cfg = self.db.get_config()
|
| 25 |
-
return cfg.get(key, default)
|
| 26 |
-
|
| 27 |
-
def set(self, key, value):
|
| 28 |
-
self.db.update_config(key, value)
|
| 29 |
-
|
| 30 |
-
def get_all(self):
|
| 31 |
-
return dict(self.db.get_config())
|
| 32 |
-
|
| 33 |
-
def is_configured(self):
|
| 34 |
-
cfg = self.db.get_config()
|
| 35 |
-
return bool(cfg.get("blog_id") and cfg.get("client_id") and cfg.get("client_secret") and cfg.get("refresh_token"))
|
| 36 |
-
|
| 37 |
-
def is_enabled(self):
|
| 38 |
-
return bool(self.db.get_config().get("enabled", False))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/database.py
DELETED
|
@@ -1,213 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import os
|
| 3 |
-
import time
|
| 4 |
-
import threading
|
| 5 |
-
import logging
|
| 6 |
-
|
| 7 |
-
logger = logging.getLogger(__name__)
|
| 8 |
-
|
| 9 |
-
DB_FILE = "/data/blogger_data.json"
|
| 10 |
-
lock = threading.Lock()
|
| 11 |
-
|
| 12 |
-
DEFAULT_BLOGGER_DATA = {
|
| 13 |
-
"config": {
|
| 14 |
-
"blog_id": "",
|
| 15 |
-
"client_id": "",
|
| 16 |
-
"client_secret": "",
|
| 17 |
-
"refresh_token": "",
|
| 18 |
-
"publish_as_draft": False,
|
| 19 |
-
"enabled": False,
|
| 20 |
-
},
|
| 21 |
-
"ai_keys": {},
|
| 22 |
-
"channels": {},
|
| 23 |
-
"articles": {},
|
| 24 |
-
"published_ids": [],
|
| 25 |
-
"logs": [],
|
| 26 |
-
"stats": {
|
| 27 |
-
"total_published": 0,
|
| 28 |
-
"total_failed": 0,
|
| 29 |
-
"daily": {},
|
| 30 |
-
"monthly": {},
|
| 31 |
-
},
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
class BloggerDatabase:
|
| 36 |
-
def __init__(self):
|
| 37 |
-
self._cache = None
|
| 38 |
-
|
| 39 |
-
def _ensure_file(self):
|
| 40 |
-
os.makedirs(os.path.dirname(DB_FILE), exist_ok=True)
|
| 41 |
-
if not os.path.exists(DB_FILE):
|
| 42 |
-
with open(DB_FILE, "w", encoding="utf-8") as f:
|
| 43 |
-
json.dump(DEFAULT_BLOGGER_DATA, f, ensure_ascii=False, indent=2)
|
| 44 |
-
|
| 45 |
-
def _read(self):
|
| 46 |
-
self._ensure_file()
|
| 47 |
-
try:
|
| 48 |
-
with open(DB_FILE, "r", encoding="utf-8") as f:
|
| 49 |
-
data = json.load(f)
|
| 50 |
-
except Exception:
|
| 51 |
-
data = {}
|
| 52 |
-
for key, value in DEFAULT_BLOGGER_DATA.items():
|
| 53 |
-
if key not in data:
|
| 54 |
-
data[key] = value.copy() if isinstance(value, (list, dict)) else value
|
| 55 |
-
if not isinstance(data.get("config"), dict):
|
| 56 |
-
data["config"] = {}
|
| 57 |
-
for k, v in DEFAULT_BLOGGER_DATA["config"].items():
|
| 58 |
-
data["config"].setdefault(k, v)
|
| 59 |
-
return data
|
| 60 |
-
|
| 61 |
-
def _write(self, data):
|
| 62 |
-
self._ensure_file()
|
| 63 |
-
tmp = DB_FILE + ".tmp"
|
| 64 |
-
with open(tmp, "w", encoding="utf-8") as f:
|
| 65 |
-
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 66 |
-
f.flush()
|
| 67 |
-
try:
|
| 68 |
-
os.fsync(f.fileno())
|
| 69 |
-
except Exception:
|
| 70 |
-
pass
|
| 71 |
-
os.replace(tmp, DB_FILE)
|
| 72 |
-
self._cache = None
|
| 73 |
-
|
| 74 |
-
def get_config(self):
|
| 75 |
-
with lock:
|
| 76 |
-
return dict(self._read().get("config", {}))
|
| 77 |
-
|
| 78 |
-
def update_config(self, key, value):
|
| 79 |
-
with lock:
|
| 80 |
-
data = self._read()
|
| 81 |
-
data["config"][key] = value
|
| 82 |
-
self._write(data)
|
| 83 |
-
|
| 84 |
-
def get_channel(self, channel_id):
|
| 85 |
-
with lock:
|
| 86 |
-
data = self._read()
|
| 87 |
-
return data.get("channels", {}).get(str(channel_id))
|
| 88 |
-
|
| 89 |
-
def get_all_channels(self):
|
| 90 |
-
with lock:
|
| 91 |
-
data = self._read()
|
| 92 |
-
return list(data.get("channels", {}).values())
|
| 93 |
-
|
| 94 |
-
def save_channel(self, channel_id, channel_data):
|
| 95 |
-
with lock:
|
| 96 |
-
data = self._read()
|
| 97 |
-
data["channels"][str(channel_id)] = channel_data
|
| 98 |
-
self._write(data)
|
| 99 |
-
|
| 100 |
-
def delete_channel(self, channel_id):
|
| 101 |
-
with lock:
|
| 102 |
-
data = self._read()
|
| 103 |
-
data["channels"].pop(str(channel_id), None)
|
| 104 |
-
self._write(data)
|
| 105 |
-
|
| 106 |
-
def save_article(self, article_id, article_data):
|
| 107 |
-
with lock:
|
| 108 |
-
data = self._read()
|
| 109 |
-
data["articles"][str(article_id)] = article_data
|
| 110 |
-
self._write(data)
|
| 111 |
-
|
| 112 |
-
def get_article(self, article_id):
|
| 113 |
-
with lock:
|
| 114 |
-
data = self._read()
|
| 115 |
-
return data.get("articles", {}).get(str(article_id))
|
| 116 |
-
|
| 117 |
-
def is_published(self, fingerprint):
|
| 118 |
-
with lock:
|
| 119 |
-
data = self._read()
|
| 120 |
-
return fingerprint in data.get("published_ids", [])
|
| 121 |
-
|
| 122 |
-
def mark_published(self, fingerprint):
|
| 123 |
-
with lock:
|
| 124 |
-
data = self._read()
|
| 125 |
-
if fingerprint not in data["published_ids"]:
|
| 126 |
-
data["published_ids"].append(fingerprint)
|
| 127 |
-
data["stats"]["total_published"] += 1
|
| 128 |
-
self._write(data)
|
| 129 |
-
|
| 130 |
-
def mark_failed(self):
|
| 131 |
-
with lock:
|
| 132 |
-
data = self._read()
|
| 133 |
-
data["stats"]["total_failed"] += 1
|
| 134 |
-
self._write(data)
|
| 135 |
-
|
| 136 |
-
def add_log(self, entry):
|
| 137 |
-
with lock:
|
| 138 |
-
data = self._read()
|
| 139 |
-
data["logs"].append(entry)
|
| 140 |
-
if len(data["logs"]) > 1000:
|
| 141 |
-
data["logs"] = data["logs"][-1000:]
|
| 142 |
-
self._write(data)
|
| 143 |
-
|
| 144 |
-
def get_logs(self, limit=50):
|
| 145 |
-
with lock:
|
| 146 |
-
data = self._read()
|
| 147 |
-
return list(data["logs"])[-limit:]
|
| 148 |
-
|
| 149 |
-
def get_stats(self):
|
| 150 |
-
with lock:
|
| 151 |
-
data = self._read()
|
| 152 |
-
return dict(data.get("stats", {}))
|
| 153 |
-
|
| 154 |
-
def get_articles_by_status(self, status):
|
| 155 |
-
with lock:
|
| 156 |
-
data = self._read()
|
| 157 |
-
return [a for a in data.get("articles", {}).values() if a.get("status") == status]
|
| 158 |
-
|
| 159 |
-
def update_article_status(self, article_id, status, extra=None):
|
| 160 |
-
with lock:
|
| 161 |
-
data = self._read()
|
| 162 |
-
if str(article_id) in data["articles"]:
|
| 163 |
-
data["articles"][str(article_id)]["status"] = status
|
| 164 |
-
if extra:
|
| 165 |
-
data["articles"][str(article_id)].update(extra)
|
| 166 |
-
self._write(data)
|
| 167 |
-
|
| 168 |
-
def get_all_ai_keys(self):
|
| 169 |
-
with lock:
|
| 170 |
-
data = self._read()
|
| 171 |
-
return dict(data.get("ai_keys", {}))
|
| 172 |
-
|
| 173 |
-
def add_ai_key(self, key_id, key_data):
|
| 174 |
-
with lock:
|
| 175 |
-
data = self._read()
|
| 176 |
-
data["ai_keys"][str(key_id)] = {
|
| 177 |
-
"name": key_data.get("name", str(key_id)),
|
| 178 |
-
"key": key_data.get("key", ""),
|
| 179 |
-
"enabled": key_data.get("enabled", True),
|
| 180 |
-
"usage_count": 0,
|
| 181 |
-
"error_count": 0,
|
| 182 |
-
"last_used": 0,
|
| 183 |
-
"added_at": int(time.time()),
|
| 184 |
-
}
|
| 185 |
-
self._write(data)
|
| 186 |
-
|
| 187 |
-
def delete_ai_key(self, key_id):
|
| 188 |
-
with lock:
|
| 189 |
-
data = self._read()
|
| 190 |
-
data["ai_keys"].pop(str(key_id), None)
|
| 191 |
-
self._write(data)
|
| 192 |
-
|
| 193 |
-
def set_ai_key_enabled(self, key_id, enabled):
|
| 194 |
-
with lock:
|
| 195 |
-
data = self._read()
|
| 196 |
-
if str(key_id) in data["ai_keys"]:
|
| 197 |
-
data["ai_keys"][str(key_id)]["enabled"] = enabled
|
| 198 |
-
self._write(data)
|
| 199 |
-
|
| 200 |
-
def increment_ai_key_usage(self, key_id):
|
| 201 |
-
with lock:
|
| 202 |
-
data = self._read()
|
| 203 |
-
if str(key_id) in data["ai_keys"]:
|
| 204 |
-
data["ai_keys"][str(key_id)]["usage_count"] = data["ai_keys"][str(key_id)].get("usage_count", 0) + 1
|
| 205 |
-
data["ai_keys"][str(key_id)]["last_used"] = int(time.time())
|
| 206 |
-
self._write(data)
|
| 207 |
-
|
| 208 |
-
def increment_ai_key_error(self, key_id):
|
| 209 |
-
with lock:
|
| 210 |
-
data = self._read()
|
| 211 |
-
if str(key_id) in data["ai_keys"]:
|
| 212 |
-
data["ai_keys"][str(key_id)]["error_count"] = data["ai_keys"][str(key_id)].get("error_count", 0) + 1
|
| 213 |
-
self._write(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/gemini.py
DELETED
|
@@ -1,174 +0,0 @@
|
|
| 1 |
-
import time
|
| 2 |
-
import json
|
| 3 |
-
import asyncio
|
| 4 |
-
import logging
|
| 5 |
-
from typing import Optional, Dict, Any, List
|
| 6 |
-
from collections import defaultdict
|
| 7 |
-
|
| 8 |
-
import httpx
|
| 9 |
-
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"
|
| 13 |
-
GEMINI_MODEL = "gemini-2.0-flash"
|
| 14 |
-
GEMINI_TIMEOUT = 60.0
|
| 15 |
-
KEY_COOLDOWN = 300
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
class GeminiKeyManager:
|
| 19 |
-
def __init__(self, db):
|
| 20 |
-
self.db = db
|
| 21 |
-
self._keys: Dict[str, dict] = {}
|
| 22 |
-
self._round_robin_index = 0
|
| 23 |
-
self._cooldown_until: Dict[str, float] = {}
|
| 24 |
-
self._lock = asyncio.Lock()
|
| 25 |
-
|
| 26 |
-
def _load_keys(self):
|
| 27 |
-
raw = self.db.get_all_ai_keys()
|
| 28 |
-
self._keys = {}
|
| 29 |
-
for kid, kdata in raw.items():
|
| 30 |
-
if kdata.get("enabled", True):
|
| 31 |
-
self._keys[kid] = kdata
|
| 32 |
-
|
| 33 |
-
def get_all_keys_summary(self):
|
| 34 |
-
raw = self.db.get_all_ai_keys()
|
| 35 |
-
return raw
|
| 36 |
-
|
| 37 |
-
async def get_available_key(self) -> Optional[tuple]:
|
| 38 |
-
async with self._lock:
|
| 39 |
-
self._load_keys()
|
| 40 |
-
if not self._keys:
|
| 41 |
-
return None
|
| 42 |
-
now = time.time()
|
| 43 |
-
active = {k: v for k, v in self._keys.items()
|
| 44 |
-
if k not in self._cooldown_until or now >= self._cooldown_until[k]}
|
| 45 |
-
if not active:
|
| 46 |
-
oldest = min(self._cooldown_until.items(), key=lambda x: x[1])
|
| 47 |
-
wait = max(0, oldest[1] - now)
|
| 48 |
-
if wait > 0:
|
| 49 |
-
await asyncio.sleep(min(wait, 5))
|
| 50 |
-
self._cooldown_until.pop(oldest[0], None)
|
| 51 |
-
active = {oldest[0]: self._keys[oldest[0]]}
|
| 52 |
-
items = list(active.items())
|
| 53 |
-
if self._round_robin_index >= len(items):
|
| 54 |
-
self._round_robin_index = 0
|
| 55 |
-
kid, kdata = items[self._round_robin_index]
|
| 56 |
-
self._round_robin_index = (self._round_robin_index + 1) % len(items)
|
| 57 |
-
return (kid, kdata.get("key", ""))
|
| 58 |
-
|
| 59 |
-
async def record_success(self, key_id: str):
|
| 60 |
-
async with self._lock:
|
| 61 |
-
self.db.increment_ai_key_usage(key_id)
|
| 62 |
-
self._cooldown_until.pop(key_id, None)
|
| 63 |
-
|
| 64 |
-
async def record_failure(self, key_id: str):
|
| 65 |
-
async with self._lock:
|
| 66 |
-
self.db.increment_ai_key_error(key_id)
|
| 67 |
-
self._cooldown_until[key_id] = time.time() + KEY_COOLDOWN
|
| 68 |
-
|
| 69 |
-
async def mark_disabled(self, key_id: str):
|
| 70 |
-
async with self._lock:
|
| 71 |
-
self.db.set_ai_key_enabled(key_id, False)
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
class GeminiClient:
|
| 75 |
-
def __init__(self, key_manager: GeminiKeyManager):
|
| 76 |
-
self.key_manager = key_manager
|
| 77 |
-
self._http = httpx.AsyncClient(timeout=GEMINI_TIMEOUT)
|
| 78 |
-
|
| 79 |
-
async def close(self):
|
| 80 |
-
await self._http.aclose()
|
| 81 |
-
|
| 82 |
-
async def generate(self, prompt: str, system_instruction: str = None) -> Optional[str]:
|
| 83 |
-
kid, api_key = await self.key_manager.get_available_key()
|
| 84 |
-
if not api_key:
|
| 85 |
-
logger.error("No Gemini API keys available")
|
| 86 |
-
return None
|
| 87 |
-
url = f"{GEMINI_API_BASE}/{GEMINI_MODEL}:generateContent?key={api_key}"
|
| 88 |
-
body: Dict[str, Any] = {
|
| 89 |
-
"contents": [{"parts": [{"text": prompt}]}],
|
| 90 |
-
"generationConfig": {
|
| 91 |
-
"temperature": 0.7,
|
| 92 |
-
"maxOutputTokens": 4096,
|
| 93 |
-
},
|
| 94 |
-
}
|
| 95 |
-
if system_instruction:
|
| 96 |
-
body["systemInstruction"] = {"parts": [{"text": system_instruction}]}
|
| 97 |
-
try:
|
| 98 |
-
resp = await self._http.post(url, json=body)
|
| 99 |
-
if resp.status_code == 429:
|
| 100 |
-
await self.key_manager.record_failure(kid)
|
| 101 |
-
logger.warning(f"Gemini key {kid} rate limited, cooling down")
|
| 102 |
-
return await self._retry(prompt, system_instruction)
|
| 103 |
-
if resp.status_code == 403 or resp.status_code == 401:
|
| 104 |
-
await self.key_manager.mark_disabled(kid)
|
| 105 |
-
logger.warning(f"Gemini key {kid} invalid, disabled")
|
| 106 |
-
return await self._retry(prompt, system_instruction)
|
| 107 |
-
data = resp.json()
|
| 108 |
-
if resp.is_error:
|
| 109 |
-
logger.error(f"Gemini API error {resp.status_code}: {data}")
|
| 110 |
-
await self.key_manager.record_failure(kid)
|
| 111 |
-
return await self._retry(prompt, system_instruction)
|
| 112 |
-
candidates = data.get("candidates", [])
|
| 113 |
-
if not candidates:
|
| 114 |
-
logger.warning("Gemini returned no candidates")
|
| 115 |
-
await self.key_manager.record_failure(kid)
|
| 116 |
-
return None
|
| 117 |
-
text = candidates[0].get("content", {}).get("parts", [{}])[0].get("text", "")
|
| 118 |
-
if not text:
|
| 119 |
-
logger.warning("Gemini returned empty text")
|
| 120 |
-
await self.key_manager.record_failure(kid)
|
| 121 |
-
return None
|
| 122 |
-
await self.key_manager.record_success(kid)
|
| 123 |
-
return text
|
| 124 |
-
except httpx.TimeoutException:
|
| 125 |
-
logger.error(f"Gemini timeout for key {kid}")
|
| 126 |
-
await self.key_manager.record_failure(kid)
|
| 127 |
-
return await self._retry(prompt, system_instruction)
|
| 128 |
-
except Exception as e:
|
| 129 |
-
logger.exception(f"Gemini request failed: {e}")
|
| 130 |
-
await self.key_manager.record_failure(kid)
|
| 131 |
-
return None
|
| 132 |
-
|
| 133 |
-
async def _retry(self, prompt: str, system_instruction: str = None) -> Optional[str]:
|
| 134 |
-
kid2, api_key2 = await self.key_manager.get_available_key()
|
| 135 |
-
if not api_key2:
|
| 136 |
-
return None
|
| 137 |
-
url = f"{GEMINI_API_BASE}/{GEMINI_MODEL}:generateContent?key={api_key2}"
|
| 138 |
-
body = {
|
| 139 |
-
"contents": [{"parts": [{"text": prompt}]}],
|
| 140 |
-
"generationConfig": {"temperature": 0.7, "maxOutputTokens": 4096},
|
| 141 |
-
}
|
| 142 |
-
if system_instruction:
|
| 143 |
-
body["systemInstruction"] = {"parts": [{"text": system_instruction}]}
|
| 144 |
-
try:
|
| 145 |
-
resp = await self._http.post(url, json=body)
|
| 146 |
-
data = resp.json() if not resp.is_error else {}
|
| 147 |
-
candidates = data.get("candidates", [])
|
| 148 |
-
if candidates:
|
| 149 |
-
text = candidates[0].get("content", {}).get("parts", [{}])[0].get("text", "")
|
| 150 |
-
if text:
|
| 151 |
-
return text
|
| 152 |
-
except Exception as e:
|
| 153 |
-
logger.error(f"Gemini retry also failed: {e}")
|
| 154 |
-
return None
|
| 155 |
-
|
| 156 |
-
async def generate_json(self, prompt: str, system_instruction: str = None) -> Optional[dict]:
|
| 157 |
-
text = await self.generate(prompt, system_instruction)
|
| 158 |
-
if not text:
|
| 159 |
-
return None
|
| 160 |
-
text = text.strip()
|
| 161 |
-
if text.startswith("```"):
|
| 162 |
-
for marker in ["```json", "```JSON", "```"]:
|
| 163 |
-
if text.startswith(marker):
|
| 164 |
-
text = text[len(marker):]
|
| 165 |
-
break
|
| 166 |
-
end_idx = text.rfind("```")
|
| 167 |
-
if end_idx != -1:
|
| 168 |
-
text = text[:end_idx]
|
| 169 |
-
text = text.strip()
|
| 170 |
-
try:
|
| 171 |
-
return json.loads(text)
|
| 172 |
-
except json.JSONDecodeError:
|
| 173 |
-
logger.warning(f"Gemini response is not valid JSON, returning raw text")
|
| 174 |
-
return {"raw": text}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/processor.py
DELETED
|
@@ -1,194 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import time
|
| 3 |
-
import hashlib
|
| 4 |
-
import logging
|
| 5 |
-
from typing import Optional, Dict, Any, List
|
| 6 |
-
|
| 7 |
-
from modules.blogger.gemini import GeminiClient, GeminiKeyManager
|
| 8 |
-
from modules.blogger.prompts import (
|
| 9 |
-
SYSTEM_REWRITE,
|
| 10 |
-
SYSTEM_EXTRACT,
|
| 11 |
-
SYSTEM_SEO,
|
| 12 |
-
SYSTEM_HASHTAGS,
|
| 13 |
-
SYSTEM_ALT_IMAGE,
|
| 14 |
-
make_rewrite_prompt,
|
| 15 |
-
make_extract_prompt,
|
| 16 |
-
make_seo_prompt,
|
| 17 |
-
make_hashtag_prompt,
|
| 18 |
-
)
|
| 19 |
-
from modules.blogger.database import BloggerDatabase
|
| 20 |
-
|
| 21 |
-
logger = logging.getLogger(__name__)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class ArticleProcessor:
|
| 25 |
-
def __init__(self, db: BloggerDatabase, gemini_client: GeminiClient):
|
| 26 |
-
self.db = db
|
| 27 |
-
self.gemini = gemini_client
|
| 28 |
-
|
| 29 |
-
async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]:
|
| 30 |
-
raw_text = raw_text.strip()
|
| 31 |
-
if not raw_text:
|
| 32 |
-
return None
|
| 33 |
-
keys_available = bool(self.gemini.key_manager.get_all_keys_summary())
|
| 34 |
-
if not keys_available:
|
| 35 |
-
logger.warning("Blogger: no Gemini keys configured, articles will be published without AI rewriting")
|
| 36 |
-
fingerprint = self._fingerprint(raw_text, source_url)
|
| 37 |
-
if self.db.is_published(fingerprint):
|
| 38 |
-
logger.info(f"Article already processed: {fingerprint[:16]}...")
|
| 39 |
-
return None
|
| 40 |
-
article = {
|
| 41 |
-
"fingerprint": fingerprint,
|
| 42 |
-
"source_text": raw_text,
|
| 43 |
-
"source_url": source_url,
|
| 44 |
-
"media": media or [],
|
| 45 |
-
"status": "processing",
|
| 46 |
-
"created_at": int(time.time()),
|
| 47 |
-
}
|
| 48 |
-
try:
|
| 49 |
-
rewrite = await self._rewrite(raw_text)
|
| 50 |
-
if rewrite:
|
| 51 |
-
article.update(rewrite)
|
| 52 |
-
extracted = await self._extract(raw_text)
|
| 53 |
-
if extracted:
|
| 54 |
-
article["extracted"] = extracted
|
| 55 |
-
seo = await self._seo(
|
| 56 |
-
article.get("title", raw_text[:60]),
|
| 57 |
-
article.get("body", raw_text),
|
| 58 |
-
)
|
| 59 |
-
if seo:
|
| 60 |
-
article["seo"] = seo
|
| 61 |
-
hashtags = await self._hashtags(
|
| 62 |
-
extracted or {},
|
| 63 |
-
article.get("title", raw_text[:60]),
|
| 64 |
-
article.get("body", raw_text),
|
| 65 |
-
)
|
| 66 |
-
if hashtags:
|
| 67 |
-
article["hashtags"] = hashtags
|
| 68 |
-
labels = self._make_labels(extracted or {}, seo or {})
|
| 69 |
-
article["labels"] = labels
|
| 70 |
-
if media:
|
| 71 |
-
alt_data = await self._alt_text(
|
| 72 |
-
article.get("title", raw_text[:60]),
|
| 73 |
-
article.get("body", raw_text),
|
| 74 |
-
)
|
| 75 |
-
if alt_data:
|
| 76 |
-
article["media_alt"] = alt_data
|
| 77 |
-
article["status"] = "processed"
|
| 78 |
-
article["processed_at"] = int(time.time())
|
| 79 |
-
self._save_article(article)
|
| 80 |
-
return article
|
| 81 |
-
except Exception as e:
|
| 82 |
-
logger.exception(f"Article processing failed: {e}")
|
| 83 |
-
article["status"] = "failed"
|
| 84 |
-
article["error"] = str(e)
|
| 85 |
-
self._save_article(article)
|
| 86 |
-
return None
|
| 87 |
-
|
| 88 |
-
def _fingerprint(self, text: str, url: str = "") -> str:
|
| 89 |
-
raw = f"{url}|{text[:300]}"
|
| 90 |
-
return hashlib.md5(raw.encode("utf-8")).hexdigest()
|
| 91 |
-
|
| 92 |
-
def _save_article(self, article: Dict):
|
| 93 |
-
aid = article.get("fingerprint", str(int(time.time())))
|
| 94 |
-
self.db.save_article(aid, article)
|
| 95 |
-
|
| 96 |
-
async def _rewrite(self, text: str) -> Optional[Dict]:
|
| 97 |
-
prompt = make_rewrite_prompt(text)
|
| 98 |
-
result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE)
|
| 99 |
-
if not result:
|
| 100 |
-
logger.warning("Gemini _rewrite returned no result, using fallback")
|
| 101 |
-
return {"title": text[:80], "body": f"<p>{text}</p>", "introduction": "", "faq": [], "conclusion": "", "gemini_used": False}
|
| 102 |
-
logger.info("Gemini _rewrite succeeded")
|
| 103 |
-
return {
|
| 104 |
-
"title": result.get("title", text[:80]),
|
| 105 |
-
"body": result.get("body", f"<p>{text}</p>"),
|
| 106 |
-
"introduction": result.get("introduction", ""),
|
| 107 |
-
"faq": result.get("faq", []),
|
| 108 |
-
"conclusion": result.get("conclusion", ""),
|
| 109 |
-
"gemini_used": True,
|
| 110 |
-
}
|
| 111 |
-
|
| 112 |
-
async def _extract(self, text: str) -> Optional[Dict]:
|
| 113 |
-
prompt = make_extract_prompt(text)
|
| 114 |
-
return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT)
|
| 115 |
-
|
| 116 |
-
async def _seo(self, title: str, body: str) -> Optional[Dict]:
|
| 117 |
-
prompt = make_seo_prompt(title, body)
|
| 118 |
-
return await self.gemini.generate_json(prompt, SYSTEM_SEO)
|
| 119 |
-
|
| 120 |
-
async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 121 |
-
prompt = make_hashtag_prompt(extracted, title, body)
|
| 122 |
-
result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS)
|
| 123 |
-
if result and isinstance(result, dict):
|
| 124 |
-
tags = result.get("hashtags", [])
|
| 125 |
-
if isinstance(tags, list):
|
| 126 |
-
return tags
|
| 127 |
-
return []
|
| 128 |
-
|
| 129 |
-
async def _alt_text(self, title: str, body: str) -> Optional[Dict]:
|
| 130 |
-
prompt = f"""أنشئ وصف ALT وتعليق للصورة بناءً على:
|
| 131 |
-
العنوان: {title}
|
| 132 |
-
المحتوى: {body[:500]}
|
| 133 |
-
الرد JSON فقط: {{"alt": "...", "caption": "..."}}"""
|
| 134 |
-
return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE)
|
| 135 |
-
|
| 136 |
-
def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]:
|
| 137 |
-
labels = set()
|
| 138 |
-
if extracted.get("type"):
|
| 139 |
-
labels.add(extracted["type"])
|
| 140 |
-
if extracted.get("ministry"):
|
| 141 |
-
labels.add(extracted["ministry"])
|
| 142 |
-
if extracted.get("province"):
|
| 143 |
-
labels.add(extracted["province"])
|
| 144 |
-
if extracted.get("city"):
|
| 145 |
-
labels.add(extracted["city"])
|
| 146 |
-
if extracted.get("company"):
|
| 147 |
-
labels.add(extracted["company"])
|
| 148 |
-
seo_labels = seo.get("labels", [])
|
| 149 |
-
if isinstance(seo_labels, list):
|
| 150 |
-
for lbl in seo_labels:
|
| 151 |
-
if lbl:
|
| 152 |
-
labels.add(str(lbl))
|
| 153 |
-
return list(labels)[:10]
|
| 154 |
-
|
| 155 |
-
def make_article_html(self, article: Dict) -> str:
|
| 156 |
-
parts = []
|
| 157 |
-
intro = article.get("introduction", "")
|
| 158 |
-
if intro:
|
| 159 |
-
parts.append(f'<p>{intro}</p>')
|
| 160 |
-
body = article.get("body", "")
|
| 161 |
-
if body:
|
| 162 |
-
parts.append(body)
|
| 163 |
-
extracted = article.get("extracted", {})
|
| 164 |
-
if extracted:
|
| 165 |
-
table_rows = []
|
| 166 |
-
labels_map = {
|
| 167 |
-
"ministry": "الوزارة", "company": "الشركة", "province": "المحافظة",
|
| 168 |
-
"city": "المدينة", "salary": "الراتب", "qualification": "المؤهل",
|
| 169 |
-
"gender": "الجنس", "age": "العمر", "experience": "الخبرة",
|
| 170 |
-
"deadline": "آخر موعد", "apply_url": "رابط التقديم",
|
| 171 |
-
"email": "البريد الإلكتروني", "phone": "الهاتف",
|
| 172 |
-
}
|
| 173 |
-
for key, label in labels_map.items():
|
| 174 |
-
val = extracted.get(key)
|
| 175 |
-
if val:
|
| 176 |
-
val_str = str(val)
|
| 177 |
-
if key == "apply_url" and val_str.startswith("http"):
|
| 178 |
-
val_str = f'<a href="{val_str}">رابط التقديم</a>'
|
| 179 |
-
table_rows.append(f'<tr><td>{label}</td><td>{val_str}</td></tr>')
|
| 180 |
-
if table_rows:
|
| 181 |
-
parts.append(f'<table>{"".join(table_rows)}</table>')
|
| 182 |
-
faq = article.get("faq", [])
|
| 183 |
-
if faq:
|
| 184 |
-
faq_html = "<h2>الأسئلة الشائعة</h2>"
|
| 185 |
-
for item in faq:
|
| 186 |
-
q = item.get("question", "")
|
| 187 |
-
a = item.get("answer", "")
|
| 188 |
-
if q and a:
|
| 189 |
-
faq_html += f'<h3>{q}</h3><p>{a}</p>'
|
| 190 |
-
parts.append(faq_html)
|
| 191 |
-
conclusion = article.get("conclusion", "")
|
| 192 |
-
if conclusion:
|
| 193 |
-
parts.append(f'<p>{conclusion}</p>')
|
| 194 |
-
return "\n".join(parts)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/prompts.py
DELETED
|
@@ -1,125 +0,0 @@
|
|
| 1 |
-
SYSTEM_REWRITE = """
|
| 2 |
-
أنت كاتب محتوى عراقي محترف مهمتك إعادة صياغة المنشورات إلى مقالات احترافية منظمة.
|
| 3 |
-
|
| 4 |
-
قواعد صارمة:
|
| 5 |
-
1. حافظ على جميع المعلومات المهمة — لا تحذف أي شيء.
|
| 6 |
-
2. حسن اللغة العربية ورتب الفقرات.
|
| 7 |
-
3. أزل التكرار والحشو.
|
| 8 |
-
4. حول المعلومات الطويلة إلى نقاط منظمة.
|
| 9 |
-
5. أضف عناوين فرعية مناسبة.
|
| 10 |
-
6. أضف قسم أسئلة شائعة (FAQ) إذا كان المحتوى مناسباً.
|
| 11 |
-
7. اجعل المقال جاهزاً للنشر على مدونة.
|
| 12 |
-
8. استخدم لغة عربية فصحى واضحة.
|
| 13 |
-
|
| 14 |
-
الرد يكون بتنسيق JSON فقط بهذا الشكل:
|
| 15 |
-
{
|
| 16 |
-
"title": "عنوان المقال",
|
| 17 |
-
"introduction": "مقدمة من 2-3 جمل",
|
| 18 |
-
"body": "محتوى المقال منسق بعلامات HTML (p, h2, ul, ol, li, table)",
|
| 19 |
-
"faq": [{"question": "سؤال?", "answer": "جواب"}],
|
| 20 |
-
"conclusion": "خاتمة من 1-2 جمل"
|
| 21 |
-
}
|
| 22 |
-
"""
|
| 23 |
-
|
| 24 |
-
SYSTEM_EXTRACT = """
|
| 25 |
-
استخرج البيانات التالية من النص إذا وجدت:
|
| 26 |
-
|
| 27 |
-
- الوزارة / الجهة
|
| 28 |
-
- الشركة / المؤسسة
|
| 29 |
-
- المحافظة
|
| 30 |
-
- المدينة / المنطقة / القضاء / الناحية
|
| 31 |
-
- نوع الوظيفة أو الإعلان
|
| 32 |
-
- الراتب
|
| 33 |
-
- المؤهل العلمي
|
| 34 |
-
- الاختصاص
|
| 35 |
-
- الجنس (ذكر / أنثى / غير محدد)
|
| 36 |
-
- العمر المطلوب
|
| 37 |
-
- سنوات الخبرة
|
| 38 |
-
- آخر موعد للتقديم
|
| 39 |
-
- رابط التقديم
|
| 40 |
-
- البريد الإلكتروني
|
| 41 |
-
- أرقام الهاتف
|
| 42 |
-
- المستمسكات المطلوبة
|
| 43 |
-
- طريقة التقديم
|
| 44 |
-
|
| 45 |
-
الرد بتنسيق JSON. أي حقل غير موجود يكون قيمته null.
|
| 46 |
-
"""
|
| 47 |
-
|
| 48 |
-
SYSTEM_SEO = """
|
| 49 |
-
قم بتحسين النص لمحركات البحث وأنشئ:
|
| 50 |
-
|
| 51 |
-
1. عنوان SEO (لا يزيد عن 60 حرف)
|
| 52 |
-
2. Meta Description (لا يزيد عن 160 حرف)
|
| 53 |
-
3. Focus Keyword (كلمة مفتاحية رئيسية)
|
| 54 |
-
4. Long Tail Keywords (3-5 كلمات مفتاحية طويلة)
|
| 55 |
-
5. Slug (رابط صديق)
|
| 56 |
-
6. Labels (3-5 تصنيفات)
|
| 57 |
-
|
| 58 |
-
الرد بتنسيق JSON فقط.
|
| 59 |
-
"""
|
| 60 |
-
|
| 61 |
-
SYSTEM_HASHTAGS = """
|
| 62 |
-
أنشئ هاشتاكات ذكية بناءً على البيانات المستخرجة من النص.
|
| 63 |
-
|
| 64 |
-
مثال:
|
| 65 |
-
إذا كانت الوظيفة في بغداد، الكرادة، وزارة التربية:
|
| 66 |
-
#بغداد #الكرادة #وزارة_التربية #وظائف_العراق #وظائف_بغداد #تعيينات #فرص_عمل
|
| 67 |
-
|
| 68 |
-
القواعد:
|
| 69 |
-
- استخرج الهاشتاكات من البيانات الموجودة فقط.
|
| 70 |
-
- أضف هاشتاكات عامة مرتبطة بالموضوع.
|
| 71 |
-
- لا تخترع معلومات غير موجودة.
|
| 72 |
-
- أضف 5-10 هاشتاكات مناسبة.
|
| 73 |
-
|
| 74 |
-
الرد بتنسيق JSON:
|
| 75 |
-
{"hashtags": ["هاشتاك1", "هاشتاك2", ...]}
|
| 76 |
-
"""
|
| 77 |
-
|
| 78 |
-
SYSTEM_ALT_IMAGE = """
|
| 79 |
-
أنشئ وصف بديل (ALT) وتعليق (Caption) لصورة المقال بناءً على محتوى المقال.
|
| 80 |
-
|
| 81 |
-
الرد بتنسيق JSON:
|
| 82 |
-
{
|
| 83 |
-
"alt": "وصف بديل للصورة",
|
| 84 |
-
"caption": "تعليق أسفل الصورة"
|
| 85 |
-
}
|
| 86 |
-
"""
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def make_rewrite_prompt(raw_text: str) -> str:
|
| 90 |
-
return f"""أعد صياغة النص التالي إلى مقال احترافي منظم وجاهز للنشر على مدونة عراقية:
|
| 91 |
-
|
| 92 |
-
{raw_text}
|
| 93 |
-
|
| 94 |
-
يجب أن يكون الرد JSON بالشكل المطلوب."""
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def make_extract_prompt(text: str) -> str:
|
| 98 |
-
return f"""استخرج المعلومات التالية من هذا النص:
|
| 99 |
-
|
| 100 |
-
{text}
|
| 101 |
-
|
| 102 |
-
الرد JSON فقط."""
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def make_seo_prompt(title: str, body: str) -> str:
|
| 106 |
-
return f"""حسن النص التالي لمحركات البحث:
|
| 107 |
-
|
| 108 |
-
العنوان: {title}
|
| 109 |
-
المحتوى: {body[:2000]}
|
| 110 |
-
|
| 111 |
-
الرد JSON فقط."""
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def make_hashtag_prompt(extracted_data: dict, title: str, body: str) -> str:
|
| 115 |
-
data_str = json.dumps(extracted_data, ensure_ascii=False)
|
| 116 |
-
return f"""أنشئ هاشتاكات ذكية بناءً على:
|
| 117 |
-
|
| 118 |
-
البيانات المستخرجة: {data_str}
|
| 119 |
-
العنوان: {title}
|
| 120 |
-
المحتوى: {body[:1000]}
|
| 121 |
-
|
| 122 |
-
الرد JSON فقط."""
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/publisher.py
DELETED
|
@@ -1,79 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import time
|
| 3 |
-
import hashlib
|
| 4 |
-
import logging
|
| 5 |
-
from typing import Optional, Dict, Any
|
| 6 |
-
|
| 7 |
-
from modules.blogger.database import BloggerDatabase
|
| 8 |
-
from modules.blogger.blogger_client import BloggerClient
|
| 9 |
-
from modules.blogger.config import BloggerConfig
|
| 10 |
-
from modules.blogger.gemini import GeminiClient, GeminiKeyManager
|
| 11 |
-
from modules.blogger.processor import ArticleProcessor
|
| 12 |
-
from modules.blogger.scheduler import BloggerScheduler
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class BloggerPublisher:
|
| 18 |
-
def __init__(self):
|
| 19 |
-
self.db = BloggerDatabase()
|
| 20 |
-
self.config = BloggerConfig(self.db)
|
| 21 |
-
self.client = BloggerClient(self.db)
|
| 22 |
-
self.key_manager = GeminiKeyManager(self.db)
|
| 23 |
-
self.gemini = GeminiClient(self.key_manager)
|
| 24 |
-
self.processor = ArticleProcessor(self.db, self.gemini)
|
| 25 |
-
self.scheduler = BloggerScheduler(self.db, self.processor, self)
|
| 26 |
-
self._running = False
|
| 27 |
-
|
| 28 |
-
async def start(self):
|
| 29 |
-
self._running = True
|
| 30 |
-
logger.info("BloggerPublisher started")
|
| 31 |
-
asyncio.create_task(self.scheduler.start())
|
| 32 |
-
|
| 33 |
-
async def stop(self):
|
| 34 |
-
self._running = False
|
| 35 |
-
await self.scheduler.stop()
|
| 36 |
-
await self.gemini.close()
|
| 37 |
-
await self.client.close()
|
| 38 |
-
logger.info("BloggerPublisher stopped")
|
| 39 |
-
|
| 40 |
-
def is_running(self):
|
| 41 |
-
return self._running
|
| 42 |
-
|
| 43 |
-
async def test_connection(self) -> bool:
|
| 44 |
-
return await self.client.test_connection()
|
| 45 |
-
|
| 46 |
-
async def publish_article(self, article: Dict[str, Any]) -> Optional[str]:
|
| 47 |
-
if not self.config.is_enabled():
|
| 48 |
-
logger.warning("Blogger publisher is disabled")
|
| 49 |
-
return None
|
| 50 |
-
if not self.client.is_configured():
|
| 51 |
-
logger.warning("Blogger not configured")
|
| 52 |
-
return None
|
| 53 |
-
fingerprint = self._make_fingerprint(article)
|
| 54 |
-
if self.db.is_published(fingerprint):
|
| 55 |
-
logger.info(f"Article already published: {fingerprint[:16]}...")
|
| 56 |
-
return None
|
| 57 |
-
post_id = await self.client.publish(article)
|
| 58 |
-
if post_id:
|
| 59 |
-
self.db.mark_published(fingerprint)
|
| 60 |
-
self.db.add_log({
|
| 61 |
-
"time": int(time.time()),
|
| 62 |
-
"type": "publish",
|
| 63 |
-
"post_id": post_id,
|
| 64 |
-
"title": article.get("title", ""),
|
| 65 |
-
"status": "success",
|
| 66 |
-
})
|
| 67 |
-
return post_id
|
| 68 |
-
self.db.mark_failed()
|
| 69 |
-
self.db.add_log({
|
| 70 |
-
"time": int(time.time()),
|
| 71 |
-
"type": "publish",
|
| 72 |
-
"title": article.get("title", ""),
|
| 73 |
-
"status": "failed",
|
| 74 |
-
})
|
| 75 |
-
return None
|
| 76 |
-
|
| 77 |
-
def _make_fingerprint(self, article: Dict[str, Any]) -> str:
|
| 78 |
-
raw = f"{article.get('title', '')}|{article.get('source_url', '')}|{article.get('source_text', '')[:200]}"
|
| 79 |
-
return hashlib.md5(raw.encode("utf-8")).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/scheduler.py
DELETED
|
@@ -1,166 +0,0 @@
|
|
| 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 = 60
|
| 13 |
-
MAX_ARTICLES_PER_CYCLE = 5
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
class BloggerScheduler:
|
| 17 |
-
def __init__(self, db: BloggerDatabase, processor: ArticleProcessor, publisher):
|
| 18 |
-
self.db = db
|
| 19 |
-
self.processor = processor
|
| 20 |
-
self.publisher = publisher
|
| 21 |
-
self._running = False
|
| 22 |
-
self._queue: List[Dict] = []
|
| 23 |
-
|
| 24 |
-
async def start(self):
|
| 25 |
-
self._running = True
|
| 26 |
-
logger.info("BloggerScheduler started")
|
| 27 |
-
while self._running:
|
| 28 |
-
try:
|
| 29 |
-
await self._cycle()
|
| 30 |
-
except Exception as e:
|
| 31 |
-
logger.exception(f"Scheduler cycle error: {e}")
|
| 32 |
-
await asyncio.sleep(POLL_INTERVAL)
|
| 33 |
-
|
| 34 |
-
async def stop(self):
|
| 35 |
-
self._running = False
|
| 36 |
-
|
| 37 |
-
async def _cycle(self):
|
| 38 |
-
if not self.publisher.config.is_enabled():
|
| 39 |
-
return
|
| 40 |
-
channels = self.db.get_all_channels()
|
| 41 |
-
if not channels:
|
| 42 |
-
return
|
| 43 |
-
await self._fetch_new_posts(channels)
|
| 44 |
-
await self._process_queue()
|
| 45 |
-
|
| 46 |
-
async def _fetch_new_posts(self, channels: List[Dict]):
|
| 47 |
-
from bot_core import user_client
|
| 48 |
-
if not user_client:
|
| 49 |
-
logger.warning("User client not available for Blogger polling")
|
| 50 |
-
return
|
| 51 |
-
for ch in channels:
|
| 52 |
-
if not ch.get("enabled", True):
|
| 53 |
-
continue
|
| 54 |
-
ch_id = ch.get("channel_id", "")
|
| 55 |
-
if not ch_id:
|
| 56 |
-
continue
|
| 57 |
-
try:
|
| 58 |
-
last_id = ch.get("last_message_id", 0)
|
| 59 |
-
chat_identifier = int(ch_id) if str(ch_id).lstrip('-').isdigit() else ch_id
|
| 60 |
-
latest_id = last_id
|
| 61 |
-
async for msg in user_client.get_chat_history(chat_identifier, limit=3):
|
| 62 |
-
if msg.id <= last_id:
|
| 63 |
-
break
|
| 64 |
-
if msg.id > latest_id:
|
| 65 |
-
latest_id = msg.id
|
| 66 |
-
if not msg.text and not msg.caption:
|
| 67 |
-
continue
|
| 68 |
-
raw = msg.text or msg.caption or ""
|
| 69 |
-
if not raw.strip():
|
| 70 |
-
continue
|
| 71 |
-
fingerprint = self.processor._fingerprint(raw, str(msg.id))
|
| 72 |
-
if self.db.is_published(fingerprint):
|
| 73 |
-
logger.info(f"Blogger: skip already published {fingerprint[:16]}...")
|
| 74 |
-
continue
|
| 75 |
-
article = self.db.get_article(fingerprint)
|
| 76 |
-
if article and article.get("status") in ("queued", "published"):
|
| 77 |
-
continue
|
| 78 |
-
media = []
|
| 79 |
-
if msg.photo:
|
| 80 |
-
media.append({"type": "photo", "file_id": msg.photo.file_id})
|
| 81 |
-
elif msg.video:
|
| 82 |
-
media.append({"type": "video", "file_id": msg.video.file_id})
|
| 83 |
-
chat_str = str(ch_id).replace('-100', '') if str(ch_id).lstrip('-').isdigit() else str(ch_id).lstrip('@')
|
| 84 |
-
source_url = f"https://t.me/c/{chat_str}/{msg.id}"
|
| 85 |
-
logger.info(f"Blogger: processing new message {msg.id} from {ch_id}")
|
| 86 |
-
article_data = await self.processor.process_raw_post(raw, source_url, media)
|
| 87 |
-
if article_data and article_data.get("status") == "processed":
|
| 88 |
-
article_data["channel_id"] = ch_id
|
| 89 |
-
article_data["section"] = ch.get("section", "general")
|
| 90 |
-
article_data["status"] = "queued"
|
| 91 |
-
self._queue.append(article_data)
|
| 92 |
-
self.db.save_article(article_data["fingerprint"], article_data)
|
| 93 |
-
logger.info(f"Blogger: queued article '{article_data.get('title', '')[:30]}' from {ch_id}")
|
| 94 |
-
else:
|
| 95 |
-
logger.warning(f"Blogger: processing failed for message {msg.id}")
|
| 96 |
-
self.db.save_channel(ch_id, {**ch, "last_message_id": latest_id})
|
| 97 |
-
except Exception as e:
|
| 98 |
-
logger.warning(f"Blogger: failed to poll channel {ch_id}: {e}")
|
| 99 |
-
|
| 100 |
-
async def _process_queue(self):
|
| 101 |
-
now = datetime.now()
|
| 102 |
-
current_hour = now.hour
|
| 103 |
-
channels = {c.get("channel_id"): c for c in self.db.get_all_channels()}
|
| 104 |
-
today_published = self._today_published_count()
|
| 105 |
-
queue = [a for a in self._queue if a.get("status") == "queued"]
|
| 106 |
-
if not queue:
|
| 107 |
-
return
|
| 108 |
-
published = 0
|
| 109 |
-
for article in queue:
|
| 110 |
-
if published >= MAX_ARTICLES_PER_CYCLE:
|
| 111 |
-
break
|
| 112 |
-
ch_id = article.get("channel_id", "")
|
| 113 |
-
ch_config = channels.get(ch_id, {})
|
| 114 |
-
if not self._can_publish_now(ch_config, current_hour, today_published):
|
| 115 |
-
continue
|
| 116 |
-
section = article.get("section", "general")
|
| 117 |
-
section_today = today_published.get(section, 0)
|
| 118 |
-
daily_limit = ch_config.get("daily_limit", 10)
|
| 119 |
-
if section_today >= daily_limit:
|
| 120 |
-
continue
|
| 121 |
-
html = self.processor.make_article_html(article)
|
| 122 |
-
blogger_article = {
|
| 123 |
-
"title": article.get("title", "عنوان المقال"),
|
| 124 |
-
"content": html,
|
| 125 |
-
"labels": article.get("labels", []),
|
| 126 |
-
}
|
| 127 |
-
post_id = await self.publisher.publish_article(blogger_article)
|
| 128 |
-
if post_id:
|
| 129 |
-
self.db.update_article_status(article["fingerprint"], "published", {
|
| 130 |
-
"post_id": post_id,
|
| 131 |
-
"published_at": int(time.time()),
|
| 132 |
-
})
|
| 133 |
-
today_published[section] = today_published.get(section, 0) + 1
|
| 134 |
-
published += 1
|
| 135 |
-
logger.info(f"Blogger: published article {article.get('title', '')[:30]}...")
|
| 136 |
-
else:
|
| 137 |
-
self.db.update_article_status(article["fingerprint"], "failed", {
|
| 138 |
-
"failed_at": int(time.time()),
|
| 139 |
-
})
|
| 140 |
-
article["status"] = "published" if post_id else "failed"
|
| 141 |
-
self._queue = [a for a in self._queue if a.get("fingerprint") != article["fingerprint"]]
|
| 142 |
-
|
| 143 |
-
def _can_publish_now(self, ch_config: Dict, current_hour: int, today_published: Dict) -> bool:
|
| 144 |
-
if not ch_config.get("enabled", True):
|
| 145 |
-
return False
|
| 146 |
-
start_hour = ch_config.get("start_hour", 9)
|
| 147 |
-
end_hour = ch_config.get("end_hour", 23)
|
| 148 |
-
if current_hour < start_hour or current_hour >= end_hour:
|
| 149 |
-
return False
|
| 150 |
-
daily_limit = ch_config.get("daily_limit", 10)
|
| 151 |
-
section = ch_config.get("section", "general")
|
| 152 |
-
section_count = today_published.get(section, 0)
|
| 153 |
-
if section_count >= daily_limit:
|
| 154 |
-
return False
|
| 155 |
-
return True
|
| 156 |
-
|
| 157 |
-
def _today_published_count(self) -> Dict:
|
| 158 |
-
today = time.strftime("%Y-%m-%d")
|
| 159 |
-
stats = self.db.get_stats()
|
| 160 |
-
daily = stats.get("daily", {})
|
| 161 |
-
return daily.get(today, {})
|
| 162 |
-
|
| 163 |
-
def add_to_queue(self, article: Dict):
|
| 164 |
-
article["status"] = "queued"
|
| 165 |
-
self._queue.append(article)
|
| 166 |
-
self.db.save_article(article["fingerprint"], article)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/blogger/ui.py
DELETED
|
@@ -1,665 +0,0 @@
|
|
| 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 |
-
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
_publisher = None
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def get_publisher():
|
| 16 |
-
global _publisher
|
| 17 |
-
if _publisher is None:
|
| 18 |
-
_publisher = BloggerPublisher()
|
| 19 |
-
return _publisher
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _grid_buttons(buttons, max_cols=2):
|
| 23 |
-
rows = []
|
| 24 |
-
pending = []
|
| 25 |
-
for item in buttons:
|
| 26 |
-
if isinstance(item, list):
|
| 27 |
-
if pending:
|
| 28 |
-
rows.append(pending)
|
| 29 |
-
pending = []
|
| 30 |
-
rows.append(item)
|
| 31 |
-
else:
|
| 32 |
-
pending.append(item)
|
| 33 |
-
if len(pending) >= max_cols:
|
| 34 |
-
rows.append(pending)
|
| 35 |
-
pending = []
|
| 36 |
-
if pending:
|
| 37 |
-
rows.append(pending)
|
| 38 |
-
return rows
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
async def safe_edit(callback, text, reply_markup=None):
|
| 42 |
-
try:
|
| 43 |
-
await callback.edit_message_text(text, reply_markup=reply_markup)
|
| 44 |
-
except Exception:
|
| 45 |
-
try:
|
| 46 |
-
await callback.answer()
|
| 47 |
-
except Exception:
|
| 48 |
-
pass
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
async def blogger_main_menu(client, callback):
|
| 52 |
-
pub = get_publisher()
|
| 53 |
-
cfg = pub.config.get_all()
|
| 54 |
-
enabled = "✅ مفعل" if pub.config.is_enabled() else "❌ متوقف"
|
| 55 |
-
configured = "✅ تم" if pub.client.is_configured() else "❌ غير مكتمل"
|
| 56 |
-
blog_id = cfg.get("blog_id", "") or "غير محدد"
|
| 57 |
-
text = (
|
| 58 |
-
f"🌐 **Blogger Publisher**\n\n"
|
| 59 |
-
f"الحالة: {enabled}\n"
|
| 60 |
-
f"الإعدادات: {configured}\n"
|
| 61 |
-
f"Blog ID: `{blog_id}`\n\n"
|
| 62 |
-
f"اختر من القائمة:"
|
| 63 |
-
)
|
| 64 |
-
buttons = [
|
| 65 |
-
InlineKeyboardButton(f"{'✅' if pub.config.is_enabled() else '❌'} تشغيل/إيقاف", callback_data="blogger_toggle"),
|
| 66 |
-
InlineKeyboardButton("⚙️ إعدادات Blogger", callback_data="blogger_settings"),
|
| 67 |
-
InlineKeyboardButton("📢 إدارة القنوات", callback_data="blogger_channels"),
|
| 68 |
-
InlineKeyboardButton("🔑 مفاتيح Gemini", callback_data="blogger_ai_keys"),
|
| 69 |
-
InlineKeyboardButton("📊 إحصائيات", callback_data="blogger_stats"),
|
| 70 |
-
InlineKeyboardButton("📋 سجل العمليات", callback_data="blogger_logs"),
|
| 71 |
-
InlineKeyboardButton("🧪 اختبار الاتصال", callback_data="blogger_test"),
|
| 72 |
-
]
|
| 73 |
-
rows = _grid_buttons(buttons, 2)
|
| 74 |
-
rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")])
|
| 75 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
async def blogger_settings_menu(client, callback):
|
| 79 |
-
pub = get_publisher()
|
| 80 |
-
cfg = pub.config.get_all()
|
| 81 |
-
text = (
|
| 82 |
-
f"⚙️ **إعدادات Blogger**\n\n"
|
| 83 |
-
f"Blog ID: `{cfg.get('blog_id', '') or '❌ فارغ'}`\n"
|
| 84 |
-
f"Client ID: `{cfg.get('client_id', '')[:15] or '❌ فارغ'}...`\n"
|
| 85 |
-
f"Client Secret: {'✅ محفوظ' if cfg.get('client_secret') else '❌ فارغ'}\n"
|
| 86 |
-
f"Refresh Token: {'✅ محفوظ' if cfg.get('refresh_token') else '❌ فارغ'}\n"
|
| 87 |
-
f"النشر كمسودة: {'✅' if cfg.get('publish_as_draft') else '❌'}\n\n"
|
| 88 |
-
f"لتعيين أو تغيير أي قيمة، اضغط على الزر المناسب."
|
| 89 |
-
)
|
| 90 |
-
buttons = [
|
| 91 |
-
InlineKeyboardButton("📝 Blog ID", callback_data="blogger_set_blog_id"),
|
| 92 |
-
InlineKeyboardButton("🔑 Client ID", callback_data="blogger_set_client_id"),
|
| 93 |
-
InlineKeyboardButton("🔐 Client Secret", callback_data="blogger_set_client_secret"),
|
| 94 |
-
InlineKeyboardButton("🔄 Refresh Token", callback_data="blogger_set_refresh_token"),
|
| 95 |
-
InlineKeyboardButton(f"{'✅' if cfg.get('publish_as_draft') else '❌'} مسودة", callback_data="blogger_toggle_draft"),
|
| 96 |
-
InlineKeyboardButton("🧪 اختبار", callback_data="blogger_test"),
|
| 97 |
-
]
|
| 98 |
-
rows = _grid_buttons(buttons, 2)
|
| 99 |
-
rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")])
|
| 100 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
async def blogger_channels_menu(client, callback):
|
| 104 |
-
pub = get_publisher()
|
| 105 |
-
channels = pub.db.get_all_channels()
|
| 106 |
-
text = f"📢 **قنوات Blogger**\n\nعدد القنوات: {len(channels)}\n\n"
|
| 107 |
-
if channels:
|
| 108 |
-
for ch in channels:
|
| 109 |
-
section = ch.get("section", "غير محدد")
|
| 110 |
-
daily = ch.get("daily_limit", 0)
|
| 111 |
-
enabled = "✅" if ch.get("enabled", True) else "❌"
|
| 112 |
-
start_h = ch.get("start_hour", 9)
|
| 113 |
-
end_h = ch.get("end_hour", 23)
|
| 114 |
-
text += f"{enabled} {ch.get('name', ch.get('channel_id', '?'))}\n"
|
| 115 |
-
text += f" 📂 {section} | 📊 {daily}/يوم | 🕐 {start_h}:00-{end_h}:00\n"
|
| 116 |
-
else:
|
| 117 |
-
text += "لا توجد قنوات بعد.\nأضف قناة تيليجرام كمصدر للنشر."
|
| 118 |
-
buttons = [
|
| 119 |
-
InlineKeyboardButton("➕ إضافة قناة", callback_data="blogger_add_channel"),
|
| 120 |
-
]
|
| 121 |
-
if channels:
|
| 122 |
-
buttons.append(InlineKeyboardButton("🗑 حذف قناة", callback_data="blogger_del_channel"))
|
| 123 |
-
for ch in channels:
|
| 124 |
-
ch_id = ch.get("channel_id", "")
|
| 125 |
-
name = ch.get("name", ch_id)
|
| 126 |
-
buttons.append(InlineKeyboardButton(f"⚙️ {name[:25]}", callback_data=f"blogger_edit_ch_{ch_id}"))
|
| 127 |
-
rows = _grid_buttons(buttons, 2)
|
| 128 |
-
rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")])
|
| 129 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
async def blogger_add_channel_prompt(client, callback):
|
| 133 |
-
from bot_core import user_states
|
| 134 |
-
user_states.pop(callback.from_user.id, None)
|
| 135 |
-
user_states[callback.from_user.id] = {"state": "blogger_add_channel_id"}
|
| 136 |
-
await safe_edit(callback, "أرسل معرف القناة (ID) أو اليوزر (@username):\n\nمثال: @my_channel أو -1001234567890", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")]]))
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
async def blogger_add_channel_section_prompt(client, message, ch_id, ch_name):
|
| 140 |
-
from bot_core import user_states
|
| 141 |
-
uid = message.from_user.id
|
| 142 |
-
user_states.pop(uid, None)
|
| 143 |
-
user_states[uid] = {"state": "blogger_add_ch_section", "ch_id": ch_id, "ch_name": ch_name}
|
| 144 |
-
await message.reply("أرسل اسم القسم في المدونة:\nمثال: وظائف, أخبار, مناقصات")
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
async def blogger_add_channel_limit_prompt(client, message, ch_id, section):
|
| 148 |
-
from bot_core import user_states
|
| 149 |
-
uid = message.from_user.id
|
| 150 |
-
user_states.pop(uid, None)
|
| 151 |
-
user_states[uid] = {"state": "blogger_add_ch_limit", "ch_id": ch_id, "section": section}
|
| 152 |
-
await message.reply("أرسل الحد اليومي لعدد المنشورات:\nمثال: 30")
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
async def blogger_del_channel_menu(client, callback):
|
| 156 |
-
pub = get_publisher()
|
| 157 |
-
channels = pub.db.get_all_channels()
|
| 158 |
-
if not channels:
|
| 159 |
-
await callback.answer("لا توجد قنوات.", show_alert=True)
|
| 160 |
-
return
|
| 161 |
-
text = "🗑 **حذف قناة Blogger**\n\nاختر القناة للحذف:"
|
| 162 |
-
buttons = []
|
| 163 |
-
for ch in channels:
|
| 164 |
-
name = ch.get("name", ch.get("channel_id", "?"))
|
| 165 |
-
ch_id = ch.get("channel_id", "")
|
| 166 |
-
buttons.append([InlineKeyboardButton(f"🗑 {name}", callback_data=f"blogger_del_ch_{ch_id}")])
|
| 167 |
-
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")])
|
| 168 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
async def blogger_confirm_del_channel(client, callback):
|
| 172 |
-
ch_id = callback.data.split("_")[-1]
|
| 173 |
-
pub = get_publisher()
|
| 174 |
-
pub.db.delete_channel(ch_id)
|
| 175 |
-
await callback.answer("✅ تم حذف القناة.")
|
| 176 |
-
await blogger_channels_menu(client, callback)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
async def blogger_edit_channel_menu(client, callback):
|
| 180 |
-
ch_id = callback.data.split("_")[-1]
|
| 181 |
-
pub = get_publisher()
|
| 182 |
-
ch = pub.db.get_channel(ch_id)
|
| 183 |
-
if not ch:
|
| 184 |
-
await callback.answer("غير موجودة.")
|
| 185 |
-
return
|
| 186 |
-
enabled = "✅" if ch.get("enabled", True) else "❌"
|
| 187 |
-
text = (
|
| 188 |
-
f"⚙️ **إعدادات قناة Blogger**\n\n"
|
| 189 |
-
f"الاسم: {ch.get('name', ch_id)}\n"
|
| 190 |
-
f"ID: `{ch_id}`\n"
|
| 191 |
-
f"الحالة: {enabled}\n"
|
| 192 |
-
f"القسم: {ch.get('section', 'غير محدد')}\n"
|
| 193 |
-
f"الحد اليومي: {ch.get('daily_limit', 10)}\n"
|
| 194 |
-
f"ساعات النشر: {ch.get('start_hour', 9)}:00 - {ch.get('end_hour', 23)}:00\n"
|
| 195 |
-
)
|
| 196 |
-
buttons = [
|
| 197 |
-
InlineKeyboardButton(f"{'✅' if ch.get('enabled', True) else '❌'} تفعيل/تعطيل", callback_data=f"blogger_toggle_ch_{ch_id}"),
|
| 198 |
-
InlineKeyboardButton(f"📂 تغيير القسم", callback_data=f"blogger_ch_section_{ch_id}"),
|
| 199 |
-
InlineKeyboardButton(f"📊 تغيير الحد اليومي", callback_data=f"blogger_ch_limit_{ch_id}"),
|
| 200 |
-
InlineKeyboardButton(f"🕐 تغيير ساعات النشر", callback_data=f"blogger_ch_hours_{ch_id}"),
|
| 201 |
-
InlineKeyboardButton(f"🔄 معالجة فورية", callback_data=f"blogger_process_{ch_id}"),
|
| 202 |
-
]
|
| 203 |
-
rows = _grid_buttons(buttons, 2)
|
| 204 |
-
rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")])
|
| 205 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
async def blogger_toggle_channel_handler(client, callback):
|
| 209 |
-
ch_id = callback.data.split("_")[-1]
|
| 210 |
-
pub = get_publisher()
|
| 211 |
-
ch = pub.db.get_channel(ch_id)
|
| 212 |
-
if ch:
|
| 213 |
-
new_state = not ch.get("enabled", True)
|
| 214 |
-
ch["enabled"] = new_state
|
| 215 |
-
pub.db.save_channel(ch_id, ch)
|
| 216 |
-
await callback.answer("✅ تم التبديل.")
|
| 217 |
-
callback.data = f"blogger_edit_ch_{ch_id}"
|
| 218 |
-
await blogger_edit_channel_menu(client, callback)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
async def blogger_manual_process(client, callback):
|
| 222 |
-
ch_id = callback.data.split("_")[-1]
|
| 223 |
-
pub = get_publisher()
|
| 224 |
-
ch = pub.db.get_channel(ch_id)
|
| 225 |
-
if not ch:
|
| 226 |
-
await callback.answer("غير موجودة.")
|
| 227 |
-
return
|
| 228 |
-
await callback.answer("جارٍ المعالجة...")
|
| 229 |
-
try:
|
| 230 |
-
before = len(pub.db.get_all_channels())
|
| 231 |
-
await pub.scheduler._fetch_new_posts([ch])
|
| 232 |
-
await callback.answer("✅ تمت معالجة المنشورات وجدولتها.", show_alert=True)
|
| 233 |
-
except Exception as e:
|
| 234 |
-
logger.exception(f"Blogger manual process error: {e}")
|
| 235 |
-
await callback.answer(f"❌ فشل: {str(e)[:50]}", show_alert=True)
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
async def blogger_ch_section_prompt(client, callback):
|
| 239 |
-
from bot_core import user_states
|
| 240 |
-
ch_id = callback.data.split("_")[-1]
|
| 241 |
-
uid = callback.from_user.id
|
| 242 |
-
user_states[uid] = {"state": "blogger_ch_section_input", "ch_id": ch_id}
|
| 243 |
-
await safe_edit(callback, "أرسل اسم القسم الجديد:\nمثال: وظائف, أخبار, مناقصات", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
async def blogger_ch_limit_prompt(client, callback):
|
| 247 |
-
from bot_core import user_states
|
| 248 |
-
ch_id = callback.data.split("_")[-1]
|
| 249 |
-
uid = callback.from_user.id
|
| 250 |
-
user_states[uid] = {"state": "blogger_ch_limit_input", "ch_id": ch_id}
|
| 251 |
-
await safe_edit(callback, "أرسل الحد اليومي الجديد:\nمثال: 30", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
async def blogger_ch_hours_prompt(client, callback):
|
| 255 |
-
from bot_core import user_states
|
| 256 |
-
ch_id = callback.data.split("_")[-1]
|
| 257 |
-
uid = callback.from_user.id
|
| 258 |
-
user_states[uid] = {"state": "blogger_ch_hours_input", "ch_id": ch_id}
|
| 259 |
-
await safe_edit(callback, "أرسل ساعات النشر بالتنسيق:\n`start_hour-end_hour`\nمثال: 9-23", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
async def blogger_stats_menu(client, callback):
|
| 263 |
-
pub = get_publisher()
|
| 264 |
-
stats = pub.db.get_stats()
|
| 265 |
-
text = (
|
| 266 |
-
f"📊 **إحصائيات Blogger**\n\n"
|
| 267 |
-
f"✅ المنشورات: {stats.get('total_published', 0)}\n"
|
| 268 |
-
f"❌ الفاشلة: {stats.get('total_failed', 0)}"
|
| 269 |
-
)
|
| 270 |
-
buttons = [[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]]
|
| 271 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
async def blogger_logs_menu(client, callback):
|
| 275 |
-
pub = get_publisher()
|
| 276 |
-
logs = pub.db.get_logs(20)
|
| 277 |
-
text = "📋 **آخر العمليات**\n\n"
|
| 278 |
-
if not logs:
|
| 279 |
-
text += "لا توجد عمليات."
|
| 280 |
-
else:
|
| 281 |
-
for entry in logs:
|
| 282 |
-
ts = entry.get("time", 0)
|
| 283 |
-
tstr = time.strftime("%H:%M", time.localtime(ts)) if ts else "?"
|
| 284 |
-
st = "✅" if entry.get("status") == "success" else "❌"
|
| 285 |
-
title = entry.get("title", "")[:30]
|
| 286 |
-
text += f"{st} [{tstr}] {title}\n"
|
| 287 |
-
buttons = [[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]]
|
| 288 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
async def blogger_test_handler(client, callback):
|
| 292 |
-
pub = get_publisher()
|
| 293 |
-
if not pub.client.is_configured():
|
| 294 |
-
await safe_edit(
|
| 295 |
-
callback,
|
| 296 |
-
"❌ الإعدادات غير مكتملة. أضف Blog ID و Client ID و Secret و Refresh Token أولاً.",
|
| 297 |
-
InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]])
|
| 298 |
-
)
|
| 299 |
-
return
|
| 300 |
-
await callback.answer("جاري اختبار الاتصال...")
|
| 301 |
-
ok = await pub.test_connection()
|
| 302 |
-
if ok:
|
| 303 |
-
await safe_edit(
|
| 304 |
-
callback,
|
| 305 |
-
"✅ **تم الاتصال بنجاح**\n\nBlogger يعمل بشكل صحيح.",
|
| 306 |
-
InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]])
|
| 307 |
-
)
|
| 308 |
-
else:
|
| 309 |
-
await safe_edit(
|
| 310 |
-
callback,
|
| 311 |
-
"❌ **فشل الاتصال**\n\nتحقق من الإعدادات وراجع السجل.",
|
| 312 |
-
InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]])
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
async def blogger_toggle_handler(client, callback):
|
| 317 |
-
pub = get_publisher()
|
| 318 |
-
new_state = not pub.config.is_enabled()
|
| 319 |
-
pub.config.set("enabled", new_state)
|
| 320 |
-
status = "✅ تم التفعيل" if new_state else "❌ تم الإيقاف"
|
| 321 |
-
await callback.answer(status, show_alert=True)
|
| 322 |
-
await blogger_main_menu(client, callback)
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
async def blogger_toggle_draft_handler(client, callback):
|
| 326 |
-
pub = get_publisher()
|
| 327 |
-
current = pub.config.get("publish_as_draft", False)
|
| 328 |
-
pub.config.set("publish_as_draft", not current)
|
| 329 |
-
await callback.answer("تم التحديث.")
|
| 330 |
-
await blogger_settings_menu(client, callback)
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
async def set_blog_id_prompt(client, callback):
|
| 334 |
-
from bot_core import user_states
|
| 335 |
-
user_states.pop(callback.from_user.id, None)
|
| 336 |
-
user_states[callback.from_user.id] = {"state": "blogger_set_blog_id"}
|
| 337 |
-
await safe_edit(callback, "أرسل Blog ID الخاص بمدونتك:", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_settings")]]))
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
async def set_client_id_prompt(client, callback):
|
| 341 |
-
from bot_core import user_states
|
| 342 |
-
user_states.pop(callback.from_user.id, None)
|
| 343 |
-
user_states[callback.from_user.id] = {"state": "blogger_set_client_id"}
|
| 344 |
-
await safe_edit(callback, "أرسل Client ID من Google Cloud Console:", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_settings")]]))
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
async def set_client_secret_prompt(client, callback):
|
| 348 |
-
from bot_core import user_states
|
| 349 |
-
user_states.pop(callback.from_user.id, None)
|
| 350 |
-
user_states[callback.from_user.id] = {"state": "blogger_set_client_secret"}
|
| 351 |
-
await safe_edit(callback, "أرسل Client Secret:", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_settings")]]))
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
async def set_refresh_token_prompt(client, callback):
|
| 355 |
-
from bot_core import user_states
|
| 356 |
-
user_states.pop(callback.from_user.id, None)
|
| 357 |
-
user_states[callback.from_user.id] = {"state": "blogger_set_refresh_token"}
|
| 358 |
-
await safe_edit(callback, "أرسل Refresh Token:", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_settings")]]))
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
async def blogger_test_ai_key_handler(client, callback):
|
| 362 |
-
pub = get_publisher()
|
| 363 |
-
kid = callback.data.split("_")[-1]
|
| 364 |
-
keys = pub.db.get_all_ai_keys()
|
| 365 |
-
kdata = keys.get(kid)
|
| 366 |
-
if not kdata:
|
| 367 |
-
await callback.answer("المفتاح غير موجود.", show_alert=True)
|
| 368 |
-
return
|
| 369 |
-
api_key = kdata.get("key", "")
|
| 370 |
-
if not api_key:
|
| 371 |
-
await callback.answer("المفتاح فارغ.", show_alert=True)
|
| 372 |
-
return
|
| 373 |
-
await callback.answer("جارٍ اختبار المفتاح...")
|
| 374 |
-
import httpx
|
| 375 |
-
import json
|
| 376 |
-
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}"
|
| 377 |
-
body = {"contents": [{"parts": [{"text": "قل مرحبا بالعربية"}]}]}
|
| 378 |
-
try:
|
| 379 |
-
async with httpx.AsyncClient(timeout=30) as hc:
|
| 380 |
-
resp = await hc.post(url, json=body)
|
| 381 |
-
if resp.status_code == 200:
|
| 382 |
-
data = resp.json()
|
| 383 |
-
candidates = data.get("candidates", [])
|
| 384 |
-
if candidates:
|
| 385 |
-
txt = candidates[0].get("content", {}).get("parts", [{}])[0].get("text", "")
|
| 386 |
-
await callback.answer(f"✅ {txt[:80]}", show_alert=True)
|
| 387 |
-
else:
|
| 388 |
-
await callback.answer("❌ لا يوجد رد من Gemini", show_alert=True)
|
| 389 |
-
else:
|
| 390 |
-
err = resp.json().get("error", {}).get("message", resp.reason_phrase)
|
| 391 |
-
await callback.answer(f"❌ خطأ {resp.status_code}: {err[:50]}", show_alert=True)
|
| 392 |
-
except Exception as e:
|
| 393 |
-
await callback.answer(f"❌ خطأ: {str(e)[:60]}", show_alert=True)
|
| 394 |
-
await blogger_ai_keys_menu(client, callback)
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
async def blogger_ai_keys_menu(client, callback):
|
| 398 |
-
pub = get_publisher()
|
| 399 |
-
keys = pub.db.get_all_ai_keys()
|
| 400 |
-
text = "🔑 **مفاتيح Gemini**\n\n"
|
| 401 |
-
if not keys:
|
| 402 |
-
text += "لا توجد مفاتيح بعد.\nأضف مفتاحاً جديداً."
|
| 403 |
-
else:
|
| 404 |
-
text += f"العدد: {len(keys)}\n\n"
|
| 405 |
-
for kid, kdata in keys.items():
|
| 406 |
-
name = kdata.get("name", kid)
|
| 407 |
-
status = "✅" if kdata.get("enabled", True) else "❌"
|
| 408 |
-
usage = kdata.get("usage_count", 0)
|
| 409 |
-
errors = kdata.get("error_count", 0)
|
| 410 |
-
last = kdata.get("last_used", 0)
|
| 411 |
-
last_str = time.strftime("%H:%M", time.localtime(last)) if last else "لم يستخدم"
|
| 412 |
-
text += f"{status} **{name}**\n"
|
| 413 |
-
text += f" 📊 {usage} طلب | ❌ {errors} خطأ | 🕐 {last_str}\n"
|
| 414 |
-
buttons = [
|
| 415 |
-
InlineKeyboardButton("➕ إضافة مفتاح", callback_data="blogger_add_ai_key"),
|
| 416 |
-
]
|
| 417 |
-
if keys:
|
| 418 |
-
buttons.append(InlineKeyboardButton("🗑 حذف مفتاح", callback_data="blogger_del_ai_key"))
|
| 419 |
-
buttons.append(InlineKeyboardButton("🔁 تبديل حالة", callback_data="blogger_toggle_ai_key"))
|
| 420 |
-
for kid, kdata in keys.items():
|
| 421 |
-
name = kdata.get("name", kid)[:12]
|
| 422 |
-
buttons.append(InlineKeyboardButton(f"🧪 اختبار {name}", callback_data=f"blogger_test_ai_key_{kid}"))
|
| 423 |
-
rows = _grid_buttons(buttons, 2)
|
| 424 |
-
rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")])
|
| 425 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(rows))
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
async def blogger_add_ai_key_prompt(client, callback):
|
| 429 |
-
from bot_core import user_states
|
| 430 |
-
user_states.pop(callback.from_user.id, None)
|
| 431 |
-
user_states[callback.from_user.id] = {"state": "blogger_add_ai_key"}
|
| 432 |
-
await safe_edit(callback, "أرسل مفتاح Gemini API:\n\nمثال: AIzaSy...", InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_ai_keys")]]))
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
async def blogger_del_ai_key_menu(client, callback):
|
| 436 |
-
pub = get_publisher()
|
| 437 |
-
keys = pub.db.get_all_ai_keys()
|
| 438 |
-
if not keys:
|
| 439 |
-
await callback.answer("لا توجد مفاتيح.", show_alert=True)
|
| 440 |
-
return
|
| 441 |
-
text = "🗑 **حذف مفتاح Gemini**\n\nاختر المفتاح للحذف:"
|
| 442 |
-
buttons = []
|
| 443 |
-
for kid, kdata in keys.items():
|
| 444 |
-
name = kdata.get("name", kid)
|
| 445 |
-
buttons.append([InlineKeyboardButton(f"🗑 {name}", callback_data=f"blogger_del_ai_key_{kid}")])
|
| 446 |
-
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_ai_keys")])
|
| 447 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
async def blogger_confirm_del_ai_key(client, callback):
|
| 451 |
-
key_id = callback.data.split("_")[-1]
|
| 452 |
-
pub = get_publisher()
|
| 453 |
-
pub.db.delete_ai_key(key_id)
|
| 454 |
-
await callback.answer("✅ تم الحذف.")
|
| 455 |
-
await blogger_ai_keys_menu(client, callback)
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
async def blogger_toggle_ai_key_menu(client, callback):
|
| 459 |
-
pub = get_publisher()
|
| 460 |
-
keys = pub.db.get_all_ai_keys()
|
| 461 |
-
if not keys:
|
| 462 |
-
await callback.answer("لا توجد مفاتيح.", show_alert=True)
|
| 463 |
-
return
|
| 464 |
-
text = "🔁 **تبديل حالة مفتاح Gemini**\n\nاختر المفتاح لتفعيل/تعطيل:"
|
| 465 |
-
buttons = []
|
| 466 |
-
for kid, kdata in keys.items():
|
| 467 |
-
name = kdata.get("name", kid)
|
| 468 |
-
st = "✅" if kdata.get("enabled", True) else "❌"
|
| 469 |
-
buttons.append([InlineKeyboardButton(f"{st} {name}", callback_data=f"blogger_toggle_ai_key_{kid}")])
|
| 470 |
-
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="blogger_ai_keys")])
|
| 471 |
-
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
async def blogger_confirm_toggle_ai_key(client, callback):
|
| 475 |
-
key_id = callback.data.split("_")[-1]
|
| 476 |
-
pub = get_publisher()
|
| 477 |
-
keys = pub.db.get_all_ai_keys()
|
| 478 |
-
current = keys.get(key_id, {}).get("enabled", True) if key_id in keys else True
|
| 479 |
-
pub.db.set_ai_key_enabled(key_id, not current)
|
| 480 |
-
await callback.answer("✅ تم التبديل.")
|
| 481 |
-
await blogger_toggle_ai_key_menu(client, callback)
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
async def handle_blogger_text_input(client, message):
|
| 485 |
-
from bot_core import is_admin, user_states
|
| 486 |
-
if not is_admin(message.from_user.id):
|
| 487 |
-
return
|
| 488 |
-
uid = message.from_user.id
|
| 489 |
-
if uid not in user_states:
|
| 490 |
-
return
|
| 491 |
-
state = user_states[uid].get("state", "")
|
| 492 |
-
if not state.startswith("blogger_"):
|
| 493 |
-
return
|
| 494 |
-
text = message.text.strip()
|
| 495 |
-
pub = get_publisher()
|
| 496 |
-
back_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_menu")]])
|
| 497 |
-
try:
|
| 498 |
-
if state == "blogger_set_blog_id":
|
| 499 |
-
pub.config.set("blog_id", text)
|
| 500 |
-
await message.reply("✅ تم حفظ Blog ID.", reply_markup=back_markup)
|
| 501 |
-
user_states.pop(uid, None)
|
| 502 |
-
elif state == "blogger_set_client_id":
|
| 503 |
-
pub.config.set("client_id", text)
|
| 504 |
-
await message.reply("✅ تم حفظ Client ID.", reply_markup=back_markup)
|
| 505 |
-
user_states.pop(uid, None)
|
| 506 |
-
elif state == "blogger_set_client_secret":
|
| 507 |
-
pub.config.set("client_secret", text)
|
| 508 |
-
await message.reply("✅ تم حفظ Client Secret.", reply_markup=back_markup)
|
| 509 |
-
user_states.pop(uid, None)
|
| 510 |
-
elif state == "blogger_set_refresh_token":
|
| 511 |
-
pub.config.set("refresh_token", text)
|
| 512 |
-
await message.reply("✅ تم حفظ Refresh Token.", reply_markup=back_markup)
|
| 513 |
-
user_states.pop(uid, None)
|
| 514 |
-
elif state == "blogger_add_ai_key":
|
| 515 |
-
name = text[:30]
|
| 516 |
-
kid = str(int(time.time()))
|
| 517 |
-
pub.db.add_ai_key(kid, {"name": name, "key": text})
|
| 518 |
-
await message.reply(f"✅ تم إضافة المفتاح '{name}'.", reply_markup=back_markup)
|
| 519 |
-
user_states.pop(uid, None)
|
| 520 |
-
elif state == "blogger_add_channel_id":
|
| 521 |
-
raw = text.strip()
|
| 522 |
-
ch_id = raw
|
| 523 |
-
ch_name = raw
|
| 524 |
-
import re
|
| 525 |
-
m = re.search(r'(?:https?://)?(?:t\.me/|telegram\.me/)(\w+)', raw)
|
| 526 |
-
if m:
|
| 527 |
-
ch_id = "@" + m.group(1)
|
| 528 |
-
ch_name = ch_id
|
| 529 |
-
elif raw.startswith("@"):
|
| 530 |
-
ch_id = raw
|
| 531 |
-
ch_name = raw
|
| 532 |
-
try:
|
| 533 |
-
from bot_core import user_client
|
| 534 |
-
if user_client:
|
| 535 |
-
chat = await user_client.get_chat(ch_id)
|
| 536 |
-
ch_name = chat.title or chat.username or ch_id
|
| 537 |
-
ch_id = str(chat.id)
|
| 538 |
-
except Exception as e:
|
| 539 |
-
logger.warning(f"Blogger: could not resolve channel name for {ch_id}: {e}")
|
| 540 |
-
user_states[uid] = {"state": "blogger_add_ch_section", "ch_id": ch_id, "ch_name": ch_name}
|
| 541 |
-
bk = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")]])
|
| 542 |
-
await message.reply(f"✅ تم التعرف على القناة: {ch_name}\nأرسل اسم القسم في المدونة:\nمثال: وظائف, أخبار, مناقصات", reply_markup=bk)
|
| 543 |
-
elif state == "blogger_add_ch_section":
|
| 544 |
-
ch_id = user_states[uid].get("ch_id", "")
|
| 545 |
-
ch_name = user_states[uid].get("ch_name", ch_id)
|
| 546 |
-
section = text.strip()
|
| 547 |
-
if not section:
|
| 548 |
-
await message.reply("❌ اسم القسم لا يمكن أن يكون فارغاً.")
|
| 549 |
-
return
|
| 550 |
-
user_states[uid] = {"state": "blogger_add_ch_limit", "ch_id": ch_id, "ch_name": ch_name, "section": section}
|
| 551 |
-
bk = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")]])
|
| 552 |
-
await message.reply(f"✅ القسم: {section}\nأرسل الحد اليومي لعدد المنشورات:\nمثال: 30", reply_markup=bk)
|
| 553 |
-
elif state == "blogger_ch_section_input":
|
| 554 |
-
ch_id = user_states[uid].get("ch_id", "")
|
| 555 |
-
section = text.strip()
|
| 556 |
-
if not section:
|
| 557 |
-
await message.reply("❌ اسم القسم لا يمكن أن يكون فارغاً.")
|
| 558 |
-
return
|
| 559 |
-
ch = pub.db.get_channel(ch_id)
|
| 560 |
-
if ch:
|
| 561 |
-
ch["section"] = section
|
| 562 |
-
pub.db.save_channel(ch_id, ch)
|
| 563 |
-
await message.reply("✅ تم تحديث القسم.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 564 |
-
user_states.pop(uid, None)
|
| 565 |
-
elif state == "blogger_ch_limit_input":
|
| 566 |
-
ch_id = user_states[uid].get("ch_id", "")
|
| 567 |
-
try:
|
| 568 |
-
limit = int(text.strip())
|
| 569 |
-
except ValueError:
|
| 570 |
-
await message.reply("❌ الرجاء إرسال رقم صحيح.\nمثال: 30")
|
| 571 |
-
return
|
| 572 |
-
ch = pub.db.get_channel(ch_id)
|
| 573 |
-
if ch:
|
| 574 |
-
ch["daily_limit"] = limit
|
| 575 |
-
pub.db.save_channel(ch_id, ch)
|
| 576 |
-
await message.reply(f"✅ تم تحديث الحد اليومي إلى {limit}.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 577 |
-
user_states.pop(uid, None)
|
| 578 |
-
elif state == "blogger_ch_hours_input":
|
| 579 |
-
ch_id = user_states[uid].get("ch_id", "")
|
| 580 |
-
import re
|
| 581 |
-
m = re.match(r'(\d+)\s*[-\s]\s*(\d+)', text.strip())
|
| 582 |
-
if not m:
|
| 583 |
-
await message.reply("❌ التنسيق خطأ. أرسل مثل: `9-23`")
|
| 584 |
-
return
|
| 585 |
-
start_h, end_h = int(m.group(1)), int(m.group(2))
|
| 586 |
-
if not (0 <= start_h < 24 and 0 <= end_h < 24):
|
| 587 |
-
await message.reply("❌ الساعات يجب أن تكون بين 0 و 23.")
|
| 588 |
-
return
|
| 589 |
-
ch = pub.db.get_channel(ch_id)
|
| 590 |
-
if ch:
|
| 591 |
-
ch["start_hour"] = start_h
|
| 592 |
-
ch["end_hour"] = end_h
|
| 593 |
-
pub.db.save_channel(ch_id, ch)
|
| 594 |
-
await message.reply(f"✅ تم تحديث ساعات النشر: {start_h}:00 - {end_h}:00.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data=f"blogger_edit_ch_{ch_id}")]]))
|
| 595 |
-
user_states.pop(uid, None)
|
| 596 |
-
elif state == "blogger_add_ch_limit":
|
| 597 |
-
ch_id = user_states[uid].get("ch_id", "")
|
| 598 |
-
ch_name = user_states[uid].get("ch_name", ch_id)
|
| 599 |
-
section = user_states[uid].get("section", "عام")
|
| 600 |
-
try:
|
| 601 |
-
daily_limit = int(text.strip())
|
| 602 |
-
except ValueError:
|
| 603 |
-
await message.reply("❌ الرجاء إرسال رقم صحيح.\nمثال: 30")
|
| 604 |
-
return
|
| 605 |
-
channel_data = {
|
| 606 |
-
"channel_id": ch_id,
|
| 607 |
-
"name": ch_name,
|
| 608 |
-
"section": section,
|
| 609 |
-
"daily_limit": daily_limit,
|
| 610 |
-
"enabled": True,
|
| 611 |
-
"start_hour": 9,
|
| 612 |
-
"end_hour": 23,
|
| 613 |
-
"last_message_id": 0,
|
| 614 |
-
"added_at": int(time.time()),
|
| 615 |
-
}
|
| 616 |
-
pub.db.save_channel(ch_id, channel_data)
|
| 617 |
-
bk = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="blogger_channels")]])
|
| 618 |
-
await message.reply(f"✅ تم إضافة القناة بنجاح:\n{ch_name} → {section} ({daily_limit}/يوم)", reply_markup=bk)
|
| 619 |
-
user_states.pop(uid, None)
|
| 620 |
-
else:
|
| 621 |
-
return
|
| 622 |
-
except Exception as e:
|
| 623 |
-
logger.exception(f"Blogger input error: {e}")
|
| 624 |
-
await message.reply(f"❌ فشل: {e}", reply_markup=back_markup)
|
| 625 |
-
user_states.pop(uid, None)
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
BLOGGER_CALLBACKS = {
|
| 629 |
-
"blogger_menu": blogger_main_menu,
|
| 630 |
-
"blogger_settings": blogger_settings_menu,
|
| 631 |
-
"blogger_channels": blogger_channels_menu,
|
| 632 |
-
"blogger_ai_keys": blogger_ai_keys_menu,
|
| 633 |
-
"blogger_stats": blogger_stats_menu,
|
| 634 |
-
"blogger_logs": blogger_logs_menu,
|
| 635 |
-
"blogger_test": blogger_test_handler,
|
| 636 |
-
"blogger_toggle": blogger_toggle_handler,
|
| 637 |
-
"blogger_toggle_draft": blogger_toggle_draft_handler,
|
| 638 |
-
"blogger_set_blog_id": set_blog_id_prompt,
|
| 639 |
-
"blogger_set_client_id": set_client_id_prompt,
|
| 640 |
-
"blogger_set_client_secret": set_client_secret_prompt,
|
| 641 |
-
"blogger_set_refresh_token": set_refresh_token_prompt,
|
| 642 |
-
"blogger_add_ai_key": blogger_add_ai_key_prompt,
|
| 643 |
-
"blogger_toggle_ai_key": blogger_toggle_ai_key_menu,
|
| 644 |
-
"blogger_del_ai_key": blogger_del_ai_key_menu,
|
| 645 |
-
"blogger_add_channel": blogger_add_channel_prompt,
|
| 646 |
-
"blogger_del_channel": blogger_del_channel_menu,
|
| 647 |
-
}
|
| 648 |
-
|
| 649 |
-
DYNAMIC_PREFIXES = {
|
| 650 |
-
"blogger_del_ai_key_": "blogger_confirm_del_ai_key",
|
| 651 |
-
"blogger_toggle_ai_key_": "blogger_confirm_toggle_ai_key",
|
| 652 |
-
"blogger_test_ai_key_": "blogger_test_ai_key_handler",
|
| 653 |
-
"blogger_del_ch_": "blogger_confirm_del_channel",
|
| 654 |
-
"blogger_edit_ch_": "blogger_edit_channel_menu",
|
| 655 |
-
"blogger_toggle_ch_": "blogger_toggle_channel_handler",
|
| 656 |
-
"blogger_process_": "blogger_manual_process",
|
| 657 |
-
"blogger_ch_section_": "blogger_ch_section_prompt",
|
| 658 |
-
"blogger_ch_limit_": "blogger_ch_limit_prompt",
|
| 659 |
-
"blogger_ch_hours_": "blogger_ch_hours_prompt",
|
| 660 |
-
}
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
def register_blogger_handlers(app):
|
| 664 |
-
app.add_handler(MessageHandler(handle_blogger_text_input, filters.text & filters.private))
|
| 665 |
-
logger.info("Blogger UI handlers registered")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|