import pyowm owm = pyowm.OWM('6bfdea88e336b11188629e654d5012fa') dir(owm) see = owm.weather_at_place('Hong Kong') dir(see) wth = see.get_weather() dir(wth) jukai = wth.get_humidity() print(jukai) print("The humudity in Hong Kong, at the moment, is " + str(jukai))
import random from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os import time import pyttsx3 import speech_recognition as sr import pytz import subprocess import webbrowser import pyowm import config owm = pyowm.OWM("0c7cb189167666cb7ffbbe3906203557") def speak(text): engine = pyttsx3.init() engine.say(text) engine.runAndWait() def get_audio(): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) said = "" try:
import pyowm myOwm = pyowm.OWM("dbf6aaf008f3591e4eeb64257fd2d985") location = 'Oslo, Norway' myWeather = myOwm.weather_at_place(location) print(myWeather.get_weather().get_humidity()) print(myWeather.get_weather().get_temperature('celsius')) #print(myWeather.get_weather().get_sunset())
import pyowm from api_key import API_KEY owm = pyowm.OWM(API_KEY) mgr = owm.weather_manager() obs = mgr.weather_at_coords(lat=48.853409, lon=2.3488) weather = obs.weather temperature = weather.temperature(unit='fahrenheit')['temp'] print(f'The temperature is {temperature} degrees Fahrenheit.')
import pyowm from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = pyowm.OWM('API', config_dict) mgr = owm.weather_manager() place = input('Введите город: ') observation = mgr.weather_at_place(place) w = observation.weather.detailed_status temp_dict_celsius = observation.weather.temperature('celsius')['temp'] wind_dict_in_meters_per_sec = observation.weather.wind()['speed'] print('В городе ' + place + ' сейчас ' + w + ', температура ' + str(round(temp_dict_celsius)) + ' градусов по Цельсию, ветер ' + str(wind_dict_in_meters_per_sec) + ' м/c.') if temp_dict_celsius < 10: print('Одевай тёплую ветровку и брюки!') elif temp_dict_celsius >= 10 and temp_dict_celsius <= 20: print('Одевай лёгкую ветровку и лёгкие штаны!') elif temp_dict_celsius > 20: print('Одевай футболку и лёгкие брюки или шорты: на улице тепло!') print('Нажми любую кнопку, чтобы завершить работы программы!') input()
import pyowm import telebot from PIL import Image from PIL import ImageFont from PIL import ImageDraw from telebot import types admins = [412422372] users_id_file = 'users.txt' bot = telebot.TeleBot("") # Создание объекта бота owm = pyowm.OWM('bbc3649126d17d7bb4111c44c6a562d5', language="ru") # Объект owm print("Бот запущен") def keyboard(): markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) button1 = types.KeyboardButton('Вк') # как кнопка занывается button2 = types.KeyboardButton('Погода') # как кнопка называется button3 = types.KeyboardButton('Админ') markup.add(button1) # добавляем 1 кнопку markup.add(button2) # добавляем 2 кнопку markup.add(button3) return markup @bot.message_handler(commands=[ 'start' ]) # Декоратор на команды start и хелп. Срабатывает когда пишут их def send_welcome(message): #вот тут подключаем клаву(с команды старт)
key = os.environ['OPENWEATHER_API_KEY'] except (EmptyValue, KeyError): exit('Undefined environment variable OPENWEATHER_API_KEY.') except InvalidFormat: exit(f'This doesn\'t look like valid API key: {key}') try: city = os.environ['CITY_NAME'] if len(city) == 0: raise EmptyValue('Environment varialbe CITY_NAME is empty.') except KeyError: exit('Undefined environment variable CITY_NAME.') owm = pyowm.OWM(key) if owm.is_API_online(): observation = owm.weather_at_place(city) location = observation.get_location().get_name() weather = observation.get_weather() description = weather.get_detailed_status() temperature = weather.get_temperature()['temp'] humidity = weather.get_humidity() print(f'source=openweathermap,' ' city="{city}",' ' description="{description}",' ' temp={temperature},' ' humidity={humidity}') else: exit('API not online.')
import pyowm from os import getenv api_key = getenv('OPENWEATHER_API_KEY', 'REPLACE_THIS_WITH_THE_ACTUAL_API_KEY') city_name = getenv('CITY_NAME', 'Zagreb') # Make sure that the variables aren't empty if getenv('CITY_NAME') == "": city_name = 'Zagreb' if getenv('OPENWEATHER_API_KEY') == "": api_key = 'REPLACE_THIS_WITH_THE_ACTUAL_API_KEY' if api_key != 'REPLACE_THIS_WITH_THE_ACTUAL_API_KEY': owm = pyowm.OWM(api_key) owm_city = owm.weather_at_place(city_name) weather = owm_city.get_weather() temperature = weather.get_temperature('celsius')['temp'] humidity = weather.get_humidity() status = weather.get_detailed_status() output = ('source=openweathermap, city="{}", description="{}", ' 'temp={}, humidity={}').format(city_name, status, temperature, humidity) print(output) else: print("API key variable not set, skipping weather check.")
# bot.remove_webhook() # bot.set_webhook(url=url) states = {'start': 1, 'init': 2, 'query': 3, 'add': 4, 'city': 5, 'del': 6} markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True) itembtn1 = telebot.types.KeyboardButton('Получить список одежды') itembtn2 = telebot.types.KeyboardButton('Добавит предмет в гардероб') itembtn3 = telebot.types.KeyboardButton('Удалить предмет') itembtn4 = telebot.types.KeyboardButton('Установить город') itembtn5 = telebot.types.KeyboardButton('Подобрать одежду на сегодня') markup.row(itembtn1, itembtn2) markup.row(itembtn3, itembtn4) markup.row(itembtn5) owm = pyowm.OWM('370baafacdbb4a1468e5cef4e6c46a5e') @app.route('/' + secret, methods=['POST']) def webhook(): update = telebot.types.Update.de_json( request.stream.read().decode('utf-8')) bot.process_new_updates([update]) return 'ok', 200 @bot.message_handler(commands=['start']) def start(message): user = User.query.filter(User.id == message.chat.id).first() if user is None: user = User(message.chat.id, message.chat.username)
import pyowm owm = pyowm.OWM('2a62786782ef789a0ca6137cd3f912ef') def get_weather(): observation = owm.weather_at_coords(12.824732, 80.045154) weather = observation.get_weather() return weather def get_temperature(): weather = get_weather() return (weather.get_temperature('celsius')['temp'], weather.get_humidity())
def get_record(): owm = pyowm.OWM('c3535d8ffea52c2766f8333a9a3c7640') # Valid API key # Get current date current_date = datetime.now().date() # Get current hour and minute time = datetime.strptime(str(datetime.now().time()), '%H:%M:%S.%f') hour_minute = str(time.hour).zfill(2) + ':' + str(time.minute).zfill(2) cities_dict = { 'Barcelona': { 'apiId': '6356055', 'country': 'Spain' }, 'Geneve': { 'apiId': '2660646', 'country': 'Switzerland' }, 'Lausanne': { 'apiId': '7286283', 'country': 'Switzerland' }, 'Thun': { 'apiId': '2658377', 'country': 'Switzerland' }, 'Interlaken': { 'apiId': '2660253', 'country': 'Switzerland' }, 'Lauterbrunnen': { 'apiId': '7286285', 'country': 'Switzerland' }, 'Lucerne (Luzern)': { 'apiId': '7286409', 'country': 'Switzerland' }, 'Zurich': { 'apiId': '2657896', 'country': 'Switzerland' }, 'Neuhausen am Rheinfall': { 'apiId': '7286627', 'country': 'Switzerland' }, 'Innsbruck': { 'apiId': '2775220', 'country': 'Austria' }, 'Hall in Tirol': { 'apiId': '7873622', 'country': 'Austria' }, 'Salzburg': { 'apiId': '2766824', 'country': 'Austria' }, 'Morzg (Hellbrunn)': { 'apiId': '7286283', 'country': 'Austria' }, 'Vienna': { 'apiId': '2761369', 'country': 'Austria' } } # User-sorted list cities_list = [ 'Barcelona', 'Geneve', 'Lausanne', 'Thun', 'Interlaken', 'Lauterbrunnen', 'Lucerne (Luzern)', 'Zurich', 'Neuhausen am Rheinfall', 'Innsbruck', 'Hall in Tirol', 'Salzburg', 'Morzg (Hellbrunn)', 'Vienna' ] weather_record_writer = csv.writer(open(RESULT_FILE, 'a')) for city in cities_list: city_values = cities_dict.get(city) obs = owm.weather_at_id(int(city_values['apiId'])) w = obs.get_weather() weather_record_writer.writerow([ current_date, hour_minute, city_values['country'], city, w.get_detailed_status(), w.get_temperature(unit='celsius')['temp'], w.get_temperature(unit='celsius')['temp_max'], w.get_temperature(unit='celsius')['temp_min'], w.get_humidity(), w.get_wind()['speed'], get_summer_timezone_time(w.get_sunrise_time('iso')), get_summer_timezone_time(w.get_sunset_time('iso')) ]) open(RESULT_FILE).close()
import random import pyowm import telebot import datetime import time import requests from bs4 import BeautifulSoup owm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc', language='ru') bot = '' #=================== # Weather showing == #=================== @bot.message_handler(commands=['weather_now']) def send_weather(message): observation = owm.weather_at_place('Kyiv') forecast = owm.three_hours_forecast('Kyiv') w = observation.get_weather() temp = round(w.get_temperature('celsius')["temp"]) now = datetime.datetime.now() answer = 'Сегодня: ' + str(now.strftime("%d.%m.%Y")) + ', время: ' + str(now.strftime('%H:%M')) + '\n' + "В Киеве сейчас " + w.get_detailed_status() + ", " + str(temp) + "°" bot.send_message(message.chat.id, answer) #========================================================= # Shows air pollution level, air pressure, and humidity == #========================================================= @bot.message_handler(commands=['check_air']) def check_air(message): headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15'}
def getTemp(): global temp w = pyowm.OWM('c7df50e0e8a98cd81fe2c7ba38966bd6').weather_around_coords( 12.8888509, 77.6102861, limit=1)[0].get_weather() temp = w.get_temperature('celsius')['temp'] writeCache()
def __init__(self, settings): self._cfg = settings["weather"] self._owm = pyowm.OWM(self._cfg["API_key"])
def post_facebook_message(fbid, recevied_message): request = ai.text_request() request.query = recevied_message intent_Name = '' warm_weather = 'The temperature is high right now , make sure to wear something light & dont go out in the sun much !' cold_weather = 'The temperature is low right now , make sure to wear heavy clothes to keep you warm ! ' response = json.loads(request.getresponse().read().decode( 'utf-8')) #getting the response from the agent. responseStatus = response['status']['code'] if (responseStatus == 200): print("Bot response", response['result']['fulfillment']['speech']) try: intent_Name = response['result']['metadata']['intentName'] except: reply = ' ' if (intent_Name == 'Current-weather'): try: input_city = response['result']['parameters']['geo-city'] owm = pyowm.OWM('5124e78e5d11b3dad24c4cf0a3b4ba4f') observation = owm.weather_at_place(input_city) w = observation.get_weather() curr_temp = str(w.get_temperature('celsius')['temp']) max_temp = str(w.get_temperature('celsius')['temp_max']) min_temp = str(w.get_temperature('celsius')['temp_min']) if (float(curr_temp) > 33): reply = response['result']['fulfillment'][ 'speech'] + curr_temp + ' celsius' + ' it has a high of ' + max_temp + ' C' + ' and a low of ' + min_temp + ' C' + '\n' + warm_weather elif (float(curr_temp) < 17): reply = response['result']['fulfillment'][ 'speech'] + curr_temp + ' celsius' + ' it has a high of ' + max_temp + ' C' + ' and a low of ' + min_temp + ' C' + '\n' + cold_weather else: reply = response['result']['fulfillment'][ 'speech'] + curr_temp + ' celsius' + ' it has a high of ' + max_temp + ' C' + ' and a low of ' + min_temp + ' C' except: reply = 'Something wrong happened , please try again' else: reply = response['result']['fulfillment']['speech'] else: reply = 'I didnt understand what you mean , please ask again' post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=EAACuhUNoWHcBAGU6YC1DqIvesUQhDOcL9axSMVzEmgzBNmxmWAlbyrbUxJDls6GtwSjwxbQUZBwu5e8gejTRpT3V6Ag4TZAYtCUT9ZBS3yWXyazjqgJooqNHqsZCd4ZAFbx6oWZCT2M5y2AoZAm58oc0uiGHWGgGixmj7NmCYT8YwZDZD' response_msg = json.dumps({ "recipient": { "id": fbid }, "message": { "text": reply } }) status = requests.post(post_message_url, headers={"Content-Type": "application/json"}, data=response_msg) pprint(status.json())
logging.basicConfig(level=logit.LOG_LEVEL_NUM) logger = logging.getLogger(__name__) logger.logit('Creating and initializing Bot') # Robit's Slack BOT ID, BOT_TOKEN, and Weather API ID as environment variables BOT_ID = os.environ.get("BOT_ID") OWM_ID = os.environ.get("OWM_ID") OBISITE = os.environ.get("OBISITE") # instantiate Slack client slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) # instantiate Open Weather Map object # see http://openweathermap.org/appid to get free Weather API owm = pyowm.OWM(OWM_ID) logger.logit('Setting Weather API...') # Load list of cities available in OWM (list downloaded from site) # http://sustainablesources.com/resources/country-abbreviations/ # http://bulk.openweathermap.org/sample/city.list.json.gz with open('city.list.json') as data_file: data = json.load(data_file) logger.debug('Number of cities available: %s', len(data)) logger.debug('Data example= %s', data[0]) # cities = {} # countryset = set() # for cities in data:
#import giphypop #g = giphypop.Giphy() #results = [x for x in g.search('cake')] from giphypop import translate import dialogflow_v2 as dialogflow dialogflow_session_client = dialogflow.SessionsClient() PROJECT_ID = "newsbot-qlpqub" # https://console.dialogflow.com/api-client/#/editAgent/9db1e3db-93e1-4a18-acf4-20cb206238cc/ from gnewsclient import gnewsclient client = gnewsclient.NewsClient(max_results=3) import pyowm owm = pyowm.OWM('6f6d5f66162ddf2c5f83c5a0eb975eeb') def get_weather(parameters): print("*************************************************") print("PARAMETRES : ", parameters) print("*************************************************") print("*************************************************") city = parameters.get('geo-city') if city == '': lis = ["Not found"] #country=parameters.get('geo-country') else: observation = owm.weather_at_place(city) w = observation.get_weather() wind = w.get_wind()
import pyowm apiKey = '2cac2a2f1a4907ada47ba637b9c3686f' #apiKey = 'bf45390a352169d3a24e4ea5363c3c49' owm = pyowm.OWM(apiKey) #observation = owm.weather_at_place('London,uk') obs1 = owm.weather_at_place('Hong Kong,china') obs2 = owm.weather_at_place('Tokyo,japan') #w = observation.get_weather() w = obs1.get_weather() p = obs2.get_weather() w.get_reference_time() print(w.get_reference_time()) print(w.get_reference_time(timeformat='date')) print(w.get_clouds()) print(w.get_rain()) print(w.get_snow()) print(w.get_wind()) print(w.get_humidity()) print(w.get_status()) if w.get_humidity() > p.get_humidity(): print("Humidity in Hong Kong China high compared to Tokyo Japan ") elif p.get_humidity() > w.get_humidity(): print("Humidity in Tokyo Japan is high compared to Hong Kong,China")
from colorama import init from colorama import Fore, Back, Style import pyowm init() print(Fore.BLACK) print(Back.CYAN) owm = pyowm.OWM('7c9f41e4faf7b9046a78088c174938b8', language="ru") def check_city(place): try: observation = owm.weather_at_place(place) w = observation.get_weather() temp = w.get_temperature('celsius')["temp"] print(Back.YELLOW) print("В городе " + place + " сейчас " + w.get_detailed_status()) print(Back.RED) print("Температура сейчас в районе " + str(temp) + "градусов") except pyowm.exceptions.api_response_error.NotFoundError: print("Вы ввели не правильный город ") check_city(input("Введите город? ")) input()
import os import time import json import datetime from slackclient import SlackClient import pyowm import nltk from nltk import word_tokenize, pos_tag, ne_chunk BOT_NAME = 'weatherbot' SLACK_BOT_TOKEN = 'SLACK TOKEN' # got off of slack page owm = pyowm.OWM( 'Open Weather Map Token' ) # available after creating account at https://home.openweathermap.org slack_client = SlackClient(SLACK_BOT_TOKEN) api_call = slack_client.api_call("users.list") if api_call.get('ok'): # retrieve all users so we can find our bot users = api_call.get('members') for user in users: if 'name' in user and user.get('name') == BOT_NAME: print("Bot ID for '" + user['name'] + "' is " + user.get('id')) BOT_ID = user.get('id') print('loop completed') else: print("could not find bot user with the name " + BOT_NAME) # starterbot's ID as an environment variable
#!/usr/bin/python import pyowm from paho.mqtt.client import Client from time import sleep mqtt = Client() mqtt.connect("localhost", 50001, 60) sleep(.3) k = "2d19784349d26a0853b4c54397d7ff07" owm = pyowm.OWM(k) observation = owm.weather_at_place('Cleveland, US') w = observation.get_weather() temperature = w.get_temperature('fahrenheit')['temp_min'] print "looks like it's going to get down to {} ".format(temperature) mqtt.publish("/devices/b827eb679fe8/sparti/weather/temperature", payload=temperature) sleep(.3) if temperature < 50: print "It is going to be cold!" mqtt.publish("/devices/b827eb679fe8/sparti/weather/cold", payload="1") sleep(.3) else: print "It's going to be warm" mqtt.publish("/devices/b827eb679fe8/sparti/weather/cold", payload="0") sleep(.3)
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) #Home page today = date.today().strftime("%b-%d-%Y") self.home_date.setText(_translate("MainWindow", today)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.home_tab), _translate("MainWindow", "Home")) #Current Status page #Add API key owm = pyowm.OWM('xxxxx') #obtain weather manager weather_mgr = owm.weather_manager() #declare location loc = weather_mgr.weather_at_place('Ottawa,CA') #obtain data weather = loc.weather #weather object temp = weather.temperature(unit='celsius') #temperature temp_min = temp['temp_min'] temp_max = temp['temp_max'] wind_speed = weather.wind()['speed'] #wind speed sunrise = weather.sunrise_time(timeformat='date') - timedelta( hours=4) #sunrise time sunset = weather.sunset_time(timeformat='date') - timedelta( hours=4) #sunset time self.title.setText(_translate("MainWindow", "Current Forcast")) self.status.setText( _translate("MainWindow", f"Status: {weather.detailed_status}")) self.min_temp.setText(_translate("MainWindow", f"Min Temp: {temp_min}")) self.max_temp.setText(_translate("MainWindow", f"Max Temp: {temp_max}")) self.wind.setText(_translate("MainWindow", f"Wind: {wind_speed}m/s")) self.sunrise.setText(_translate("MainWindow", f"Sunrise: {sunrise}")) self.sunset.setText(_translate("MainWindow", f"Sunset: {sunset}")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.status_tab), _translate("MainWindow", "Current Status")) #Weather page #obtain data forecast_3h = weather_mgr.forecast_at_place( 'Ottawa,CA', '3h').forecast #forcast in 3h intervals (5 days) day_0 = datetime.today().date() - timedelta(hours=4) day_1 = day_0 + timedelta(days=1) - timedelta(hours=4) day_2 = day_0 + timedelta(days=2) - timedelta(hours=4) day_3 = day_0 + timedelta(days=3) - timedelta(hours=4) day_4 = day_0 + timedelta(days=4) - timedelta(hours=4) #sorting items __sortingEnabled = self.listWidget.isSortingEnabled() self.listWidget.setSortingEnabled(False) self.listWidget.setSortingEnabled(__sortingEnabled) __sortingEnabled = self.listWidget_2.isSortingEnabled() self.listWidget_2.setSortingEnabled(False) self.listWidget_2.setSortingEnabled(__sortingEnabled) __sortingEnabled = self.listWidget_3.isSortingEnabled() self.listWidget_3.setSortingEnabled(False) self.listWidget_3.setSortingEnabled(__sortingEnabled) __sortingEnabled = self.listWidget_4.isSortingEnabled() self.listWidget_4.setSortingEnabled(False) self.listWidget_4.setSortingEnabled(__sortingEnabled) __sortingEnabled = self.listWidget_5.isSortingEnabled() self.listWidget_5.setSortingEnabled(False) self.listWidget_5.setSortingEnabled(__sortingEnabled) index = 0 day = 0 last_day = day_0 for forcast in forecast_3h: currentday = forcast.reference_time('date') - timedelta(hours=4) if last_day != currentday.date(): last_day = currentday.date() index = 0 day += 1 if day == 0: item = self.listWidget.item(index) item.setText( _translate( "MainWindow", f"{currentday.time()} - {forcast.detailed_status}")) elif day == 1: item = self.listWidget_2.item(index) item.setText( _translate( "MainWindow", f"{currentday.time()} - {forcast.detailed_status}")) elif day == 2: item = self.listWidget_3.item(index) item.setText( _translate( "MainWindow", f"{currentday.time()} - {forcast.detailed_status}")) elif day == 3: item = self.listWidget_4.item(index) item.setText( _translate( "MainWindow", f"{currentday.time()} - {forcast.detailed_status}")) elif day == 4: item = self.listWidget_5.item(index) item.setText( _translate( "MainWindow", f"{currentday.time()} - {forcast.detailed_status}")) index += 1 self.date_1.setText(_translate("MainWindow", f"{day_0}")) self.date_2.setText(_translate("MainWindow", f"{day_1}")) self.date_3.setText(_translate("MainWindow", f"{day_2}")) self.date_4.setText(_translate("MainWindow", f"{day_4}")) self.date_5.setText(_translate("MainWindow", f"{day_3}")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.weather_tab), _translate("MainWindow", "Weather")) #Notes page self.pushButton.setText(_translate("MainWindow", files[0])) self.pushButton_2.setText(_translate("MainWindow", files[1])) self.pushButton_3.setText(_translate("MainWindow", files[2])) self.pushButton.clicked.connect(self.openFile) self.pushButton_2.clicked.connect(self.openFile_1) self.pushButton_3.clicked.connect(self.openFile_2) self.tabWidget.setTabText(self.tabWidget.indexOf(self.note_tab), _translate("MainWindow", "Notes"))
from dotenv import load_dotenv load_dotenv(dotenv_path="./.env") from adafruitio import ioclient OWM_API_KEY = os.getenv("OWM_API_KEY") ADAFRUIT_IO_OUTSIDE_TEMP_FEED_NAME = os.getenv( "ADAFRUIT_IO_OUTSIDE_TEMP_FEED_NAME") ADAFRUIT_IO_OUTSIDE_HUMID_FEED_NAME = os.getenv( "ADAFRUIT_IO_OUTSIDE_HUMID_FEED_NAME") ADAFRUIT_IO_OUTSIDE_SUNLIGHT_HOURS_FEED_NAME = os.getenv( "ADAFRUIT_IO_OUTSIDE_SUNLIGHT_HOURS_FEED_NAME") ADAFRUIT_IO_OUTSIDE_CLOUDCOVER_FEED_NAME = os.getenv( "ADAFRUIT_IO_OUTSIDE_CLOUDCOVER_FEED_NAME") owm = pyowm.OWM(OWM_API_KEY) while True: observation = owm.weather_at_place('Portland,OR,USA') weather = observation.get_weather() humidity = weather.get_humidity() temperature = weather.get_temperature('celsius')['temp'] sunlightHours = ( (weather.get_sunset_time() - weather.get_sunrise_time()) / 60) / 60 # weather.get_rain() cloudCover = weather.get_clouds() ioclient.publish(ADAFRUIT_IO_OUTSIDE_TEMP_FEED_NAME, temperature) ioclient.publish(ADAFRUIT_IO_OUTSIDE_HUMID_FEED_NAME, humidity) ioclient.publish(ADAFRUIT_IO_OUTSIDE_SUNLIGHT_HOURS_FEED_NAME, sunlightHours) ioclient.publish(ADAFRUIT_IO_OUTSIDE_CLOUDCOVER_FEED_NAME, cloudCover)
import requests as requests from covid import Covid import json import pyowm # open weathermap api key weatherkey = '466637f3807d5d9bb00fccfba2185dee' owm = pyowm.OWM(weatherkey) covid = Covid() # url for telegram bot url = "https://api.telegram.org/bot1200959445:AAH5rwX_74Z5H6Zdac9u0W-T3T5vV77voVU/" # create func that get chat id def get_chat_id(update): chat_id = update["message"]["chat"]["id"] return chat_id # function to get message text def get_message_text(update): message_text = update["message"]["text"] return message_text # function to get last update def last_update(req): response = requests.get(req + "getUpdates") response = response.json()
''' https://stackoverflow.com/questions/1474489/python-weather-api http://openweathermap.org/appid ''' import pyowm owm = pyowm.OWM( '698d67c5bed3089c18e103c453c2a698') # You MUST provide a valid API key #observation = owm.weather_at_place('London,uk') observation = owm.weather_at_place('Brisbane,au') w = observation.get_weather() print(type(w), w) wind = w.get_wind() print(type(wind), wind, wind['speed'], wind['deg']) humidity = w.get_humidity() print(type(humidity), humidity) temp = w.get_temperature('celsius') print(type(temp), temp, temp['temp']) weatherReport = "the wind is " + str(wind['speed']) + " km/hr from " + str( wind['deg']) + " degrees." weatherReport += " The temperature is " + str(temp['temp']) weatherReport += " The humidity is " + str(humidity) print(weatherReport)
def handle(msg): content_type, chat_type, chat_id = telepot.glance(msg) file_id = "" chat_id = msg['chat']['id'] command = "" user = "" if (content_type == "text"): chat_id = msg['chat']['id'] command = msg['text'] print("in text mode") user = msg['from']['first_name'] print("Got command: %s" % command) if command == 'time': bot.sendMessage(chat_id, str(datetime.datetime.now())) #determining reply message based on the hourof day elif command == 'Hi' or command == 'hi' or command == 'HI' or command == 'hI': #Hi Query replyMessage = "Hi " + user + " " greeting = "It is sleeping time you still awake" hour = int( datetime.datetime.strftime(datetime.datetime.now(), '%H')) #print(hour) if (hour >= 4 and hour < 12): greeting = "Good Morning" elif (hour >= 12 and hour < 16): greeting = "Good Afternoon" elif (hour >= 16 and hour < 20): greeting = "Good Evening" replyMessage = replyMessage + greeting bot.sendMessage(chat_id, replyMessage) #gives various details of raspberry pi elif command.lower() == "How are you".lower(): #Health Query print("In Health Query") cpu_temparature = get_cpu_temparature() cpu_usage = psutil.cpu_percent() ram = psutil.virtual_memory() ram_total = ram.total / 2**20 # MiB. ram_used = ram.used / 2**20 ram_free = ram.free / 2**20 ram_percent_used = ram.percent disk = psutil.disk_usage('/') disk_total = disk.total / 2**30 # GiB. disk_used = disk.used / 2**30 disk_free = disk.free / 2**30 disk_percent_used = disk.percent message = "I am doing as \nCPU Temparature " + str( cpu_temparature) + "C \nCPU Usage " + str( cpu_usage) + " \nRam Percent Used " + str( ram_percent_used) + " \nFree Disk Space " + str( disk_free) + "Gb" bot.sendMessage(chat_id, message) #sends the local ip address and the wifi name to which it is connected to elif command.lower() == "Where are you".lower(): print("telling where am I") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((ConfigParams.google_domain, 80)) ipaddr = s.getsockname()[0] wifi = Wireless('wlan0') wifiname = wifi.getEssid() message = "I am connected on " + ipaddr + " \nto WiFi " + wifiname bot.sendMessage(chat_id, message) elif command.lower() == "coming up cricket": print("fetching upcoming matches") #if below command is cricket then it will fetch scrores from cricbuzz page elif command.lower() == "cricket".lower(): print("Fetching Cricket Scores ...") page = requests.get(ConfigParams.crc_buzz_url) tree = html.fromstring(page.content) #searching for required data allscoreslist = tree.xpath(ConfigParams.cric_buzz_path) allscores = [] #for loop used to remove duplicate values may override actual existing values some time #todo for score in allscoreslist: if score not in allscores: allscores.append(score) message = "" teamscores = [] #formatting data received for readability for score in allscoreslist: if score[0].isdigit(): message = message + (score + "\n") else: if len(score) > 6: score = score + "\n" message = message + score message = message + "**************" + "\n" if message not in teamscores: teamscores.append(message) message = "" else: print("Met matching values") message = "" else: message = message + (score + "\t") bot.sendMessage(chat_id, "".join(teamscores)) #used for downloading files uploaded to this bot elif command.lower().find("download") != -1: if command.split(".")[1] == "jpg" or command.split( ".")[1] == "jpeg" or command.split(".")[1] == "png": try: filename = '/home/pi/Scripts/photos/' + command.split( " ")[1] document = open(r'/home/pi/Scripts/photos/' + command.split(" ")[1]) except IOError: bot.sendMessage(chat_id, "File not found") else: try: filename = '/home/pi/Scripts/documents/' + command.split( " ")[1] document = open(r'/home/pi/Scripts/documents/' + command.split(" ")[1]) except IOError: bot.sendMessage(chat_id, "File not found") bot.sendDocument(chat_id, document) #if message contains stocks key word then it tries to fetch company and sends to get nse stock code to get current price elif command.lower().split(":")[0] == "stocks": #variable for storing variable name company = command.split(":")[1] nse = Nse() all_codes = readCodesFile('StockCodes.csv', company) if bool(all_codes): codes = sorted(all_codes.keys()) message = " " for code in codes: message = message + code + " : " + str( nse.get_quote(all_codes[code])['lastPrice']) + "\n" else: message = "Stock not found" bot.sendMessage(chat_id, message) else: message = "My Boss asked me to stay silent rather giving false information" bot.sendMessage(chat_id, message) #if user sent message is of photo or video or document then below code is used to store it on raspberry pi and download later elif (content_type == "document" or content_type == "photo" or content_type == "video"): if content_type == "document": file_id = msg['document']['file_id'] file_name = msg['document']['file_name'] elif content_type == "photo": file_id = msg['photo'][-1]['file_id'] elif content_type == "video": file_id = msg['video']['file_id'] bot.getUpdates() filereceived = bot.getFile(file_id) filepath = filereceived['file_path'] file_name, file_extension = os.path.splitext(filepath) if content_type == "document": bot.download_file(file_id, "/home/pi/Scripts/" + file_name + file_extension) bot.sendMessage(chat_id, "Received and stored your file " + file_name) elif content_type == "photo": bot.download_file(file_id, "/home/pi/Scripts/" + file_name + file_extension) bot.sendMessage(chat_id, "Received and stored your photo " + file_name) elif content_type == "video": bot.download_file(file_id, "/home/pi/Scripts/" + file_name + file_extension) bot.sendMessage(chat_id, "Received and stored your video " + file_name) #if user sent message is location then below code is executed elif content_type == 'location': location = msg['location'] lat = location['latitude'] lon = location['longitude'] owm = pyowm.OWM(ConfigParams.open_weather_key) observation = owm.weather_at_coords(lat, lon) weather = observation.get_weather() location = observation.get_location() gmaps = googlemaps.Client(key=ConfigParams.google_key) geo_loc = str(lat), str(lon) g = geocoder.google(geo_loc, method='reverse') message = "***Weather&Location Statistics***" message = message + "\nCity : " + location.get_name( ) + "\nState : " + g.state + "\nPostalCode : " + g.postal + "\nTemp Max : " + str( weather.get_temperature('celsius') ['temp_max']) + "\nTemp Min : " + str( weather.get_temperature('celsius') ['temp_min']) + " \nStatus : " + weather.get_detailed_status( ) + "\nSunRise : " + weather.get_sunrise_time('iso') message = message + "\nSunSetTime : " + weather.get_sunset_time( 'iso') + "\n" bot.sendMessage(chat_id, message)
import re today = date.today() today_tuple_ = today.timetuple() time_now = datetime.now() #MySQL DB Information for Droplet db = MySQLdb.connect(host="localhost", user="******", passwd="am2814698350", db="droplet") #Cursor object cur = db.cursor() owm = pyowm.OWM( '066d502693de8dbdb6065a22d0143a78') # You MUST provide a valid API key cur.execute("SELECT * FROM schedule") #place each row from MySQL in named tuple queue_row = namedtuple( 'row_', 'sch_id dow start_time zone duration delay cancel_conf') #each named tuple is placed into a list queue = [] for row in cur.fetchall(): print("Sch ID:"), print(row[1]), print(", Time:"), print(row[2])
# Weather to colour dict COLOUR_MAP = { 'clear': 'FFFF6000', 'clouds': '80000000', 'rain': '000000FF', 'drizzle': '0000FFFF', 'snow': 'FFFFFFFF', 'thunderstorm': '80FF0000' } #### Code below #### # Show the name of the playbulb proc = subprocess.Popen( ('gatttool -b ' + PLAYBULB_ADDRESS + ' --char-read -a 0x0003').split(), stdout=subprocess.PIPE) for line in iter(proc.stdout.readline, ''): name = ''.join(x.strip() for x in re.findall(r'[0-9a-f]{2}\s', line)).decode("hex") print 'Playbulb name: ' + name # Get weather forecast weather = pyowm.OWM().weather_at_place(LOCATION).get_weather().get_status() colour = COLOUR_MAP[weather] print 'Weather for ' + LOCATION + ': ' + weather + ', colour ' + colour # Set Playbulb colour subprocess.call(('gatttool -b ' + PLAYBULB_ADDRESS + ' --char-write -a 0x0016 -n ' + colour).split())
os.startfile(codePath) #elif 'motherf*****' in query or 'asshole' in query or 'bainchoad' in query: #speak("sir...!gentelman doesn't talk this way...!") elif 'how are you' in query: hour = int(datetime.datetime.now().hour) if hour >= 5 and hour < 10: speak(" sir! i'm always fine...!") else: speak(" sir! i'm always fine...! how was your day...!") elif 'weather' in query or 'temperature' in query: degree_sign = u'\N{DEGREE SIGN}' owm = pyowm.OWM('a8401ab41d6d7db45008c61f4d8eae63') observation = owm.weather_at_place('kolkata,in') weather = observation.get_weather() temperature = weather.get_temperature('celsius')['temp'] wind = weather.get_wind('miles_hour')['speed'] status = weather.get_detailed_status() speak( f'sir! the temperature is today {temperature}{degree_sign} celsius...!' ) print(f'the temperature is today = {temperature}{degree_sign}') speak(f' the wind speed is today {wind} miles per hour...!') print(f'the wind speed is today = {wind} m/h..!') speak(f' the weather status today is {status}...!') print(f'the weather status today is = {status}')
from telethon.tl.functions.photos import UploadProfilePhotoRequest, DeletePhotosRequest from telethon.sync import TelegramClient from PIL import Image, ImageFont, ImageDraw from datetime import datetime from pytz import timezone import pyowm API_ID = "YOUR_API" API_HASH = "YOU_API_HASH" SESSION_NAME = "SESION_NAME" owm = pyowm.OWM('OPENWEATHERMAP_API_KEY') client = TelegramClient(session=SESSION_NAME, api_id=API_ID, api_hash=API_HASH) client.start() client.connect() now_time = '' def get_time(): """ Function for getting current time, please check the timezone """ return datetime.now(timezone('Europe/Moscow')).strftime('%H:%M') def get_date(): """ Function for getting current date, please check the timezone """ return datetime.now(timezone('Europe/Moscow')).strftime('%d.%m.%Y')