#!/usr/bin/env python3
"""
AstroAstayogini.in Integration Script
Direct integration for your astrology website
"""
import requests
import json
from datetime import date, datetime
from scrapers.astrology_com_scraper import AstrologyComScraper
from scrapers.horoscope_com_scraper import HoroscopeComScraper
import time
class AstroAstayoginiIntegrator:
"""Direct integration for astroastayogini.in"""
def __init__(self, wordpress_url=None, username=None, password=None):
"""Initialize with WordPress credentials"""
self.wordpress_url = wordpress_url or "https://astroastayogini.in/wp-json/"
self.username = username
self.password = password
# Initialize scrapers
self.scrapers = {
"astrology.com": AstrologyComScraper(),
"horoscope.com": HoroscopeComScraper(),
}
self.zodiac_signs = [
"aries", "taurus", "gemini", "cancer",
"leo", "virgo", "libra", "scorpio",
"sagittarius", "capricorn", "aquarius", "pisces"
]
def scrape_daily_horoscopes(self):
"""Scrape horoscopes for all signs from multiple sources"""
print(f"Scraping daily horoscopes for {date.today()}")
results = {}
for sign in self.zodiac_signs:
print(f"Processing {sign.title()}...")
results[sign] = {}
for source_name, scraper in self.scrapers.items():
try:
result = scraper.scrape_sign(scraper.base_url, sign)
if result.get('success'):
results[sign][source_name] = {
"prediction": result['prediction'],
"date": result['date'],
"success": True
}
print(f" ā
{source_name}: {len(result['prediction'])} characters")
else:
print(f" ā {source_name}: {result.get('error', 'Unknown error')}")
results[sign][source_name] = {
"error": result.get('error', 'Unknown error'),
"success": False
}
# Rate limiting
time.sleep(1)
except Exception as e:
print(f" ā {source_name}: Exception - {str(e)}")
results[sign][source_name] = {
"error": str(e),
"success": False
}
return results
def create_consolidated_horoscope(self, sign_data):
"""Create a consolidated horoscope from multiple sources (without AI)"""
successful_predictions = []
sources = []
for source, data in sign_data.items():
if data.get('success') and data.get('prediction'):
successful_predictions.append(data['prediction'])
sources.append(source)
if not successful_predictions:
return None
if len(successful_predictions) == 1:
return {
"consolidated": successful_predictions[0],
"sources": sources
}
# Simple consolidation: combine predictions with transitions
consolidated = ""
# Add opening
consolidated += f"The stars align with multiple insights for you today. "
# Add first prediction
consolidated += successful_predictions[0]
if len(successful_predictions) > 1:
# Add transition and second prediction
consolidated += f" Additionally, the cosmic energies suggest that {successful_predictions[1].lower()}"
# Clean up and format
consolidated = consolidated.replace('..', '.').replace(' ', ' ')
return {
"consolidated": consolidated,
"sources": sources
}
def format_for_wordpress(self, sign, consolidated_data, date_str):
"""Format horoscope for WordPress post"""
sign_title = sign.title()
formatted_date = datetime.strptime(date_str, '%Y-%m-%d').strftime('%B %d, %Y')
title = f"{sign_title} Horoscope for {formatted_date}"
content = f"""
{sign_title} Daily Horoscope - {formatted_date}
{consolidated_data['consolidated']}
"""
return {
"title": title,
"content": content.strip(),
"status": "publish",
"categories": [1], # Adjust category ID as needed
"tags": [sign.lower(), "horoscope", "astrology", "daily"],
"excerpt": consolidated_data['consolidated'][:150] + "..."
}
def publish_to_wordpress(self, post_data):
"""Publish horoscope to WordPress"""
if not self.username or not self.password:
return {
"success": False,
"error": "WordPress credentials not configured"
}
try:
url = f"{self.wordpress_url}wp/v2/posts"
response = requests.post(
url,
auth=(self.username, self.password),
json=post_data,
headers={'Content-Type': 'application/json'}
)
if response.status_code in [200, 201]:
post_data = response.json()
return {
"success": True,
"post_id": post_data.get("id"),
"url": post_data.get("link"),
"status": post_data.get("status")
}
else:
return {
"success": False,
"error": f"WordPress API error: {response.status_code}",
"details": response.text
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
def run_daily_update(self):
"""Run complete daily horoscope update for astroastayogini.in"""
print("š Starting daily horoscope update for AstroAstayogini.in")
print("=" * 60)
# Scrape all horoscopes
scraped_data = self.scrape_daily_horoscopes()
# Process each sign
today = date.today().isoformat()
results = {}
for sign in self.zodiac_signs:
print(f"\nProcessing {sign.title()} horoscope...")
sign_data = scraped_data.get(sign, {})
# Create consolidated horoscope
consolidated = self.create_consolidated_horoscope(sign_data)
if not consolidated:
print(f" ā No valid predictions found for {sign}")
results[sign] = {"status": "failed", "error": "No predictions available"}
continue
# Format for WordPress
post_data = self.format_for_wordpress(sign, consolidated, today)
# Publish to WordPress (if credentials provided)
if self.username and self.password:
publish_result = self.publish_to_wordpress(post_data)
if publish_result.get('success'):
print(f" ā
Published to WordPress: {publish_result.get('url')}")
results[sign] = {
"status": "published",
"post_id": publish_result.get('post_id'),
"url": publish_result.get('url')
}
else:
print(f" ā WordPress publish failed: {publish_result.get('error')}")
results[sign] = {
"status": "ready",
"error": publish_result.get('error'),
"content": post_data
}
else:
print(f" ā
Content prepared (WordPress credentials needed for publishing)")
results[sign] = {
"status": "ready",
"content": post_data
}
print("\n" + "=" * 60)
print("DAILY UPDATE SUMMARY")
print("=" * 60)
published = sum(1 for r in results.values() if r.get('status') == 'published')
ready = sum(1 for r in results.values() if r.get('status') == 'ready')
failed = sum(1 for r in results.values() if r.get('status') == 'failed')
print(f"Published: {published}")
print(f"Ready for publishing: {ready}")
print(f"Failed: {failed}")
return results
def main():
"""Main function for testing astroastayogini.in integration"""
print("AstroAstayogini.in Integration Test")
print("=" * 40)
# Initialize integrator
integrator = AstroAstayoginiIntegrator()
# Test with a single sign first
print("Testing with Aries horoscope...")
# Scrape data for Aries
aries_data = {}
for source_name, scraper in integrator.scrapers.items():
try:
result = scraper.scrape_sign(scraper.base_url, "aries")
if result.get('success'):
aries_data[source_name] = {
"prediction": result['prediction'],
"date": result['date'],
"success": True
}
print(f"ā
{source_name}: {len(result['prediction'])} characters")
else:
print(f"ā {source_name}: {result.get('error')}")
except Exception as e:
print(f"ā {source_name}: {str(e)}")
# Create consolidated horoscope
if aries_data:
consolidated = integrator.create_consolidated_horoscope(aries_data)
if consolidated:
print(f"\nā
Consolidated horoscope created:")
print(f"Length: {len(consolidated['consolidated'])} characters")
print(f"Sources: {', '.join(consolidated['sources'])}")
print(f"Preview: {consolidated['consolidated'][:200]}...")
# Format for WordPress
post_data = integrator.format_for_wordpress("aries", consolidated, date.today().isoformat())
print(f"\nā
WordPress post formatted:")
print(f"Title: {post_data['title']}")
print(f"Content length: {len(post_data['content'])} characters")
else:
print("ā Failed to create consolidated horoscope")
else:
print("ā No data available for testing")
if __name__ == "__main__":
main()