示例#1
0
def message_callback():
    app.logger.info(request.json)
    entries = request.json['entry']
    for entry in entries:
        messagings = entry['messaging']
        if messagings is None:
            continue
        for m in messagings:
            if 'message' in m:
                to = m['sender']['id']
                message_bodies = [{
                    "text":
                    "I don't understand your message. (%s)" %
                    (m['message']['text'])
                }]
                post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token={token}'.format(
                    token=FB_TOKEN)
                ai_request = ai.text_request()
                ai_request.lang = 'en'  # optional, default value equal 'en'
                ai_request.query = m['message']['text']
                ai_response = json.loads(ai_request.getresponse().read())
                action = None
                parameters = None
                if "result" in ai_response:
                    action = ai_response["result"].get("action", None)
                    parameters = ai_response["result"].get("parameters", None)
                if action is not None:
                    app.logger.info("Action=%s" % (action))
                    app.logger.info("Parameters=%s" % (parameters))
                    if action == "show_weather":
                        message_bodies = fetch_weather()
                    if action == "show_news":
                        message_bodies = fetch_news(parameters['Media'])
                    if action == "show_restro":
                        message_bodies = fetch_restro(parameters['Places'])
                    if action == "say_hello":
                        message_bodies = say_hello()
                    if action == "say_goodbye":
                        message_bodies = say_goodbye()
                for message_body in message_bodies:
                    response_message = json.dumps({
                        "recipient": {
                            "id": to
                        },
                        "message": message_body
                    })
                    app.logger.info(response_message)
                    req = requests.post(
                        post_message_url,
                        headers={"Content-Type": "application/json"},
                        data=response_message)
                    app.logger.info(req.text)

    return "Done"
def say_weather(droid):
  """Speak the weather at the current location."""
  print 'Finding ZIP code.'
  location = droid.getLastKnownLocation()['result']
  addresses = droid.geocode(location['latitude'], location['longitude'])
  zip = addresses['result'][0]['postal_code']
  if zip is None:
    msg = 'Failed to find location.'
  else:
    print 'Fetching weather report.'
    result = weather.fetch_weather(zip)
    # Format the result for speech.
    msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result
  droid.speak(msg)
def notify_weather(droid):
  """Display the weather at the current location in a notification."""
  print 'Finding ZIP code.'
  location = droid.getLastKnownLocation()['result']
  addresses = droid.geocode(location['latitude'], location['longitude'])
  zip = addresses['result'][0]['postal_code']
  if zip is None:
    msg = 'Failed to find location.'
  else:
    print 'Fetching weather report.'
    result = weather.fetch_weather(zip)
    msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result
  droid.notify(msg, 'Weather Report', msg)
  droid.exit()
示例#4
0
def process_request():
    city = request.args.get('city')
    try:
        weather_str = fetch_weather(city)
        history_list.append(weather_str)
        return render_template('query.html', weather_str=weather_str)
    except KeyError:
        if request.args.get('history') == "历史":
            return render_template("history.html", history_list=history_list)

        elif request.args.get('help') == "帮助":
            return render_template('help.html')

        else:
            return render_template('404.html')
def notify_weather(droid):
  """Display the weather at the current location in a notification."""

  msg = 'Failed to find location.'
  location = droid.getLastKnownLocation().result
  location = location.get('gps') or location.get('network')
  if location is not None:
    print('Finding ZIP code.')
    addresses = droid.geocode(location['latitude'], location['longitude'])
    zip = addresses.result[0]['postal_code']
    if zip is not None:
      print('Fetching weather report.')
      result = weather.fetch_weather(zip)
      msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result
  droid.notify('Weather Report', msg)
示例#6
0
def say_weather(droid):
    """Speak the weather at the current location."""

    msg = 'Failed to find location.'
    location = droid.getLastKnownLocation().result
    location = location.get('gps') or location.get('network')
    if location is not None:
        print('Finding ZIP code.')
        addresses = droid.geocode(location['latitude'], location['longitude'])
        zip = addresses.result[0]['postal_code']
        if zip is not None:
            print('Fetching weather report.')
            result = weather.fetch_weather(zip)
            # Format the result for speech.
            msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result
    droid.ttsSpeak(msg)
示例#7
0
def say_weather(droid):
  """Speak the weather at the current location."""
  
  msg = 'Failed to find location.'
  location = droid.getLastKnownLocation().result
  location = location.get('gps') or location.get('network')
  if location is not None:
    print('Finding ZIP code.')
    addresses = droid.geocode(location['latitude'], location['longitude'])
    zip = addresses.result[0]['postal_code']
    if zip is not None:
      print('Fetching weather report.')
      result = weather.fetch_weather(zip)
      # Format the result for speech.
      msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result
  droid.ttsSpeak(msg)
示例#8
0
 def POST(self):
     try:
         webData = web.data()
         print "Handle Post webdata is ", webData  #后台打日志
         recMsg = receive.parse_xml(webData)
         print recMsg
         if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
             toUser = recMsg.FromUserName
             fromUser = recMsg.ToUserName
             city = recMsg.Content
             content = fetch_weather(city)
             replyMsg = reply.TextMsg(toUser, fromUser, content)
             return replyMsg.send()
         else:
             print "暂且不处理"
             return "success"
     except Exception, Argment:
         return Argment
def message_callback():
    app.logger.info(request.json)
    entries = request.json['entry']
    for entry in entries:
        messagings = entry['messaging']
        if messagings is None:
            continue
        for m in messagings:
            if 'message' in m:
                to = m['sender']['id']
                message_bodies = [{"text":"I don't understand your message. (%s)" % (m['message']['text'])}]
                post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token={token}'.format(token=FB_TOKEN)
                ai_request = ai.text_request()
                ai_request.lang = 'en'  # optional, default value equal 'en'
                ai_request.query = m['message']['text']
                ai_response = json.loads(ai_request.getresponse().read())
                action = None
                parameters = None
                if "result" in ai_response:
                    action = ai_response["result"].get("action", None)
                    parameters = ai_response["result"].get("parameters", None)
                if action is not None:
                    app.logger.info("Action=%s" % (action))
                    app.logger.info("Parameters=%s" % (parameters))
                    if action == "show_weather":
                        message_bodies = fetch_weather()
                    if action == "show_news":
                        message_bodies = fetch_news(parameters['Media'])
                    if action == "show_restro":
                        message_bodies = fetch_restro(parameters['Places'])
                    if action == "say_hello":
                        message_bodies = say_hello()
                    if action == "say_goodbye":
                        message_bodies = say_goodbye()
                for message_body in message_bodies:
                    response_message = json.dumps({"recipient":{"id": to}, 
                                       "message":message_body})
                    app.logger.info(response_message)
                    req = requests.post(post_message_url, 
                                headers={"Content-Type": "application/json"}, 
                                data=response_message)
                    app.logger.info(req.text)
 
    return "Done"
示例#10
0
def weather():
    args = request.args
    msg_fail = ''
    dic_fail = {'confirmation': 'fail', 'message': msg_fail}

    # check number of parameters in get request
    if len(args) > 3:
        dic_fail['message'] = 'parameters exceed 3'
        return jsonify(dic_fail)

    # get all the key value of parameters
    keys = args.keys()
    dic_pars = {'city': None, 'start': None, 'end': None}

    # check city
    if 'city' in keys:
        city = args['city']
        dic_pars['city'] = city
    else:
        dic_fail['message'] = 'city not found'
        return jsonify(dic_fail)

    # check start and end time
    if 'start' in keys:
        start = args['start']
        dic_pars['start'] = start
    if 'end' in keys:
        end = args['end']
        dic_pars['end'] = end

    result = fetch_weather(dic_pars)

    if result:
        return jsonify(result)
    else:
        return jsonify({
            'confirmation': 'success',
            'weather': 'no weather data available'
        })
示例#11
0
def app(db_name='imd_city_db'):
    run('clear')
    print(
        '[+]City Weather ::\n\n***Choose 1 from below list for first time use***\n'
    )
    ch = __get_menu__()
    if (ch == -1):
        return
    if (ch == 1):
        resp = fetch_city()
        if (not resp.get('error')):
            print('[+]Status after storing record : {}'.format(
                store_city_name_id(resp, db_name=db_name)))
            print('\n')
            for i, j in resp.items():
                print('\t{}\n'.format(i))
                for k in j:
                    for l, m in k.items():
                        print('\t\t\'{}\'  |  {}'.format(l, m))
                print('\n')
        else:
            print('[!]{} -> {}\n'.format('Error', resp.get('error', ':/')))
            resp = fetch_city_name_id(db_name=db_name)
            for i, j in resp.items():
                print('\t\t{}\t---\t{}'.format(i, j))
    elif (ch == 2):
        resp = __fetch_a_certain_city__(db_name)
        print('\n')
        for i, j in resp.items():
            print('\t{}\t---\t{}'.format(i, j))
        print('\n')
    else:
        resp = __fetch_a_certain_city__(db_name)
        print('\n')
        if (resp.get('error')):
            print('{}\n'.format(resp))
        else:
            if (len(resp.keys()) > 1):
                print('[+]Possible Matches found ...\n')
                for i, j in enumerate(resp.keys()):
                    print('\t{} -> {}'.format(i + 1, resp.get(j)))
                tmp = input('\n[?]Choose one from above >> ')
                try:
                    tmp = int(tmp)
                except ValueError as e:
                    print('[!]Error : {}'.format(str(e)))
                    return
                if (tmp not in range(1, len(resp.keys()) + 1)):
                    print('[!]Bad input')
                    return
                resp = {
                    list(resp.keys())[tmp - 1]:
                    resp.get(list(resp.keys())[tmp - 1])
                }
            else:
                print('[+]Match found :\n\t{}\n'.format(resp))
            print('[+]Fetching data ...\n')
            city_id = list(resp.keys())[0]
            weather = fetch_weather(city_id, db_name=db_name)
            if (weather.get('error')):
                print('{}\n'.format(weather))
                return
            print('[+]Weather Data :\n')
            pref_it = 'http://city.imd.gov.in/citywx/'
            color_init()
            for i, j in weather.get(city_id).items():
                if (i == 'past_24_hours_weather'):
                    print('\t{}{}{} :\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET))
                    for k, l in j.items():
                        if (k.startswith('Departure from Normal(oC)')):
                            k = 'Departure from Normal(oC)'
                        print('\t\t{:<90} ---  {}{}{}'.format(
                            k, Fore.RED, l, Fore.RESET))
                    print('\n')
                elif (i == '7_days_forecast'):
                    print('\t{}{}{} :\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET))
                    for k in j:
                        k[3] = Fore.MAGENTA + pref_it + k[3] + Fore.RESET
                        print('\t\t{} | {} | {} | {}'.format(*k))
                    print('\n')
                else:
                    print('\t{}{}{}\t---\t{}\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET, Fore.MAGENTA + pref_it + j + Fore.RESET))
            reset_all()
            print('[+]End\n')
    return
示例#12
0
import application
import weather
import news
import misc

if __name__ == '__main__':
    voice.speak(wish.wish())
    while True:
        query = voice.takeCommand()

        if 'open' in query.lower():
            websites.open_website(query)

        elif 'wikipedia' in query.lower():
            wiki.search(query)

        elif 'play' in query.lower() and 'music' in query.lower():
            song.play()

        elif 'start' in query.lower():
            application.start(query)

        elif 'weather' in query.lower():
            weather.fetch_weather()

        elif 'news' in query.lower():
            news.get_news()

        elif 'None' not in query:
            misc.misc(query)
 def do_fetch_weather(self, arg):
     """Usage: fetch_weather <city>"""
     if arg['<city>']:
         fetch_weather(arg['<city>'])