Untitled

 avatar
user_2332184
plain_text
2 years ago
2.4 kB
10
Indexable
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 the 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 user profile options
    opt = Options()
    # Make sure to adjust the path to your Chrome profile and WebDriver as necessary
    opt.add_argument(r'user-data-dir=C:\Path\To\User\Data')
    driver = webdriver.Chrome(r'C:\Path\To\chromedriver.exe', options=opt)


    try:
        driver.get(wassup_url)
        time.sleep(20)  # Adjust this delay as needed for the page and chatbox to load
        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:
        # Consider closing the browser after sending the 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('9043050235', '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.")
Editor is loading...
Leave a Comment