import os import requests from getpass import getpass from twilio.rest import Client import gradio as gr from datetime import datetime # TinyURL function def shorten_url(url): try: r = requests.get(f"http://tinyurl.com/api-create.php?url={url}") if r.ok: return r.text return url except: return url # -------------------------------------------------------------------- # Step 1: Load / Input API Keys # -------------------------------------------------------------------- TW_SID = os.environ.get("TWILIO_SID") TW_TOKEN = os.environ.get("TWILIO_TOKEN") GNEWS_KEY = os.environ.get("GNEWS_API_KEY") if not (TW_SID and TW_TOKEN): print("Enter your Twilio credentials:") TW_SID = getpass("Twilio SID: ").strip() TW_TOKEN = getpass("Twilio Auth Token: ").strip() os.environ["TWILIO_SID"] = TW_SID os.environ["TWILIO_TOKEN"] = TW_TOKEN if not GNEWS_KEY: print("Enter your GNews API key (get it from https://gnews.io/):") GNEWS_KEY = getpass("GNews API Key: ").strip() os.environ["GNEWS_API_KEY"] = GNEWS_KEY # -------------------------------------------------------------------- # Step 2: Twilio WhatsApp sender number # -------------------------------------------------------------------- TWILIO_WHATSAPP_FROM = "whatsapp:+14155238886" MAX_CHARS = 1500 # safe limit per WhatsApp message # -------------------------------------------------------------------- # Step 3: Function to fetch and send news (enhanced formatting) # -------------------------------------------------------------------- def send_news(whatsapp_number: str, city: str): city = city.strip() if not city: return "Please enter a valid city." url = f"https://gnews.io/api/v4/search?q={city}&lang=en&country=in&max=15&apikey={GNEWS_KEY}" r = requests.get(url) if not r.ok: return f"Failed to fetch news ({r.status_code}): {r.text}" news_data = r.json().get("articles", []) if not news_data: return f"No news found for {city}." # Prepare messages under character limit messages = [] timestamp = datetime.now().strftime("%Y-%m-%d %H:%M") current_msg = f"📰 *Top News in {city}* (Fetched: {timestamp})\n\n" for i, article in enumerate(news_data, start=1): title = article.get("title", "No title") url = article.get("url", "") short_url = shorten_url(url) line = f"{i}. *{title}* ⚡\n{short_url}\n\n" if len(current_msg) + len(line) > MAX_CHARS: messages.append(current_msg.strip()) current_msg = line else: current_msg += line if current_msg: messages.append(current_msg.strip()) # Prepare WhatsApp number TO = whatsapp_number.strip() if not TO.startswith("whatsapp:"): TO = f"whatsapp:{TO}" client = Client(TW_SID, TW_TOKEN) try: sids = [] for msg_text in messages: msg = client.messages.create(body=msg_text, from_=TWILIO_WHATSAPP_FROM, to=TO) sids.append(msg.sid) return f"Message(s) sent successfully! Message SIDs: {', '.join(sids)}" except Exception as e: return f"Failed to send WhatsApp message: {e}" # -------------------------------------------------------------------- # Step 4: Gradio UI # -------------------------------------------------------------------- with gr.Blocks() as demo: gr.Markdown("## Send latest 15 news of any Tamil Nadu city to WhatsApp") whatsapp_input = gr.Textbox(label="Your WhatsApp number (e.g. +91XXXXXXXXXX)", placeholder="+91XXXXXXXXXX") city_input = gr.Textbox(label="City in Tamil Nadu", placeholder="Coimbatore") send_button = gr.Button("Send News") output = gr.Textbox(label="Status") send_button.click(fn=send_news, inputs=[whatsapp_input, city_input], outputs=output) demo.launch()