File size: 3,889 Bytes
229ce91
 
5e29814
229ce91
 
 
 
5e29814
 
 
 
 
 
 
 
 
 
229ce91
5e29814
229ce91
 
 
 
 
5e29814
 
 
 
 
 
 
 
 
 
 
229ce91
 
5e29814
229ce91
 
 
 
 
5e29814
229ce91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77de0ff
 
 
229ce91
77de0ff
 
5e29814
 
 
77de0ff
 
 
 
 
 
 
229ce91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e29814
229ce91
 
5e29814
229ce91
 
 
 
 
 
 
5e29814
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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()