def translate_weather_now(): text = weather.weather_now() request = requests.get('https://translate.yandex.net/api/v1.5/tr.json/translate', params={'key':token, 'text':text['temp_now'], 'lang':'en-ru'}).json() weather_now = request['text'] return weather_now
def forecast_now(message): try: forecast = weather.weather_now(message.text) print(forecast) bot.send_message(message.chat.id, 'ты захотел узнать какая погода в ' + message.text) sms = f"В {message.text} сейчас такая погода:\n" \ f" 🌡 температура воздуха {forecast['temp_now']} гр,\n" \ f" 🌤 на небе {forecast['sky']},\n" \ f" 🌀 скорость ветра {forecast['wind_speed']} м/с,\n" \ f" 📏 атмосферное давление {forecast['pressure']} мм.рт.ст." bot.send_message(message.chat.id, sms) except: bot.send_message(message.chat.id, 'Ошибка связи с сервером')
def handle(msg): chat_id = msg['chat']['id'] command = msg['text'] db_adduser(chat_id) print('%s sent command: %s' % (chat_id, command)) if command == '/roll': bot.sendMessage(chat_id, random.randint(1, 6)) elif command == '/time': bot.sendMessage(chat_id, str(datetime.datetime.now())) elif command == 'weather now': ans = weather.weather_now("Hsinchu") bot.sendMessage(chat_id, ans) elif command == 'weather': ans = weather.weather_forecast("Hsinchu") bot.sendMessage(chat_id, ans) else: resp = wit_client.message(command) if 'intent' in resp['entities']: bool_weather = False bool_forecast = False for i in resp['entities']['intent']: if i['value'] == 'la_weather': bool_weather = True elif i['value'] == 'forecast': bool_forecast = True if bool_weather == True: if bool_forecast == True: ans = weather.weather_forecast( resp['entities']['location'][0]['value']) bot.sendMessage(chat_id, ans) else: ans = weather.weather_now( resp['entities']['location'][0]['value']) bot.sendMessage(chat_id, ans)
api.messages.send(uid=uid, chat_id=chat_id, message=date_time + '\n\n Information:' '\n>VKBot v.0.01, built on November 19 2016 ' '\n>Developer: Vlad Drachev') # Спиоск команд if text == 'commands': list_city = 'Список поддерживаемых городов: Ростов-на-Дону, Москва, Санкт-Петербург, Киев, Ереван ' api.messages.send( uid=uid, chat_id=chat_id, message=date_time + '\n\nCommands:\n1. info\n2. commands' '\n3. привет' '\n4. погода в [название города]\n' + list_city) # Приветствие if text == 'привет': api.messages.send(uid=uid, chat_id=chat_id, message=date_time + '\n\nЗдравствуй, ' + user_name + '!✋') # Погода if text[0:7:1] == "погодав": api.messages.send(uid=uid, chat_id=chat_id, message=str(date_time + '\n\n' + weather.weather_now(text))) # Отмечает сообщение как прочитанное api.messages.markAsRead(message_ids=m['mid']) # Время ожидания 3 секунды time.sleep(3)
device.display(background.convert(device.mode)) def show_weather_forecast(day, day_txt): background = Image.new("RGBA", device.size, "black") icon = Image.open(forecast.cond_icon(day)).resize((40, 40)).convert("RGBA") background.paste(icon, (10, 0)) ft = ImageFont.truetype("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 18) draw = ImageDraw.Draw(background) draw.multiline_text((40, 0), day_txt + '\n ' + forecast.temperature(day) + '\n'+forecast.condition(day), fill='white', font=ft, spacing=4, align='right') device.display(background.convert(device.mode)) try: now = weather_now() forecast = weather_forecast() serial = i2c(port=1, address=0x3C) device = ssd1306(serial, rotate=0) while True: for i in range(3): show_time() time.sleep(1) if Time.tm_min % 20 == 0 and Time.tm_sec < 16: now = weather_now() forecast = weather_forecast() show_weather_now() time.sleep(3) show_weather_forecast(0, '今天') time.sleep(3)
def wit_send(request, response): print(response['text']) token_file = open("token.txt", "r") #file to store token tokens = token_file.read().split('\n') wit_actions = { 'send': wit_send, } wit_token = tokens[0] wit_client = Wit(access_token=wit_token, actions=wit_actions) bot = telepot.Bot(tokens[1]) bot.message_loop(handle) print('I am listening ...') try: conn = psycopg2.connect(database="telegram_ai", user="******", password="******", host="127.0.0.1", port="5432") except: print("connect db error") while 1: now = datetime.datetime.now() if now.hour == 8 and now.minute == 0: bot.sendMessage(238121749, weather.weather_now('Hsinchu')) time.sleep(50)
def get_weather(): temp,weather = weather.weather_now() return weather
def get_temp(): temp,weather = weather.weather_now() return temp
uid = m['uid'] # Имя пользователя user_name = api.users.get(user_ids=uid)[0]['first_name'] try: # id чата chat_id = m['chat_id'] except: chat_id = 0 if chat_id > 0: uid = 0 # Форматированный текст сообщения text = m['body'] text = text.lower() text = text.replace(' ', '') # Строка с датой и временем date_time = datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]') # Команды # Приветствие if text == 'привет': api.messages.send(uid=uid, chat_id=chat_id, message=date_time + '\n\nЗдравствуй, ' + user_name + '!✋') # Погода if text[0:7:1] == "погода в": api.messages.send(uid=uid, chat_id=chat_id, message=str(date_time + '\n\nЗдравствуй,' + weather.weather_now(text))) # Отмечает сообщение как прочитанное api.messages.markAsRead(message_ids=m['mid']) # Время ожидания 3 секунды time.sleep(3)