Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
3
Indexable
Never
pip install requests selenium

import os
import requests
import json
import datetime as dt
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time

api_key = os.getenv('OPENWEATHERMAP_API')

def rain_today(location):
    # get API key from env variable
    api_key = os.getenv('OPENWEATHERMAP_API')
    if not api_key:
        print("API key for OpenWeatherMap is not set.")
        return False

    # API endpoint
    url = f'https://api.openweathermap.org/data/2.5/forecast?q={location}&units=metric&appid={api_key}'

    r = requests.get(url)
    if r.status_code != 200:
        print(f"Failed to retrieve weather data: {r.status_code}")
        return False

    data = json.loads(r.text)
    
    today = dt.datetime.now().date()
    rain = False
    for d in data['list']:
        temp_dt = dt.datetime.fromtimestamp(d['dt'])
        if temp_dt.date() == today:
            main_weather = d['weather'][0]['main']
            if main_weather.lower() == 'rain':
                rain = True
                break
    return rain

def send_whatsapp(phone_number, msg):
    # Whatsapp URL with phone number and message
    wassup_url = f'https://web.whatsapp.com/send?phone={phone_number}&text={msg}&type=phone_number&app_absent=0'

    # Chrome webdriver and profile options
    opt = Options()
    opt.add_argument(r'user-data-dir=C:\Users\iangrne\AppData\Local\Google\Chrome\User Data\Selenium')
    driver = webdriver.Chrome(r'C:\Users\iangrne\downloads\chromedriver.exe', options=opt)


    try:
        driver.get(wassup_url)
        time.sleep(20)  # Adjust as needed
        chatbox = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[2]')
        chatbox.send_keys(msg)
        time.sleep(0.1)
        chatbox.send_keys(Keys.RETURN)
    except Exception as e:
        print(e)
    finally:
        # Close browser after sending message
        time.sleep(10)  # Wait for message to be sent
        driver.quit()

# Example Usage
location = 'Ponte Vedra Beach, FL'
if rain_today(location):
    send_whatsapp('19043050235', 'It is going to rain today in Ponte Vedra Beach. Remember to bring an umbrella!')
else:
    print("No rain forecasted today in Ponte Vedra Beach.")
Leave a Comment