示例#1
0
def show_weather(msg):
    if msg.text == 'Бишкек':
        city = 'bishkek'
    elif msg.text == 'Кара-Балта':
        city = 'kara-balta'
    elif msg.text == 'Кант':
        city = 'kant'
    elif msg.text == 'Сокулук':
        city = 'sokuluk'

    weather = get_weather(city)
    temp = weather['temp']
    feels_like = weather['feels_like']
    sunrise = weather['sunrise']
    sunset = weather['sunset']
    wind = weather['wind']

    message = f"Здравствуйте.\n" \
              f"Температура {temp} °C.\n" \
              f"Ощущается как {feels_like} °C.\n" \
              f"Восход солнца в {sunrise}, заход в {sunset}.\n" \
              f"Скорость ветра {wind}м/c."

    message = bot.send_message(msg.chat.id, message, reply_markup=btns)
    bot.register_next_step_handler(message, choice_step)
示例#2
0
def send_weather_weibo(client=None):
    # send a weibo about weather.
    if client == None:
        print ('Please login in!!!')
    else:
        # build bing image to update
        get_bing_img()
        img = open('./img/Bing_img.jpg', 'rb')
        # build weather information to update
        weather_info = get_weather()
        city = weather_info['currentCity'].encode('utf-8')
        date = weather_info['weather_data'][0]['date'].encode('utf-8')
        ti = time.strftime("%Y年%m月%d日 %H时%M分")
        weather = weather_info['weather_data'][0]['weather'].encode('utf-8')
        temp = weather_info['weather_data'][0]['temperature'].encode('utf-8')
        wind = weather_info['weather_data'][0]['wind'].encode('utf-8')
        status = '这里是%s,今天%s,现在是%s,今天天气为%s,温度为%s,%s~' % (
            city, date, ti, weather, temp, wind)
        client.statuses.upload.post(status=status, pic=img)
        print ('\nSend a weibo about weather success!\n')
        # logging
        tim = time.asctime()
        P = 'Send a weibo about weather.  Time:%s.   Content: %s\n\n\n' % (
            tim, status)
        call_log(P)
    return None
示例#3
0
def re():
    song = []
    today_ = date.today().strftime("%B %d, %Y")
    weather_info = get_weather.get_weather()
    songs = songList[6:]
    print(songs)
    while len(song) < 6:

        s = random.choices(songs)
        print(s)
        if s[0] not in song:
            song += s
            print(song)
    try:
        print(id_, pwd_, "day")
        return render_template("guest.html",
                               songList=song,
                               weather_info=weather_info,
                               today=today_,
                               theme=get_weather.get_weather_theme())
    except (NameError):
        return render_template("guest.html",
                               songList=song,
                               weather_info=weather_info,
                               today=today_,
                               theme=get_weather.get_weather_theme())
示例#4
0
def main_func():
    #Setup the motors GPIO pins
    setup_motor()
    #Return a dictionary of weather values
    weather = get_weather.get_weather()

    #The temperature, in celsius (by default) or fahrenheit (if you've uncommented the line)
    temp = int(weather['temp'])

    #The last recorded temperature from the text file, the stepper motor needs to know the distance between the
    #current position it is in to the position it needs to move to!
    last_temp = get_temp_from_file()

    #If the temperature doesnt exist (no last recorded temperature), set it to 0
    if (len(last_temp) < 1):
        last_temp = 0

    #Move the motor FROM the last recorded temperature, TO the new temperature
    move_to(DEG_TO_STEP * (int(last_temp)), DEG_TO_STEP * (int(temp)))
    #Store the new temperature on a text file so we know for the future
    store_temp_on_file(int(temp))

    #Reset the motor pins, if you keep the pins on the motor gets very hot!!!
    GPIO.cleanup()

    #Setup the LED pins
    setup_leds()
    #Update the LEDs to show current weather status (rain,snow,wind...)
    update_leds(weather)
示例#5
0
def send_message(twilio_number, dest_number):
    weather_dump = get_weather()
    current_status = None
    current_temp = None
    recepient = None
    body = None

    current_temp = weather_dump[1]

    if dest_number == pg_number:
        recepient = "Paige"
    else:
        recepient = "Jeff"

    if 'rain' in weather_dump[0]:
        current_status = 'raining'
        body = f"Hi, {recepient}. It's currently {current_status} outside. Remember to bring your umbrella! Oh, just one more thing. It's {current_temp}(°F) outside, so please dress accordingly."
    elif 'cloud' in weather_dump[0]:
        current_status = 'cloudy'
        body = f"Hi, {recepient}. It's currently {current_status} outside. No need for an umbrella! Oh, just one more thing. It's {current_temp}(°F) outside, so please dress accordingly."
    elif 'clear' in weather_dump[0]:
        current_status = 'clear'
        body = f"Hi, {recepient}. It's currently {current_status} outside. No need for an umbrella! Oh, just one more thing. It's {current_temp}(°F) outside, so please dress accordingly."

    message = client.messages \
                .create(
                     body=body,
                     from_=twilio_number,
                     to=dest_number
                 )
    print(message.sid)
    return message.sid
示例#6
0
def send_weather():
    weather = get_weather.get_weather()
    payload_post = {
        'text' : weather
    }

    url = "https://hooks.slack.com/services/" + os.environ['NEWS_SLACK']
    requests.post(url, data = json.dumps(payload_post))
示例#7
0
def get_current():
    try:
        city = request.args.get('city')
        if not city.replace(' ', '').isalpha():
            raise TypeError
    except (TypeError, AttributeError):
        return jsonify({'error': 'wrong input data'})
    return jsonify(get_weather(city))
示例#8
0
    def __new_weather(self, key):
        arduino_ip = cherrypy.request.remote.ip

        weather = None
        with open('weatherconversion.json') as jf:
            weather = get_weather(json.load(jf), arduino_ip)
            cherrypy.session['weather'] = weather
            curr_w = weather[key]
        return curr_w
示例#9
0
def get_forecast():
    try:
        city = request.args.get('city')
        dt = request.args.get('dt')
        if not city.replace(' ', '').isalpha():
            raise TypeError
        if not dt.isdigit():
            raise TypeError
    except (TypeError, AttributeError):
        return jsonify({'error': 'wrong input data'})
    return jsonify(get_weather(city, dt))
示例#10
0
def show_weather(location):
    weather_info = get_weather(location)
    back_link = url_for('.get_location')

    if 'error' in weather_info.keys():
        return render_template('error.html',
                               location=location,
                               back_link=back_link)
    else:
        return render_template('location_weather.html',
            weather=weather_info,
            back_link=back_link)
示例#11
0
def show_weather(location):
    weather_info = get_weather(location)
    back_link = url_for('.get_location')

    if 'error' in weather_info.keys():
        return render_template('error.html',
                               location=location,
                               back_link=back_link)
    else:
        return render_template('location_weather.html',
                               weather=weather_info,
                               back_link=back_link)
示例#12
0
def guest():
    song = list()
    today_ = date.today().strftime("%B %d, %Y")
    weather_info = get_weather.get_weather()
    songs = songList[:6]
    while len(song) < 6:
        s = random.choices(songs)
        if s[0] not in song:
            song += s
    return render_template("guest.html",
                           songList=song,
                           weather_info=weather_info,
                           today=today_,
                           theme=get_weather.get_weather_theme())
示例#13
0
def replay_weather(msg):
    print msg.text
    if u'天气' in msg.text:

        msg.reply(get_weather.get_weather())
    if u'博客ip' in msg.text:
        with open('./cip.txt', 'r') as f:
            cip = f.read()
            cipurl = 'https://%s:8443/wordpress/' % cip
        msg.reply(cipurl)
    if u'博客地址' in msg.text:
        msg.reply('https://www.gaoshan.ink:8443/wordpress')
    if u'窗外' in msg.text:
        msg.reply_image('./capture.jpg')
示例#14
0
def integrate_data(location=location):  # 整合数据
    weather_info = get_weather.get_weather(location)
    living_info = get_living_index.main(location)
    final_info = {}
    for key in weather_info:
        if living_info.get(key):
            final_info[key] = [weather_info[key], living_info[key]]
        else:
            final_info[key] = weather_info[key]
    for key in living_info:
        if weather_info.get(key):
            pass
        else:
            final_info[key] = living_info[key]
    print("intergrate_data success!")
    return final_info
示例#15
0
def Post(request: http.Request) -> dict:
    print(type(request.body))
    print(request.body)
    query = json.loads(request.body.decode("utf-8"))


    city_name = str(query["city_name"])
    date = str(query["date"])
    
    print(city_name)
    print(date)

    reply = get_weather(city_name, date)
    print(reply)

    return {'result': json.dumps(reply, ensure_ascii=False)}
示例#16
0
 def POST(self):
     try:
         webData = web.data()
         print "Handle Post webdata is ", webData   #后台打日志
         recMsg = receive.parse_xml(webData)
         if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             _city = recMsg.Content
             content = get_weather(_city)
             replyMsg = reply.TextMsg(toUser, fromUser, content)
             return replyMsg.send()
         else:
             print "暂且不处理"
             return "success"
     except Exception, Argment:
         return Argment
 def get_sonic_speed(self, city="none"):
     #takes city and returns sonic speed in cm/s based on temperature data from the openweathermap API
     if city == "ask":
         city = input("City: ")
     if city == "none" or city == "def" or city == "":
         #skips API call
         print("Using default sonic speed of 34300 cm/s")
         self.sonic_speed = 34300
     temp_k = get_weather.get_weather(city)
     if temp_k != -1:
         temp_c = temp_k - 273.15
         ss = 100 * (331.4 + 0.6 * temp_c)
         print("Temperature (c): ", temp_c)
         print("Sonic Speed (cm/s): ", ss)
         self.sonic_speed = ss
     else:
         print("Using default sonic speed of 34300 cm/s")
         self.sonic_speed = 34300
示例#18
0
def user():
    global uname
    today_ = date.today().strftime("%B %d, %Y")
    weather_info = get_weather.get_weather()
    song = songList_user[:6]
    uname = uname
    try:
        return render_template("user.html",
                               songList=song,
                               weather_info=weather_info,
                               today=today_,
                               theme=get_weather.get_weather_theme(),
                               user=uname)
    except (NameError):
        return render_template("user.html",
                               songList=song,
                               weather_info=weather_info,
                               today=today_,
                               theme=get_weather.get_weather_theme(),
                               user='******')
示例#19
0
def display_main_page(username):
    weather, feels_like, humidity = get_weather()
    feels_like = round(feels_like - 273.15, 1)
    todayDate = date.today()
    weekday = datetime.today().strftime('%A')
    view = 'Today'
    user_id = db.execute("SELECT user_id FROM users WHERE username=:username",
                         {
                             "username": username
                         }).fetchone()
    user_id = user_id[0]
    tasks = db.execute(
        "SELECT task, task_id FROM tasks WHERE owner_id = :user_id", {
            "user_id": user_id
        }).fetchall()
    return render_template('hello.html',
                           date=todayDate,
                           view=view,
                           username=username,
                           tasks=tasks,
                           weather=weather,
                           feels_like=feels_like,
                           humidity=humidity,
                           weekday=weekday)
示例#20
0
def main():

    
    
    kakao = kakaotalk(session_key="5e5ef730af994515a3d4e1ec1198653e05b1a8068c8d47f8a6ebc1847e332f93", device_uuid="s4", user_id=130229954)

    if kakao.login()["body"]["status"] == 0:

        print "Login succeed."



        while True:

            try:

                packet = kakao.translate_response()




                if packet:

                    command = packet["command"]

                    body = packet["body"]




                    now = time.strftime("%m/%d %H:%M:%S")




                    if command == "MSG":

                        message = body["chatLog"]["message"].encode("utf-8")

                        chat_id = body["chatLog"]["chatId"]

                        author_name = body["authorNickname"].encode("utf-8")

                        author_id = body["chatLog"]["authorId"]

                        if len(message) <= 200 and not 'DEBUG' in message and not chat_id in blocked_list:
                            print "[%s] (%d) %s > %s" % (now, chat_id, author_name, message)
                        else:
                            kakao.leave(chat_id)
                        """
                        if not chat_id in chatroom_list:
                            kakao.write(chat_id,"(윙크)오늘은 여기까지!\n내일 봐요~")
                            kakao.leave(chat_id)
                            # 지울시 키워드 스타트 수정하기!
                        """
                        #KEYWARDS START
                        if not chat_id in blocked_list:
                            
                            if '@' in message:

                                message=message.replace('@','')

                            if message == "키워드" or message == "도움" or message=="도움말":

                                kakao.write(chat_id,"키워드는 다음과 같습니다. '@'는 빼고 말해주세요!")
                                kakao.write(chat_id,"◎실시간서비스 : 네이버실시간, 다음실시간, 영화실시간, 주식\n\n◎날씨서비스 : 날씨, 전국날씨\n\n◎뉴스서비스 : 뉴스, 스포츠뉴스, 축구뉴스, 야구뉴스, 농구뉴스\n\n◆유틸서비스 : 검색!, 위키!, 번역, 롤전적\n\n◎키워드등록 : 등록!, 뜻!\n\n◎기타서비스 : 나언제죽어?, 먹을거추천좀, 여자친구추천좀, 오늘의명언, 로또, 확률, 크기, 랜덤\n\n♠만든놈정보 : 개발자\n\n성민봇 페북 : http://facebook.com/lsmbot")

                            elif "오늘의명언" in message.replace(' ',''):

                                kakao.write(chat_id,get_today_saying())


                            elif "번역" in message:
                                try:
                                    message = message.replace('번역','')
                                    sl = message[0:3]
                                    tl = message[3:6]
                                    word = message[6:]

                                    kakao.write(chat_id,google_translate.translate(sl,tl,word))
                                except:
                                    
                                    kakao.write(chat_id,"언어코드는 다음과 같습니다.\n한국어 : 한, 영어 : 영\n중국어 : 중, 일본어 : 일\n독일어 : 독, 프랑스어 : 불\n러시아어 : 러, 스페인어 : 스\n라틴어 : 라, 아랍어 : 아\n이탈리아어 : 이")
                                    kakao.write(chat_id,"예) 한영번역 '번역할 문장'  을 말하시면 한->영 번역 결과가 나옵니다.")

                            elif message=="주식":
                                kakao.write(chat_id,get_rank.get_stock())

                            elif "안녕" in message or "ㅎㅇ" in message or "하이" in message:

                                kakao.write_emoticon(chat_id,random.choice(hi)+"\n@키워드 를 말해봐!","2202001.emot_037.png","(\uc774\ubaa8\ud2f0\ucf58)") 

                            elif '등록!' in message:
                                message = message.replace('등록!','')
                                try:
                                    keyward = message[0:message.index(':')]
                                    word = message[message.index(':')+1:]
                                    write_keyward(keyward.replace(' ','').replace("'",""),word,author_name)
                                    kakao.write(chat_id,"키워드가 등록되었습니다.\n뜻! 키워드 로 확인 가능합니다.")
                                except:
                                    kakao.write(chat_id,"등록! 키워드 : 뜻 을 입력해주세요.")

                            elif '뜻!' in message:
                                message = message.replace('뜻!','').replace(' ','')
                                try:
                                    kakao.write(chat_id,load_keyward(message))
                                except:
                                    kakao.write(chat_id,"등록되지 않은 키워드입니다.\n등록! 키워드 : 뜻 으로 키워드 추가가 가능합니다.")

                            elif message=='로또':
                                kakao.write_emoticon(chat_id,author_name+'님의 이번주 로또 번호는!\n'+get_lotto_num()+'\n입니다! 부자되세요.','2202002.emot_010.png')

                            elif '확률' in message:

                                if message[len(message)-6:] == '확률':

                                    if message == '확률':
                                        kakao.write(chat_id,"뭐뭐할 확률 을 말하시면 성민봇이 가늠해줍니다.")
                                    elif '내가' in message:
                                        message = message.replace('내가',author_name+"이")
                                        kakao.write(chat_id,probability(message))
                                    elif '성민' in message:
                                        message = message.replace('성민',author_name)
                                        kakao.write(chat_id,probability(message))
                                    else:
                                        kakao.write(chat_id,probability(message))

                            elif '크기' in message:

                                if message[len(message)-6:] == '크기':
                                    if message == '크기':
                                        kakao.write(chat_id,"뭐뭐의 크기 를 말하시면 성민봇이 추정해봅니다.")
                                    elif '성민' in message:
                                        message = message.replace('성민',author_name)
                                        kakao.write(chat_id,size(message))
                                    else:
                                        kakao.write(chat_id,size(message))

                            elif '랜덤' in message:
                                if message == '랜덤':
                                    kakao.write(chat_id,"나열된 단어중에서 하나를 선택합니다\n예) 랜덤 남자 여자 중성")
                                else:
                                    message = message.replace('랜덤','')
                                    kakao.write(chat_id,random_choice(message))

                            elif "검색!" in message:
                                if message != "검색!":
                                    try:
                                        word = message.replace("검색!","").replace(' ','')
                                        kakao.write(chat_id,get_dic_search(word))

                                    except:
                                        kakao.write(chat_id,"네이버사전에 등록되지 않은 단어입니다.\n위키! 를 통해 검색해보세요.")
                                else:
                                    kakao.write(chat_id,"검색! 키워드 를 말하시면 요약된 네이버사전 검색결과가 나옵니다.")

                            elif "위키!" in message:
                                if message != "위키!":
                                    try:
                                        word = message.replace("위키!","").replace(' ','')
                                        kakao.write(chat_id,get_wiki_search(word))

                                    except:
                                        kakao.write(chat_id,"엔하위키 사전에 등록되지 않은 단어이거나.\n현재 엔하위키 사이트가 응답하지 않습니다.")
                                else:
                                    kakao.write(chat_id,"위키! 키워드 를 말하시면 엔하위키 검색결과가 나옵니다..")

                            elif '롤전적' in message:

                                name = message.replace('롤전적','').replace("'","")
                                try:
                                    kakao.write(chat_id,get_lol.get_lol_info(name))
                                except:
                                    kakao.write(chat_id,"롤전적 제대로된 소환사명\n을 치세요")
                            

                            elif message.replace(' ','') == "네이버실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_rank.get_naver_rank())))

                            elif message.replace(' ','') == "다음실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_rank.get_daum_rank())))                            
                            
                            elif message.replace(' ','') == "영화실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s"%("\n".join(get_rank.get_movie_rank())))

                            elif message.replace(' ','') == "스포츠뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_sport_news())))

                            elif message.replace(' ','') == "축구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_soccer_news())))

                            elif message.replace(' ','') == "야구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_baseball_news())))

                            elif message.replace(' ','') == "농구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_basketball_news())))

                            elif message.replace(' ','')=="전국날씨":
                                
                                kakao.write(chat_id,time.strftime("[%m월 %d일 %H시%M분%S초 현재]\n\n")+get_weather.get_weather())

                            elif message=="날씨":

                                kakao.write(chat_id,time.strftime("[%m월 %d일 %H시%M분%S초 현재]\n")+get_weather.get_seoul_weather())

                            elif message=="뉴스":

                                kakao.write(chat_id,get_news.get_total_news())

                            elif message=="야동":

                                kakao.write(chat_id,".prx2.unblocksit.es 사이트 주소뒤에 이거 붙이고 들어가면 warning.or.kr 안뜸 ㅋ")

                            elif "계산" in message and author_id==14146663:
                                _message = message.replace("계산","")
                                try:
                                    kakao.write(chat_id,"결과 : "+str(float(eval(_message))))                                    
                                except:
                                    kakao.write(chat_id,"제대로 된 수식을 입력하세요.\n연산자 종류 : +, -, *, /, ** <- 제곱,\nsqrt(n) <- n의 제곱근,\nlog(x,y) <- 밑이 y인 로그 x\nsin(x), cos(x), tan(x) <- 삼각함수(라디안)\n**수식앞에 '계산' 을 붙여주세요.**")

                            elif message=="서버":

                                kakao.write(chat_id,server_time(time_server_start))

                            elif "언제죽어" in message.replace(' ',''):
                                if '은' in message:
                                    kakao.write_emoticon(chat_id,message[0:message.index('은')]+" 은(는) "+str(random.randint(1,70))+"년 뒤에 "+random.choice(die)+" 죽음 ^오^","2202002.emot_0"+str(random.randint(10,80))+".png","(\uc774\ubaa8\ud2f0\ucf58)")
                                elif '는' in message:
                                    kakao.write_emoticon(chat_id,message[0:message.index('는')]+" 은(는) "+str(random.randint(1,70))+"년 뒤에 "+random.choice(die)+" 죽음 ^오^","2202002.emot_0"+str(random.randint(10,80))+".png","(\uc774\ubaa8\ud2f0\ucf58)")
                                else:
                                    kakao.write_emoticon(chat_id,author_name+" 은(는) "+str(random.randint(1,70))+"년 뒤에 "+random.choice(die)+" 죽음 ^오^","2202002.emot_0"+str(random.randint(10,80))+".png","(\uc774\ubaa8\ud2f0\ucf58)")

                            elif message=="먹을거추천좀":

                                kakao.write_emoticon(chat_id,random.choice(food),"2202001.emot_055.png","(\uc774\ubaa8\ud2f0\ucf58)")

                            elif "여자친구추천좀" in message.replace(' ',''):

                                kakao.write_emoticon(chat_id,"","2202001.emot_0"+str(random.choice(foob))+".png","(\uc774\ubaa8\ud2f0\ucf58)")

                            elif message == '개발자':

                                kakao.write(chat_id,"카카오톡 패킷분석은 김할라님의 pykakao를 사용하였습니다.\nhttps://github.com/HallaZzang/pykakao\n\n이메일 : [email protected]\n\n개발자는 파릇파릇한 20살. 여친구함\n\n성민봇 페이스북 :\n http://facebook.com/lsmbot")                            

                            elif (message == "나가" or "꺼저" in message or "꺼져" in message):
                                
                                if chat_id in chatroom_list:
                                    kakao.write(chat_id,"이 방은 나가기가 제한되어있는 방입니다.")
                                else:
                                    kakao.write_emoticon(chat_id,random.choice(bye),"2202001.emot_065.png","(\uc774\ubaa8\ud2f0\ucf58)")

                                    kakao.leave(chat_id)
                            
                    else: # unknown commands

                        # print "[%s] <%s, %s>" % (now, command, body)

                        pass

                else:

                    if kakao.login()["body"]["status"] != 0:

                        print "Auto-reconnect failed."

                        kakao.s.close()

                        break

            except KeyboardInterrupt:

                kakao.s.close()

                exit()

    else:

        print "Login failed."
示例#21
0
documents_added = 0
start = datetime.datetime.now()
for i in range(1, pages_to_scrape + 1):
    intermediate = datetime.datetime.now()
    diff = intermediate - start
    print(f'page {i}, {diff.seconds} seconds passed, {documents_added} \
        documents added')
    url = f'https://www.landsofamerica.com/United-States/farms/page-{i}'
    div_tops = scrape_land.get_all_land(url)
    for div_top in div_tops:
        time.sleep(1)
        try:
            land_info = scrape_land.scrape_land(div_top)
            zip_code = land_info['postal_code']
            try:
                land_info['weather_info'] = get_weather.get_weather(zip_code)
            except:
                pass
            try:
                zip_data = zip_county.getZipCounty(zip_code, df)
                if zip_data:
                    land_info['zip_data'] = zip_data
            except:
                pass
            try:
                census_data = get_census.census_data(zip_code)
                land_info['census_data'] = census_data
            except:
                pass
            db.farms.insert_one(land_info)
            documents_added += 1
示例#22
0
def main():

    
    
    kakao = kakaotalk(session_key="5e5ef730af994515a3d4e1ec1198653e05b1a8068c8d47f8a6ebc1847e332f93", device_uuid="s4", user_id=130229954)

    if kakao.login()["body"]["status"] == 0:

        print "Login succeed."



        while True:

            try:

                packet = kakao.translate_response()




                if packet:

                    command = packet["command"]

                    body = packet["body"]




                    now = time.strftime("%m/%d %H:%M:%S")




                    if command == "MSG":

                        message = body["chatLog"]["message"].encode("utf-8")

                        chat_id = body["chatLog"]["chatId"]

                        author_name = body["authorNickname"].encode("utf-8")

                        author_id = body["chatLog"]["authorId"]


                        print "[%s] (%d) %s > %s" % (now, chat_id, author_name, message)

                        sleep(0.1)
                        
                        list_txt=open("init_list.txt","r")
                        get_list_txt=list_txt.read()
                        list_txt.close()

                        if not str(chat_id) in get_list_txt:
                            kakao.write(chat_id,"@키워드 를 말해보세요!")
                            list_txt=open("init_list.txt","a")
                            list_txt.write(str(chat_id)+'\n')
                            list_txt.close()

                        if message == "@차단" and (author_id == kakao.user_id or author_id == 14146663):

                            if chat_id in blocked_list:

                                kakao.write(chat_id, "[성민봇] 이미 차단된 방입니다.")

                            else:

                                kakao.write(chat_id, "[성민봇] 차단되었습니다.")

                                blocked_list.append(chat_id)

                        elif message == "@차단해제" and (author_id == kakao.user_id or author_id == 14146663):

                            if chat_id in blocked_list:

                                kakao.write(chat_id, "[성민봇] 차단 해제되었습니다.")

                                blocked_list.remove(chat_id)

                            else:

                                kakao.write(chat_id, "[성민봇] 이미 차단 해제된 방입니다.")

                        if "@차단:" in message and (author_id == kakao.user_id or author_id == 14146663):
                            name = message.replace("@차단:","")
                            list_txt=open("blocked_list.txt","r")
                            get_list_txt=list_txt.read()
                            list_txt.close()
                            if not name in get_list_txt:
                                #blocked_list.append(name)
                                list_txt=open("blocked_list.txt","a")
                                list_txt.write(name)
                                list_txt.close()
                                kakao.write(chat_id, name+"님이 차단 되었습니다.")
                            else:
                                kakao.write(chat_id, name+"님은 이미 차단 되었습니다.")

                        elif "@차단해제:" in message and (author_id == kakao.user_id or author_id == 14146663):
                            name = message.replace("@차단해제:","")
                            list_txt=open("blocked_list.txt","r")
                            get_list_txt=list_txt.read()
                            list_txt.close()
                            if name in get_list_txt:                                
                                #blocked_list.remove(name)
                                
                                list_txt=open("blocked_list.txt","w")
                                list_txt.write(get_list_txt.replace(name,""))
                                list_txt.close()
                                kakao.write(chat_id, name+"님이 차단해제 되었습니다.")
                            else:
                                kakao.write(chat_id, name+"님은 차단목록에 없습니다.")


                        if "notice " in message and chat_id == 70546206443768:
                            f= open('init_list.txt','r')
                            notice_rooms = f.readlines()
                            f.close()

                            for notice_room in notice_rooms:
                                try:
                                    kakao.write(int(notice_room.replace('\n','')),message.replace('notice ',''))

                                except:
                                    print notice_room.replace('\n','')+"번 방 실패"

                        list_txt=open("blocked_list.txt","r")
                        get_list_txt=list_txt.read()
                        list_txt.close()


                        if not chat_id in blocked_list and not author_name in get_list_txt:
                            
                            if '@' in message:
                                message=message.replace('@','')

                            if message == "키워드":
                                kakao.write(chat_id,"키워드는 다음과 같습니다. '@'는 빼고 말해주세요!")
                            
                                kakao.write(chat_id,"◎실시간서비스 : 네이버실시간, 다음실시간, 영화실시간, 올림픽\n\n◎날씨서비스 : 날씨, 전국날씨\n\n◎뉴스서비스 : 뉴스, 스포츠뉴스, 축구뉴스, 야구뉴스, 농구뉴스\n\n◆유틸서비스 : 계산, 검색! , 번역\n\n◎기타서비스 : 나언제죽어?, 먹을거추천좀, 여자친구추천좀, 오늘의명언")
                                
                                kakao.write(chat_id,"[!NEW!]새 키워드 : 번역, 오늘의명언")

                            elif "오늘의명언" in message.replace(' ',''):

                                kakao.write(chat_id,get_today_saying())

                            elif "롤전적" in message:
                                kakao.write(chat_id,"롤전적 검색 기능은 삭제되었습니다.")
                            elif "성민봇" in message and not chat_id in chatroom_list:

                                kakao.write(chat_id,"주인님 카카오톡 : lsmorigin")

                            elif (message == "나가" or "꺼저" in message or "꺼져" in message):                                
                                #kakao.write(chat_id,"잠시 점검중 입니다.")
                                
                                kakao.write_emoticon(chat_id,"잘있어 친구들!","2202001.emot_065.png","(\uc774\ubaa8\ud2f0\ucf58)")
                                #init_list.remove(chat_id)
                                list_txt=open("init_list.txt","r")
                                get_list_txt=list_txt.read()
                                list_txt.close()
                                list_txt=open("init_list.txt","w")
                                list_txt.write(get_list_txt.replace(str(chat_id)+'\n',""))
                                list_txt.close()

                                kakao.leave(chat_id)

                            elif "번역" in message:
                                try:
                                    message = message.replace('번역','')
                                    sl = message[0:3]
                                    tl = message[3:6]
                                    word = message[6:]

                                    kakao.write(chat_id,google_translate.translate(sl,tl,word))
                                except:
                                    
                                    kakao.write(chat_id,"언어코드는 다음과 같습니다.\n한국어 : 한, 영어 : 영\n중국어 : 중, 일본어 : 일\n독일어 : 독, 프랑스어 : 불\n러시아어 : 러, 스페인어 : 스\n라틴어 : 라, 아랍어 : 아")
                                    kakao.write(chat_id,"예) \"한영번역 '번역할 문장' \" 을 말하시면 한->영 번역 결과가 나옵니다.")

                            elif message=="올림픽":
                                kakao.write(chat_id,get_rank.get_olympic_rank())

                            elif "안녕" in message or "ㅎㅇ" in message or "하이" in message:

                                kakao.write_emoticon(chat_id,hi[randint(0,len(hi)-1)]+"\n@키워드 를 말해봐!","2202001.emot_037.png","(\uc774\ubaa8\ud2f0\ucf58)") 

                            elif "검색!" in message:
                                if message != "검색!":
                                    try:
                                        word = message.replace("검색!","").replace(" ","")
                                        kakao.write(chat_id,get_dic_search(word))

                                    except:
                                        kakao.write(chat_id,"사전에 등록되지 않은 단어입니다.")
                                else:
                                    kakao.write(chat_id,"검색! '키워드' 를 말하시면 요약된 사전검색결과가 나옵니다.")


                            elif message.replace(' ','') == "네이버실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_rank.get_naver_rank())))

                            elif message.replace(' ','') == "다음실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_rank.get_daum_rank())))                            
                            
                            elif message.replace(' ','') == "영화실시간":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s"%("\n".join(get_rank.get_movie_rank())))

                            elif message.replace(' ','') == "스포츠뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_sport_news())))

                            elif message.replace(' ','') == "축구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_soccer_news())))

                            elif message.replace(' ','') == "야구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_baseball_news())))

                            elif message.replace(' ','') == "농구뉴스":

                                kakao.write(chat_id, time.strftime("[%m월 %d일 %H시%M분%S초 현재]")+"\n"+"%s" % ("\n".join(get_news.get_basketball_news())))

                            elif message.replace(' ','')=="전국날씨":
                                
                                kakao.write(chat_id,time.strftime("[%m월 %d일 %H시%M분%S초 현재]\n\n")+get_weather.get_weather())

                            elif message=="날씨":

                                kakao.write(chat_id,time.strftime("[%m월 %d일 %H시%M분%S초 현재]\n")+get_weather.get_seoul_weather())

                            elif message=="뉴스":

                                kakao.write(chat_id,get_news.get_total_news())

                            elif message=="야동":

                                kakao.write(chat_id,".prx2.unblocksit.es 사이트 주소뒤에 이거 붙이고 들어가면 warning.or.kr 안뜸 ㅋ")

                            elif "계산" in message and author_name != "이민성":
                                _message = message.replace("계산","")
                                try:
                                    kakao.write(chat_id,"결과 : "+str(float(eval(_message))))
                                    if '/' in _message:
                                        kakao.write(chat_id,"소숫점까지 아시려면 소수형태로 숫자를 써주세요.\n(예 : 1.0/2.0) ")
                                except:
                                    kakao.write(chat_id,"제대로 된 수식을 입력하세요.\n연산자 종류 : +, -, *, /, ** <- 제곱,\nsqrt(n) <- n의 제곱근,\nlog(x,y) <- 밑이 y인 로그 x\nsin(x), cos(x), tan(x) <- 삼각함수(라디안)\n**수식앞에 '계산' 을 붙여주세요.**")

                            elif message=="서버":

                                kakao.write(chat_id,server_time(time_server_start))


                            elif "섹스키워드 " in message:
                                sexkey = message.replace("섹스키워드 ","")
                                f = open('sex.txt','a')
                                f.write(sexkey+'\n')
                                kakao.write(chat_id,"키워드가 추가되었습니다.")
                                f.close()

                            elif "섹스" in message:
                                f = open('sex.txt','r')
                                sex = f.readlines()                                
                                kakao.write(chat_id,sex[randint(0,len(sex)-1)])
                                kakao.write(chat_id,"섹스키워드 '키워드' 로 키워드 추가가 가능합니다. ")
                                f.close()

                            elif "언제죽어" in message.replace(' ',''):
                                
                                kakao.write_emoticon(chat_id,author_name+" 은(는) "+str(randint(1,70))+"년 뒤에 "+die[randint(0,len(die)-1)]+" 죽음 ^오^","2202002.emot_0"+str(randint(10,80))+".png","(\uc774\ubaa8\ud2f0\ucf58)")

                            elif message=="광주는?":

                                kakao.write_emoticon(chat_id,"광주는..그..하나의 광역시야..그래서 100만명이 넘기떄문에 광역시로 지정하지 않을수가 없잖아?","2202001.emot_054.png","(\uc774\ubaa8\ud2f0\ucf58)")
                        
                            elif message=="먹을거추천좀":

                                kakao.write_emoticon(chat_id,food[randint(0,len(food)-1)],"2202001.emot_055.png","(\uc774\ubaa8\ud2f0\ucf58)")

                            elif "여자친구추천좀" in message.replace(' ',''):

                                kakao.write_emoticon(chat_id,"","2202001.emot_0"+str(foob[randint(0,len(foob)-1)])+".png","(\uc774\ubaa8\ud2f0\ucf58)")

                            
                            
                    else: # unknown commands

                        # print "[%s] <%s, %s>" % (now, command, body)

                        pass

                else:

                    if kakao.login()["body"]["status"] != 0:

                        print "Auto-reconnect failed."

                        kakao.s.close()

                        break

            except KeyboardInterrupt:

                kakao.s.close()

                exit()

    else:

        print "Login failed."
示例#23
0
def event_handler(event_type, slack_event, event_message):
    if event_type == "app_mention":

        print("여울이 이벤트 메세지 : " + event_message)

        # bob_recommand
        if event_message.find("밥") > -1:

            channel = slack_event["event"]["channel"]

            #slack.chat.post_message(channel, f"여울이의 추천메뉴는 {food_answer()} 입니다. 월월")

            slack.chat.post_message(channel, f"여울이가 추천해줘도 안먹을꺼 잖아요...")

            return make_response(
                "앱 멘션 메시지가 보내졌습니다.",
                200,
            )

        # covid check
        elif event_message.find("코로나") > -1:

            channel = slack_event["event"]["channel"]

            attachements, username, icon_emoji = get_covid()
            print(attachements)
            print(username)
            print(icon_emoji)

            slack.chat.post_message(channel,
                                    attachments=[attachements],
                                    username=username,
                                    icon_emoji=icon_emoji)

            return make_response(
                "앱 멘션 메시지가 보내졌습니다.",
                200,
            )

        # weather check
        elif event_message.find("날씨") > -1:

            channel = slack_event["event"]["channel"]

            attachements, username, icon_emoji = get_weather()

            slack.chat.post_message(channel,
                                    attachments=[attachements],
                                    username=username,
                                    icon_emoji=icon_emoji)

            return make_response(
                "앱 멘션 메시지가 보내졌습니다.",
                200,
            )

        #  url shortcut
        elif event_message.find("주소단축") > -1:
            channel = slack_event["event"]["channel"]
            orignalurl = event_message.replace("주소단축 ", "")
            if event_message.replace(" ", "") == "주소단축":
                slack.chat.post_message(channel,
                                        f"주소단축 뒤에 주소를 넣어주시면 여울이가 줄여줄게요")

            elif event_message != surl:
                ssurl = url_short(orignalurl)
                username = '******'
                icon_emoji = ''
                attachement = {
                    'pretext': '여울이의 ShortUrl',
                    "fallback": "여울이 ShortUrl",
                    "text": f"여울이가 주소를 줄였어요.  {ssurl}\n",
                    "fields": [{
                        "value": "",
                        "short": False
                    }],
                    "color": "good",
                }

                slack.chat.post_message(channel,
                                        attachments=[attachement],
                                        username=username,
                                        icon_emoji=icon_emoji)

            return make_response(
                "앱 멘션 메시지가 보내졌습니다.",
                200,
            )

        else:

            channel = slack_event["event"]["channel"]

            slack.chat.post_message(
                channel,
                f":welsh_corgi:여울이 명령어에오:welsh_corgi: \n밥, 코로나, 날씨, 주소단축")

            return make_response(
                "앱 멘션 메시지가 보내졌습니다.",
                200,
            )

        message = "[%s] 이벤트 핸들러를 찾을 수 없습니다." % event_type

        return make_response(message, 200, {"X-Slack-No-Retry": 1})
示例#24
0
def send(message):
    """Return today's weather"""
    text = get_weather.get_weather(1)
    bot.send_message(message.chat.id, text)
示例#25
0
def send(message):
    """Return weather for a week"""
    text = get_weather.get_weather(7)
    bot.send_message(message.chat.id, text)
示例#26
0
def predict(destination, origin):
    if request.method == 'POST':
        try:
            import geocoding
            import bing_maps_routes
            import bing_maps_distance_matrix
            import bing_maps_elevations
            import bing_maps_traffic_speed_flow
            import get_weather
            import get_heading
            import get_wind_type
            import get_drag
            import get_rolling_friction
            import get_speedLimits
            import get_acceleration
            import Azure_final

          
            #--------------------------------------------------------------------------------------------------
            #Module 1 - Geocoding Module

            # destGeocoded = geocoding.geocode('Fishaways - Sasol Summerstrand')
            destGeocoded = geocoding.geocode(destination)
            #--------------------------------------------------------------------------------------------------
            #Module 2 - Get Coordinates Module - coordinates for route to destination
            # this module can return two lists
            # coordinatesList provides more coordinates on route
            # maneuverPointList retruns list of each segment - use this list to reduce computational overhead
            #  coordinatesResult, maneuverPointListResult = bing_maps_routes.get_coordinates(destGeocoded) to get both lists

            # maneuverPointListResult = bing_maps_routes.get_coordinates( '-34.002053,25.670521', destGeocoded)
            maneuverPointListResult, durationList = bing_maps_routes.get_coordinates(origin,destGeocoded)

            print('printing maneuverPoints List coordinates------------')
            print(maneuverPointListResult)

            print('printing durations------------')
            print(durationList)

            # #--------------------------------------------------------------------------------------------------
            #Module 3 - Get Distances each segment on route to destination
            # Split list Coordinates in equal chunks smaller than 50

            distancesList = bing_maps_distance_matrix.split_coordinates(maneuverPointListResult)
            print('printing List of Distances------------')
            print(distancesList)
            print('total distance:',sum(distancesList))

            # #--------------------------------------------------------------------------------------------------
            # #Module 4 - Get elevations for each coordinate
            elevationList = bing_maps_elevations.get_elevations(maneuverPointListResult)
            print('printing elevations------------')
            print(elevationList)

            # #--------------------------------------------------------------------------------------------------
            # #Module 5 - Get Speeds
            # #Get speeds for list
            speedList = bing_maps_traffic_speed_flow.get_speeds_from_maps(maneuverPointListResult)
            print('Printing speed list from front----------')
            print(speedList)
            #
            # #--------------------------------------------------------------------------------------------------
            # #Module 6 - Get weather
            listwindSpeed, listwindBearing, listtemperature, listpressure = get_weather.get_weather(maneuverPointListResult)
            print('Weahter-----------')
            print("WindSpeed")
            print(listwindSpeed)
            print("Wind Bearing")
            print(listwindBearing)
            print("temperature")
            print(listtemperature)
            print('pressure')
            print(listpressure)
            # #--------------------------------------------------------------------------------------------------
            # #Module 7 - Get bearing
            bearingList = get_heading.prepare_heading_list(maneuverPointListResult)
            print('bearing')
            print(bearingList)

            ##Module 8 - Get windType
            crossWindList, tailWindList, headWindList = get_wind_type.prepare_wind_type(bearingList, listwindSpeed, listwindBearing)
            print("crosswind")
            print(crossWindList)
            print("tailwind")
            print(tailWindList)
            print("headwind")
            print(headWindList)

            # #--------------------------------------------------------------------------------------------------
            # #Module 9 - Get Drag
            dragList = get_drag.prepare_drag(listtemperature, listpressure, speedList)
            print("dragList")
            print(dragList)
            # #--------------------------------------------------------------------------------------------------
            # #Module 10 - Get Rolling Friction and calculate angle
            # return negative and positive elevation

            rollingfList, elvDiffList_Pos, elvDiffList_Neg, angleList = get_rolling_friction.get_elv_diff(elevationList, distancesList)
            print("rolling friction list")
            print(rollingfList)
            print("ELevation pos")
            print(elvDiffList_Pos)
            print("ELevation neg")
            print(elvDiffList_Neg)
            print("AngleList")
            print(angleList)

            #-----------------------------------------------------------------------------------------------
            # #Module 11 - Acceleration
            accList = get_acceleration.get_acceleration(speedList, durationList)
            print("accList")
            print(accList)

            #-----------------------------------------------------------------------------------------------
            # #Module 12 - SpeedLimits
            speedLimitList = get_speedLimits.prepare_speedLimits(maneuverPointListResult)
            print(speedLimitList)

            #-----------------------------------------------------------------------------------------------
            # #Module 13 -Print list lengths


            distancesListF = []
            speedList2 = []
            crossWindListM = []
            tailWindListM = []
            headWindListM = []

            speedList.pop(0)



            for x in range(len(speedList)):   #need to only get speeds not coordinates
                speed = speedList[x][1]
                speedF = speed * 0.277778
                speedList2.append(speedF)

            for x in range(len(distancesList)):
                distance = distancesList[x]
                distanceM = distance * 1000
                distancesListF.append(distanceM)

            for x in range(len(crossWindList)):
                crosswind = crossWindList[x]
                crossWindM = crosswind / 0.514444 #convert to meter per second
                crossWindListM.append(crossWindM)

            for x in range(len(tailWindList)):
                tailwind = tailWindList[x]
                tailWindM = tailwind / 0.514444 #convert to meter per second
                tailWindListM.append(tailWindM)

            for x in range(len(headWindList)):
                headwind = headWindList[x]
                headWindM = headwind / 0.514444 #convert to meter per second
                headWindListM.append(headWindM)

            speedLimitList.pop(0)
            dragList.pop(0)
            crossWindListM.pop(0)
            tailWindList.pop(0)
            headWindList.pop(0)
            listpressure.pop(0)
            listtemperature.pop(0)

            speedListF = speedList2
            speedLimitListF = speedLimitList
            dragListF = dragList
            crossWindListF  = crossWindListM
            headWindListF = headWindListM
            tailWindListF  = tailWindListM
            listpressureF = listpressure
            listtemperatureF = listtemperature

            #send to azure
            # speedLimitListF = speedLimitList.pop(0)
            # dragListF = dragList.pop(0)
            # crossWindListF = crossWindList.pop(0)
            # headWindListF = tailWindList.pop(0)
            # tailWindListF = headWindList.pop(0)
            # listpressureF = listpressure.pop(0)
            # listtemperatureF = listtemperature.pop(0)

            print('distance', len(distancesListF))
            print('acceleration',len(accList))
            print('speedF', len(speedListF))
            print('speedLimit',len(speedLimitListF))
            print('drag',len(dragListF))
            print('rolling',len(rollingfList))
            print('elv diff positive',len(elvDiffList_Pos))
            print('elv diff neg', len(elvDiffList_Neg))
            print('cross', len(crossWindListF))
            print('tail',len(tailWindListF))
            print('headwind',len(headWindListF))
            print('pressure',len(listpressureF))
            print('temp',len(listtemperatureF))
            print('angle', len(angleList))

        except ValueError:
            return jsonify("error")

        newlist = [distancesListF,
           speedListF,
           accList,
           listtemperatureF,
           listpressureF,
           speedLimitListF,
           crossWindListF,
           tailWindListF,
           headWindListF,
           dragListF,
           rollingfList,
           angleList,
           elvDiffList_Pos,
           elvDiffList_Neg]

        send_to_azure = [list(t) for t in zip(*newlist)]

        print(send_to_azure)

        from time import gmtime, strftime
        time = strftime("%Y-%m-%d %H:%M:%S", gmtime())

        print("CURRENT TIME:",time)
        Azure_final.calculate_EC(send_to_azure)

        return json.dumps({
            'distance': distancesList,
            'acceleration': accList,
            'speedF':speedListF,
            'speedLimit':speedLimitListF,
            'drag':dragListF,
            'rolling':rollingfList,
            'elv diff positive':elvDiffList_Pos,
            'elv diff neg':elvDiffList_Neg,
            'cross':crossWindListF,
            'tail':tailWindListF,
            'headwind':headWindListF,
            'pressure':listpressureF,
            'temp':listtemperatureF,
            'angle':angleList})

            # "coordinates" : maneuverPointListResult,
            #                "distances" : distancesList})
        return('success')
示例#27
0

def get_datetime():
    d = datetime.now()
    text = '%s月%s日、%s時%s分%s秒' % (d.month, d.day, d.hour, d.minute, d.second)
    return text


if __name__ == "__main__":
    args = parser.parse_args()

    word_txt = 'test'

    if args.command:
        if args.command == 'weather':
            word_txt = gw.get_weather()
        if args.command == 'time':
            word_txt = get_datetime()
        if args.command == 'schedule':
            word_txt = gc.get_schedule()

    if args.file:
        with open(args.file) as f:
            word_txt = f.read()
            word_txt = word_txt.replace('\n', '')
            word_txt = word_txt.replace('\r', '')

    if args.word:
        word_txt = args.word

    if args.say:
示例#28
0
from get_weather import get_weather
from get_weather import get_datetime
from time import sleep

sleep_count = 0
while sleep_count <= 11:
    print("Adding data... Time : %s"%get_datetime())
    get_weather()
    sleep(300)
    sleep_count += 1
示例#29
0
def send_hello():
    Sender(receivers=u"gaoshan\'secretary").send(u'早上好!')



def send_price(url='https://www.michelin.com/eng/finance/share-information/share-price-history'):

    Sender(receivers=u"gaoshan'secretary").send(u'今日米其林股今日米其林股价信息'+url)

def send_ip():
    with open('./cip.txt', 'r') as f:
        cip = f.read()
        cipurl = 'https://%s:8443/wordpress/' % cip
    Sender(receivers=u"gaoshan'secretary").send(cipurl)


def send_weather(weather):
    Sender(receivers=u"gaoshan'secretary").send(weather)

def send_english(english):
    Sender(receivers=u"gaoshan'secretary").send(english)



send_hello()
#send_price()
send_ip()
send_weather(get_weather.get_weather())
send_english(get_english.english_send)
示例#30
0
def main():
    # 电子墨水屏初始化
    epd = epd4in2.EPD()
    epd.init()
    # 创建空图像
    image = Image.new('1', (400, 300), 1)
    draw = ImageDraw.Draw(image)
    # 主屏幕上下分割线
    draw.line([0, 100, 399, 100], fill=0, width=2)
    # 定义字体格式
    font_calibril_super = ImageFont.truetype('/usr/share/fonts/song/calibril',
                                             90)
    font_song_small = ImageFont.truetype('/usr/share/fonts/song/simsun', 24)
    font_song_mid = ImageFont.truetype('/usr/share/fonts/song/simsun', 28)
    font_song_big = ImageFont.truetype('/usr/share/fonts/song/simsun', 32)
    font_song_large = ImageFont.truetype('/usr/share/fonts/song/simsun', 40)
    font_icon = ImageFont.truetype('/usr/share/fonts/Weather&Time', 86)
    font_icon_mid = ImageFont.truetype('/usr/share/fonts/Weather&Time', 40)
    draw.ink = 256 + 256 * 256 + 256 * 256 * 256

    # 计数君
    count = 0
    isfailed = True

    while True:
        # 清空上半部分显示区域
        draw.rectangle([0, 0, 399, 98], fill='white')
        draw.rectangle([200, 102, 399, 159], fill='white')

        # 获取日期时间
        datetime = get_datetime()
        draw.text([0, 10], datetime['time'], font=font_calibril_super)
        draw.text([250, 10], datetime['date'], font=font_song_small)
        draw.text([250, 40], datetime['week'], font=font_song_small)
        draw.text([250, 70], u'农历' + '', font=font_song_small)

        # 获取室内温度
        wet_indoor, temp_indoor = Adafruit_DHT.read(Adafruit_DHT.DHT22, 4)
        draw.text([190, 120], 'k', font=font_icon_mid)
        if temp_indoor is not None:
            draw.text([220, 120],
                      str(int(temp_indoor)) + u'℃',
                      font=font_song_large)
        draw.text([300, 120], 'j', font=font_icon_mid)
        if wet_indoor is not None:
            draw.text([330, 120],
                      str(int(wet_indoor)) + u'%',
                      font=font_song_large)

        if count == 0:
            #清空下半部分显示区域
            draw.rectangle([0, 102, 199, 299], fill='white')
            draw.rectangle([200, 160, 399, 299], fill='white')

            try:
                # 获取室外温度
                s = get_instance_weather()
                temp_outdoor = int(s['weather']['temperature'])
                wet_outdoor = int(s['weather']['humidity'])
                draw.text([220, 160],
                          str(temp_outdoor) + u'℃',
                          font=font_song_big)
                draw.text([330, 160],
                          str(wet_outdoor) + u'%',
                          font=font_song_big)

                # 获取天气状况
                weather = get_weather()
                draw.text([100, 130],
                          weather['city_name'],
                          font=font_song_small)
                #draw.text([230, 170], weather['real_temp'], font = font_song_large)
                draw.text([100, 160], u'今日', font=font_song_small)
                draw.text([10, 110],
                          str2icon(weather['day_weather']),
                          font=font_icon)
                draw.line([53, 240, 53, 290], fill=0)
                if weather.has_key('night_weather'):
                    if weather['day_weather'] == weather['night_weather']:
                        draw.text([20, 200],
                                  weather['day_weather'],
                                  font=font_song_mid)
                    else:
                        draw.text([20, 200],
                                  weather['day_weather'] + u'/' +
                                  weather['night_weather'],
                                  font=font_song_mid)
                else:
                    draw.text([20, 200],
                              weather['day_weather'],
                              font=font_song_mid)
                if weather.has_key('night_temp'):
                    draw.text([0, 240],
                              u'气温 ' + weather['day_temp'] + u'/' +
                              weather['night_temp'],
                              font=font_song_small)
                else:
                    draw.text([0, 240],
                              u'气温 ' + weather['day_temp'],
                              font=font_song_small)
                draw.text([0, 270],
                          u'风力 ' + weather['wind_dir'] + weather['wind_class'],
                          font=font_song_small)
                draw.line([293, 240, 293, 290], fill=0)
                draw.text([240, 240],
                          u'明日 ' + weather['tomorrow_weather'],
                          font=font_song_small)
                draw.text([240, 270],
                          u'天气 ' + weather['tomorrow_temp'],
                          font=font_song_small)
                isfailed = False

            except Exception, e:
                print e
                draw.rectangle([0, 102, 399, 299], fill='white')
                draw.text([0, 200], u'数据获取失败!请检查网络连接!', font=font_song_small)
                isfailed = True
                #epd.display_frame(epd.get_frame_buffer(image))

        if isfailed == False:
            count = count + 1

        if count == 20:
            count = 0

        epd.display_frame(epd.get_frame_buffer(image))
        time.sleep(60)
示例#31
0

if __name__ == "__main__":
    mic_on()
    clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientsock.connect((host, port))

    sf = clientsock.makefile('rb')

    while True:
        line = sf.readline().decode('utf-8')
        if line.find('WHYPO') != -1:
            print(line)
            if line.find(u'C1') != -1:
                mic_off()
                jtalk(gw.get_weather())
                sleep(5.0)
                mic_on()
            elif line.find(u'C2') != -1:
                mic_off()
                jtalk(get_datetime())
                sleep(5.0)
                mic_on()
            elif line.find(u'C3') != -1:
                mic_off()
                jtalk(gc.get_schedule())
                sleep(5.0)
                mic_on()
            elif line.find(u'CE') != -1:
                print("error command")
示例#32
0
import get_weather
import mongo

city = 'San Francisco'

weather_data = get_weather.get_weather(city)

mongo.m_push(weather_data)

示例#33
0
                     "mental health awareness", "ptsd", "mental health matters"]

    twitter_streamer = TwitterStreamer()

    increment = 2
    cycles = 0

    while True:
        twitter_streamer.stream_tweets(hash_tag_list)

        start = datetime.datetime.now()
        start += datetime.timedelta(minutes=increment/2)
        start -= datetime.timedelta(minutes=start.minute % increment, seconds=start.second, microseconds=start.microsecond)

        time.sleep(increment*60)

        weather = get_weather()

        count = read_counter()
        reset_counter()

        write_data(str(start), count, weather[0], weather[1])

        twitter_streamer.disconnect()

        cycles += 1

        if cycles >= 5:
            backup_data(str(datetime.datetime.now()))
            cycles = 0