Files
gfil-blog/deploy_scripts/daily_light.py

152 lines
6.4 KiB
Python
Raw Normal View History

2026-06-28 17:19:47 +00:00
#!/usr/bin/env python3
"""GFIL Light Promotion — Telegraph 2/day + Blogger 2/day, DeepSeek-generated"""
import urllib.request, json, smtplib, time, random, sys, io, os
from email.mime.text import MIMEText
from datetime import datetime
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# === CONFIG (secrets from env, never hardcoded) ===
TELEGRAPH_TOKEN = os.environ.get("TELEGRAPH_TOKEN", "")
DEEPSEEK_KEY = os.environ.get("DEEPSEEK_KEY", "")
BLOGGER_EMAIL = os.environ.get("GOOGLE_EMAIL", "")
BLOGGER_PASS = os.environ.get("SMTP_PASS", "")
BLOGGER_BLOGS = [
"marketpulse-daily",
"tradertools-hub",
]
BLOG_URL = os.environ.get("BLOG_URL", "https://blog.quant-view.xyz")
TOOLS_URL = f"{BLOG_URL}/tools"
TERMINAL_URL = os.environ.get("TERMINAL_URL", "https://gfil-intel.xyz")
TG_BOT = os.environ.get("TG_BOT_TOKEN", "")
TG_CHAT = os.environ.get("TG_CHANNEL", "@GFIL_Monitor")
# Content topics — rotated daily
TOPICS = [
("gold", "XAUUSD gold trading position size calculator free stop loss risk management",
f"position size pip value fibonacci ATR calculator {TOOLS_URL}/position-size-calculator.html"),
("forex", "forex scalping strategy 2026 lot size calculation risk per trade",
f"pip calculator margin calculator drawdown {TOOLS_URL}/pip-calculator.html"),
("crypto", "BTC ETH crypto trading tools free calculator position sizing",
f"crypto position size compound interest {TOOLS_URL}"),
]
def deepseek(prompt):
"""Generate content via DeepSeek API"""
data = json.dumps({
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a financial markets writer. Write a concise, informative trading article (250-350 words) in natural English. Include practical tips. End with a CTA linking to the free tools. Use the provided URL naturally."},
{"role": "user", "content": prompt}
],
"temperature": 0.8, "max_tokens": 500
}).encode()
req = urllib.request.Request("https://api.deepseek.com/chat/completions", data=data,
headers={"Content-Type": "application/json", "Authorization": f"Bearer {DEEPSEEK_KEY}"})
resp = json.loads(urllib.request.urlopen(req, timeout=45).read())
return resp["choices"][0]["message"]["content"]
def telegraph_post(title, content):
"""Post to Telegraph"""
data = json.dumps({
"access_token": TELEGRAPH_TOKEN,
"title": title,
"content": [{"tag": "p", "children": [content]}],
"return_content": False
}).encode()
req = urllib.request.Request("https://api.telegra.ph/createPage", data=data,
headers={"Content-Type": "application/json"})
resp = json.loads(urllib.request.urlopen(req, timeout=20).read())
if resp.get("ok"):
return resp["result"]["url"]
return None
def blogger_post(blog_name, subject, body):
"""Post to Blogger via SMTP (Gmail)"""
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = BLOGGER_EMAIL
msg['To'] = f"{blog_name}.{random.randint(1000,9999)}@blogger.com"
try:
with smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=30) as s:
s.login(BLOGGER_EMAIL, BLOGGER_PASS)
s.send_message(msg)
return True
except Exception as e:
print(f" Blogger error: {e}")
return False
def tg_notify(text):
"""Send notification to Telegram monitor channel"""
try:
url = f"https://api.telegram.org/bot{TG_BOT}/sendMessage"
data = json.dumps({"chat_id": TG_CHAT, "text": text, "parse_mode": "HTML"}).encode()
urllib.request.urlopen(urllib.request.Request(url, data=data,
headers={"Content-Type": "application/json"}), timeout=10)
except:
pass
# ===== MAIN =====
if __name__ == "__main__":
today = datetime.now().strftime("%Y-%m-%d")
print(f"=== GFIL Light Promotion {today} ===")
# Rotate topics based on day of month
idx = datetime.now().day % len(TOPICS)
topic_key, topic_seo, topic_url = TOPICS[idx]
# 1. Telegraph x2
telegraph_results = []
for i in range(2):
prompt = f"Write a trading article about {topic_seo}. Title should be SEO-optimized for Google. End with: 'Try free tools at {TOOLS_URL}'. Include the link naturally."
try:
content = deepseek(prompt)
# Clean title: strip markdown formatting
raw = content.split('\n')[0]
title = raw.replace('**','').replace('#','').replace('*','').strip()[:120]
# Remove common prefixes from AI response
for prefix in ['Title:','title:','Here is','Here\'s']:
if title.startswith(prefix):
title = title[len(prefix):].strip()
if not title or len(title) < 10:
title = f"Free Trading Tools — {today}"
url = telegraph_post(title, content)
if url:
print(f" Telegraph [{i+1}/2]: {title[:60]}... -> {url}")
telegraph_results.append(url)
else:
print(f" Telegraph [{i+1}/2]: FAILED")
except Exception as e:
print(f" Telegraph [{i+1}/2]: ERROR {e}")
time.sleep(3)
# 2. Blogger x2
blogger_results = []
for i, blog in enumerate(BLOGGER_BLOGS[:2]):
try:
prompt = f"Write a 200-word blog post about free forex/gold trading tools. Include: position size calculator, pip calculator, Fibonacci. Link: {TOOLS_URL}. Make it helpful, not spammy."
body = deepseek(prompt)
# Clean subject line
raw = body.split('\n')[0]
subject = raw.replace('**','').replace('#','').replace('*','').strip()[:80]
for prefix in ['Title:','title:','Here is','Here\'s']:
if subject.startswith(prefix):
subject = subject[len(prefix):].strip()
if not subject or len(subject) < 10:
subject = f"Free Trading Tools — {today}"
if blogger_post(blog, subject, body):
print(f" Blogger [{i+1}/2]: {blog} -> OK")
blogger_results.append(blog)
else:
print(f" Blogger [{i+1}/2]: FAILED")
except Exception as e:
print(f" Blogger [{i+1}/2]: ERROR {e}")
time.sleep(5)
# Report
t_count = len(telegraph_results)
b_count = len(blogger_results)
msg = f"Daily Light: Telegraph {t_count}/2 | Blogger {b_count}/2 | {TOPICS[idx][0]}"
print(msg)
if t_count + b_count < 2:
tg_notify(f"⚠️ {msg}")