示例#1
0
def main():
    #     print(sys.path)
    #     send_gmail.test()
    #     weather_api.test()
    api_key, location = weather_api.get_api_info()
    weather = weather_api.get_weather(api_key, location)

    if weather['cod'] == 200:
        temp = math.ceil(weather['main']['temp'])
        tempMin = math.ceil(weather['main']['temp_min'])
        tempMax = math.ceil(weather['main']['temp_max'])
        msg = []
        subject = '{} weather forcast'.format(weather['name'])
        msg.append('Current temprature: {}°'.format(temp))
        msg.append('Min: {}°'.format(tempMin))
        msg.append('Max: {}°'.format(tempMax))
        l = [w['description'] for w in weather['weather']]
        msg.append('Condition: {}'.format(l))
        message = '\n'.join(msg)
        print(message)

    from_ = '*****@*****.**'
    to = '*****@*****.**'

    service = send_gmail.service_factory()
    wather_message = send_gmail.create_message(from_, to, subject, message)
    send_gmail.send_message(service, 'me', wather_message)
示例#2
0
def weather_report(city: str):
    """
    Program that uses OpenWeatherAPI to read out the weather report of a given city.
    """
    report = get_weather(city)
    alexa = pyttsx3.init()
    alexa.say(report)
    alexa.runAndWait()
示例#3
0
def set_alarms(alarm:dict, s):
    """this function enters the alarms to the scheduler"""
    time = alarm['title'][:10:] + " " + alarm['title'][11::]
    alarm_time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M")
    delay = (alarm_time - datetime.datetime.strptime(str(datetime.datetime.now()).rpartition(':')[0], "%Y-%m-%d %H:%M")).total_seconds()
    if alarm['news'] and alarm['weather']:
        message = alarm['content'] + " - Top news stories - One - " + (get_news()[-1])['name'] + " - two - " + (get_news()[-2])['name'] + " - three - " + (get_news()[-3])['name'] + " - " + get_weather() + " - Covid-19 update - " + get_covid()
    elif alarm['news']:
        message = alarm['content'] + " - Top news stories - One - " + (get_news()[-1])['name'] + " - two - " + (get_news()[-2])['name'] + " - three - " + (get_news()[-3])['name'] + " - Covid-19 update - " + get_covid()
    elif alarm['weather']:
        message = alarm['content'] + " - " + get_weather() + " - Covid-19 update - " + get_covid()
    else:
        message = alarm['content'] + " - Covid-19 update - " + get_covid()
    s.enter(int(delay),1,set_off_alarm,(message,))
    logging.info("Alarm set in set_alarms(): " + message)
示例#4
0
def create_notifications() -> list:
    """this function creates and returns the notifications"""
    logging.info("Notifications returned by create_notifications()")
    notifications = []
    news = get_news()
    counter = len(news)
    for article in news:
        notifications.insert(
            0, {
                "title":
                "News Update " + str(counter),
                "content":
                Markup("<a href=" + article['url'] + ">" + article['name'] +
                       "<\a>")
            })
        counter = counter - 1
    weather = get_weather()
    notifications.insert(0, {"title": "Weather Update", "content": weather})
    covid = get_covid()
    notifications.insert(0, {"title": "Covid-19 Update", "content": covid})
    return notifications
示例#5
0
def save_post(driver_json, user_id, link, likes, location):
    try:
        driver_json.get(f"{link}{config.DATA_TO_JSON}")
        data = json.loads(
            BeautifulSoup(driver_json.page_source,
                          'html.parser').find('body').get_text())
        full_post = data["graphql"]["shortcode_media"]
        post = {
            "user_id":
            user_id,
            "link":
            link,
            "caption":
            full_post["edge_media_to_caption"]["edges"][-1]["node"]["text"]
            [:255],
            "likes":
            full_post["edge_media_preview_like"]["count"],
            "comments":
            full_post["edge_media_to_parent_comment"]["count"],
            "is_video":
            full_post["is_video"],
            "views":
            full_post["video_view_count"]
            if "video_view_count" in full_post else None,
            "temperature":
            None,
            "weather":
            None,
            "timestamp":
            full_post["taken_at_timestamp"]
        }

        # if there is a location let's add it
        full_location = full_post["location"]
        location_id = None
        if full_location:
            address = json.loads(full_location["address_json"]
                                 ) if full_location["address_json"] else None
            location = {
                "name":
                full_location["name"],
                "slug":
                full_location["slug"],
                "country":
                address["country_code"] if address else None,
                "city":
                address["city_name"]
                if address and len(address["city_name"]) > 0 else None
            }
            # Getting Geo location from google API
            geo_address = f"{location['city']}, {location['country']}"
            lat, lon = weather_api.google_geo(geo_address)
            location["latitude"] = lat
            location["longitude"] = lon
            # Getting weather from open weather API
            temperature, weather = weather_api.get_weather(
                lat, lon, post["timestamp"])
            post["temperature"] = temperature
            post["weather"] = weather

            location_id = db.add_location(location)

        # We save the post
        post_id = db.add_post(user_id, post)

        # If there is a location we save the aux table entry
        if location_id:
            db.add_post_location(post_id, location_id)

        return post_id
    except json.decoder.JSONDecodeError as ex:
        print(ex)
        post_id = db.add_simple_post(user_id, link, likes)
        if location:
            location_id = db.add_simple_location(location)
            db.add_post_location(post_id, location_id)
        return post_id
示例#6
0
def interests(bot, update, user_data):
    global location

    message = update.message.text.lower()
    if message == 'сменить город':
        return 1

    elif message == 'погода':
        _weather = get_weather(user_data['locality'])

        gr = morph.parse('градус')[0]
        degrise = str(_weather[0]['temp']) + ' ' + gr.make_agree_with_number(
            abs(int(_weather[0]['temp']))).word
        degrise1 = str(
            _weather[0]['feels_like']) + ' ' + gr.make_agree_with_number(
                abs(int(_weather[0]['feels_like']))).word
        date = _weather[0]['date']
        osh = _weather[0]['condition']

        mes = "Погода на {}.\nТемпература {}(ощущается как {}), {}".format(
            date, degrise, degrise1, osh)
        _1 = update.message.reply_text(mes, reply_markup=inline_keyboard_1)
        weather[_1.message_id] = [_weather, 0]

        return 2

    elif message in places:
        update.message.reply_text("Начинаю поиск...")

        _1 = 8  # choice(range(3, len(places[message]+1)))

        datas = []
        _text = []

        random_places = []

        for _ in range(len(places[message]), 0, -1):
            random_place = choice(places[message])
            while True:
                if random_place not in random_places:
                    break
                random_place = choice(places[message])

            result = search(user_data['locality'], random_place, _1)
            # print('Результат поиска: ', result)
            for _ in result:
                data = _[0]
                coord = _[1]

                if data not in datas:
                    static_api_request = "http://static-maps.yandex.ru/1.x/?ll={}&l=map&z=15&pt={},pm2blywm1".format(
                        coord, coord)
                    # print('Информация прошла проверку: ', data)
                    _text.append('[Картинка.]({})\n{} ({})'.format(
                        static_api_request, data, random_place))
                    datas.append(data)

        markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
        shuffle(_text)

        _text = cycle(_text)
        _return = update.message.reply_text(next(_text),
                                            reply_markup=inline_keyboard)
        location[_return.message_id] = _text
        update.message.reply_text("Выберите сферу которая вас интересует",
                                  reply_markup=markup)

        return 2

    else:
        return 2