def sendTWder(event, mtext): try: money = mtext if not money == '': #匯率類幣別存在 if mtext == '@使用說明': sendUse(event) elif money in keys: rate_date = twder.now(currencies[money])[0] cashBuy = float(twder.now(currencies[money])[1]) #由匯率套件取得匯率 cashSell = float(twder.now(currencies[money])[2]) #由匯率套件取得匯率 checkBuy = float(twder.now(currencies[money])[3]) #由匯率套件取得匯率 checkSell = float(twder.now(currencies[money])[4]) #由匯率套件取得匯率 message = rate_date + '\n' + money + '匯率_(台灣銀行端)'+ '\n 現金買入 : ' + str(cashBuy) message = message + '\n 現金賣出 : ' + str(cashSell) message = message + '\n 即期買入 : ' + str(checkBuy) message = message + '\n 即期賣出 : ' + str(checkSell) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='')) else: #其他未知輸入 text =' ' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text)) except: text = '' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text))
def countingRate(citys_info, number): # 幣值換算 result = '' if citys_info[0] == "TWD": result = float(number) / float(twder.now(citys_info[1])[1]) return '%.2f' % result else: result = float(number) * float(twder.now(citys_info[0])[2]) return '%.2f' % result
def change1(c): return [ c, twder.now(c)[1], twder.now(c)[2], twder.now(c)[3], twder.now(c)[4] ]
def exchange_currency(msg): condition = msg[0:2] # 買入或賣出 msg = msg.strip(msg[0:4]) currency = msg[0:3] # 外幣代號 currency_name = getCurrencyName(currency) if currency_name == "無可支援的外幣": return "無可支援的外幣" amount = float(msg[3:]) currency = twder.now(currency) now_time = str(currency[0]) # 當下時間 content = currency_name + "最新掛牌時間為: " + now_time if condition == "賣出": # 銀行即期買入價格 # 使用者想賣外幣 buying_spot = "無資料" if currency[3] == '-' else float( currency[3]) # if-else簡寫 if buying_spot == "無資料": return "此外幣無即期買入匯率" outcome = str('%.2f ' % (amount * buying_spot)) content += '\n即期買入價格: ' + str(buying_spot) else: # 銀行即期賣出價格 # 使用者想買外幣 sold_spot = "無資料" if currency[4] == '-' else float( currency[4]) # if-else簡寫 if sold_spot == "無資料": return "此外幣無即期賣出匯率" outcome = str('%.2f ' % (amount * sold_spot)) content += '\n即期賣出價格: ' + str(sold_spot) content += "\n換匯結果為台幣" + outcome + "元" return content
def showCurrency(msg): # msg為外幣代碼 content = "" currency_name = getCurrencyName(msg) if currency_name == "無可支援的外幣": return "無可支援的外幣" # 資料格式 {貨幣代碼: (時間, 現金買入, 現金賣出, 即期買入, 即期賣出), ...} currency = twder.now(msg) # 當下時間 now_time = str(currency[0]) # 銀行現金買入價格 buying_cash = "無資料" if currency[1] == '-' else str(float(currency[1])) # 銀行現金賣出價格 sold_cash = "無資料" if currency[2] == '-' else str(float(currency[2])) # 銀行即期買入價格 buying_spot = "無資料" if currency[3] == '-' else str(float(currency[3])) # 銀行即期賣出價格 sold_spot = "無資料" if currency[4] == '-' else str(float(currency[4])) try: middle_spot = str((float(buying_spot) + float(sold_spot)) / 2) except: middle_spot = '' content += currency_name + "最新掛牌時間為: " + now_time + '\n ---------- \n 現金買入價格: ' + buying_cash + '\n 現金賣出價格: ' + str( sold_cash) + '\n 即期買入價格: ' + buying_spot + '\n 即期賣出價格: ' + sold_spot + '\n \n 即期中間價: '+ middle_spot return content
def get_exchange_rate(city): global currencies keys = currencies.keys() tlist = ['現金買入', '現金賣出', '即期買入', '即期賣出'] currency = city[0] try: if currency == '台幣': currency = city[1] except Exception: return "台幣匯率??好吧~ 1台幣=1台幣" show = currency + "匯率:\n" if currency in keys: if len(city) == 3: # 如果資料中含有數字就轉跳到幣值換算 citys_coin = [currencies[city[0]], currencies[city[1]]] return countingRate(citys_coin, city[2]) for i in range(4): try: exchange = float(twder.now(currencies[currency])[i + 1]) show = show + tlist[i] + ":" + str(exchange) + "\n" except Exception: show = show + '-\n' return show else: return "無此貨幣資料"
def getUSDBuy(): usd_price = twder.now('USD') cap_time = usd_price[0] usd_buy = usd_price[3] usd_sell = usd_price[4] print(usd_sell) if float(usd_sell) > 30: message = 'sell price ok, buy usd' lineNotifyMessage(token, message)
def getRate(currency): show = currency + '匯率:\n' if currency in keys: for i in range(4): exchange = twder.now(currencies[currency])[i+1] show = show + tlist[i] + ':' + str(exchange) + '\n' return show else: return '無此貨幣資料!'
def sendTextJ(event): #傳送文字 try: money = '日幣' if not money == '': #匯率類幣別存在 if money in keys: rate = float(twder.now(currencies[money])[3]) #由匯率套件取得匯率 message = money + '的匯率為 ' + str(rate) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message)) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='發生錯誤!'))
def look_currency_price(currency, condition, price, userID): print(userID) realtime_currency = (twder.now(currency))[4] currency_name = currency_list[currency] content = currency_name + "當前即期賣出價格為: " + str(realtime_currency) if condition == '<': content += "\n篩選條件為: < " + price if float(realtime_currency) < float(price): content += "\n符合" + realtime_currency + " < " + price + "的篩選條件" line_bot_api.push_message(userID, TextSendMessage(text=content)) elif condition == '>': content += "\n篩選條件為: > " + price if float(realtime_currency) > float(price): content += "\n符合" + realtime_currency + " > " + price + "的篩選條件" line_bot_api.push_message(userID, TextSendMessage(text=content)) elif condition == "=": content += "\n篩選條件為: = " + price
def sendTWder(event, mtext): try: # money = '美元' money = mtext if not money == '': #匯率類幣別存在 if money in keys: rate3 = float(twder.now(currencies[money])[3]) #由匯率套件取得匯率 message = money + '_即期買入匯率 : ' + str(rate3)+ '_(台灣銀行端) ' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='無此幣別匯率資料!')) else: #其他未知輸入 text = '無法了解你的意思,請重新輸入!' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text)) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='執行時產生錯誤!'))
def Converter(fare_rate): if "EUR" in fare_rate: return round( (c.get_rate('EUR', 'USD')) * float(fare_rate.split("EUR")[1]), 2) if u'\u20ac' in fare_rate: return round( (c.get_rate('EUR', 'USD')) * float(fare_rate.split(u'\u20ac')[1]), 2) if u'\xa5' in fare_rate: return round( (c.get_rate('JPY', 'USD')) * float(fare_rate.split(u'\xa5')[1]), 2) if "HK$" in fare_rate: return round( (c.get_rate('HKD', 'USD')) * float(fare_rate.split("HK$")[1]), 2) if "SEK" in fare_rate: return round( (c.get_rate('SEK', 'USD')) * float(fare_rate.split("SEK")[1]), 2) if "SGD" in fare_rate: return round( (c.get_rate('SGD', 'USD')) * float(fare_rate.split("SGD")[1]), 2) if "CZK" in fare_rate: return round( (c.get_rate('CZK', 'USD')) * float(fare_rate.split("CZK")[1]), 2) if "CNY" in fare_rate: return round( (c.get_rate('CNY', 'USD')) * float(fare_rate.split("CNY")[1]), 2) if "C$" in fare_rate: return round( (c.get_rate('CAD', 'USD')) * float(fare_rate.split("C$")[1]), 2) if "A$" in fare_rate: return round( (c.get_rate('AUD', 'USD')) * float(fare_rate.split("A$")[1]), 2) if "CHF" in fare_rate: return round( (c.get_rate('CHF', 'USD')) * float(fare_rate.split("CHF")[1]), 2) if "NT$" in fare_rate: return round( (float(fare_rate.split("NT$")[1]) / float(twder.now('USD')[1])), 2) if "PKR" in fare_rate: return round((float(fare_rate.split("PKR")[1]) / 139.10), 2) if "US$" in fare_rate: return float(fare_rate.split("US$")[1]) else: return "NA"
def showCurrency(code) -> "JPY": # code 為外幣代碼 content = "" currency_name = getCurrencyName(code) if currency_name == "無可支援的外幣": return "無可支援的外幣" # 資料格式 {貨幣代碼: (時間, 現金買入, 現金賣出, 即期買入, 即期賣出), ...} currency = twder.now(code) # 當下時間 now_time = str(currency[0]) # 銀行現金買入價格 buying_cash = "無資料" if currency[1] == '-' else str(float(currency[1])) # 銀行現金賣出價格 sold_cash = "無資料" if currency[2] == '-' else str(float(currency[2])) # 銀行即期買入價格 buying_spot = "無資料" if currency[3] == '-' else str(float(currency[3])) # 銀行即期賣出價格 sold_spot = "無資料" if currency[4] == '-' else str(float(currency[4])) content += f"{currency_name} 最新掛牌時間為: {now_time}\n ---------- \n 現金買入價格: {buying_cash}\n 現金賣出價格: {sold_cash}\n 即期買入價格: {buying_spot}\n 即期賣出價格: {sold_spot}\n \n' return content
def showCurrency(msg): content = "" # 資料格式 {貨幣代碼: (時間, 現金買入, 現金賣出, 即期買入, 即期賣出), ...} currency = twder.now(msg) currency_name = currency_list[msg] # 取得對應的貨幣名稱 # 當下時間 now_time = str(currency[0]) # 銀行現金買入價格 buying_cash = "無資料" if currency[1] == '-' else str(float(currency[1])) # 銀行現金賣出價格 sold_cash = "無資料" if currency[2] == '-' else str(float(currency[2])) # 銀行即期買入價格 buying_spot = "無資料" if currency[3] == '-' else str(float(currency[3])) # 銀行即期賣出價格 sold_spot = "無資料" if currency[4] == '-' else str(float(currency[4])) content += currency_name + "最新掛牌時間為: " + now_time + '\n ---------- \n 現金買入價格: ' + buying_cash + '\n 現金賣出價格: ' + str( sold_cash ) + '\n 即期買入價格: ' + buying_spot + '\n 即期賣出價格: ' + sold_spot + '\n \n' return content
def currencySearch(search): dollorTuple = twder.now(search) reply = '{}\n美金的即期賣出價uweee! : {}'.format(dolloarTuple[0],dolloarTuple[4]) return reply
def currencySearch(search): dollarTuple = twder.now(search) #dollarTuple = twder.now_all()[search] reply = '{}\n{},{}'.format(dollarTuple[0], search, dollarTuple[4]) return reply
def test_now(self): ret = twder.now("JPY") self.assertIsInstance(ret, tuple) self.all_element_is_str(ret)
def _currency_to_excel(self, currency): currency_data = twder.now(currency) sheet = self._get_sheet(currency) last_row = sheet.range("A1").end("down").row sheet.range((last_row + 1, 1)).value = currency_data
import twder a = twder.now('USD') b = twder.now('EUR') c = twder.now('GBP') d = twder.now('CNY') e = twder.now('JPY') f = twder.now('KRW') print('美金:現金買入, 現金賣出, 即期買入, 即期賣出', a) print('歐元:現金買入, 現金賣出, 即期買入, 即期賣出', b) print('英鎊:現金買入, 現金賣出, 即期買入, 即期賣出', c) print('人民幣:現金買入, 現金賣出, 即期買入, 即期賣出', d) print('日元:現金買入, 現金賣出, 即期買入, 即期賣出', e) print('韓元:現金買入, 現金賣出, 即期買入, 即期賣出', f)
def handle_message(event): send = event.message.text if send == '你好': userID = event.source.user_id line_bot_api.push_message( userID, StickerSendMessage(package_id='11537', sticker_id='52002745')) line_bot_api.push_message(userID, TextSendMessage(text='拿到你的ID')) message = TextSendMessage(text='hello: ' + userID) elif send == '哈囉': message = TextSendMessage(text='good bye') elif send == 'Roy' or send == 'roy': message = TextSendMessage(text=send + '是笨蛋!') elif send == '日幣' or send == 'JPY': message = TextSendMessage(text='日幣匯率是' + twder.now('JPY')[3]) elif send == '星座': message = TextSendMessage( text= '選擇星座:[1]牡羊 [2]金牛 [3]雙子 [4]巨蟹 [5]獅子 [6]處女 [7]天秤 [8]天蠍 [9]射手 [10]摩羯 [11]水瓶 [12]雙魚' ) elif send == '遊戲': ''' message = TemplateSendMessage( alt_text='Krunker.io\nhttps://krunker.io\nslither.io\nhttp://slither.io/\nSTARBLAST.IO\nhttps://starblast.io/', template=ButtonsTemplate( thumbnail_image_url='https://grizix.com/media/177/krunker-io.jpg', title='遊戲選擇', text='請選擇要玩的遊戲', actions=[ URIAction( label='Krunker.io', uri='https://krunker.io' ), URIAction( label='slither.io', uri='http://slither.io/' ), URIAction( label='STARBLAST.IO', uri='https://starblast.io/' ) ] ) ) ''' message = TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate(columns=[ CarouselColumn(thumbnail_image_url= 'https://grizix.com/media/177/krunker-io.jpg', title='Krunker.io', text='射擊遊戲', actions=[ URIAction(label='開始遊玩', uri='https://krunker.io') ]), CarouselColumn( thumbnail_image_url= 'https://edgeup.asus.com/wp-content/uploads/2016/05/thumbnail-3edce8c4b813004a352d229e6ecbbc98-696x420-1.png', title='slither.io', text='貪吃蛇', actions=[URIAction(label='開始遊玩', uri='http://slither.io') ]), CarouselColumn( thumbnail_image_url= 'https://cdn.titotu.io/images/games/starblast-io-1280x720.jpg', title='STARBLAST.IO', text='戰艦遊戲', actions=[ URIAction(label='開始遊玩', uri='https://starblast.io') ]) ])) if send.isdigit() and int(send) <= 12: message = TextSendMessage(text=astroScore(send)) line_bot_api.reply_message(event.reply_token, message)
locationName = ele[0].text # 取得縣市名 if locationName == city: target_idx = idx break # 挑選出目前想要 location 的氣象資料 tlist = ['天氣狀況', '最高溫', '最低溫', '舒適度', '降雨機率'] for i in range(5): element = locations_info[target_idx][i+1] # 取出 Wx (氣象描述) timeblock = element[1] # 取出目前時間點的資料 data = timeblock[2][0].text weather = weather + tlist[i] + ':' + data + '\n' weather = weather[:-1] #移除最後一個換行 line_bot_api.reply_message(event.reply_token, TextSendMessage(text=weather)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='無此地點天氣資料!')) ''' if not money == '': #匯率類幣別存在 if money in keys: rate = float(twder.now(currencies[money])[3]) #由匯率套件取得匯率 message = money + '的匯率為 ' + str(rate) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='無此幣別匯率資料!')) else: #其他未知輸入 text = '無法了解你的意思,請重新輸入!' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text)) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='執行時產生錯誤!'))
schedul.add_row(change1("SGD")) schedul.add_row(change1("CHF")) schedul.add_row(change1("JPY")) schedul.add_row(change1("ZAR")) schedul.add_row(change1("SEK")) schedul.add_row(change1("NZD")) schedul.add_row(change1("THB")) schedul.add_row(change1("PHP")) schedul.add_row(change1("IDR")) schedul.add_row(change1("EUR")) schedul.add_row(change1("KRW")) schedul.add_row(change1("VND")) schedul.add_row(change1("MYR")) schedul.add_row(change1("CNY")) print(schedul) print("更新時間:", twder.now("USD")[0]) continue1 = int(input("繼續查詢其他幣別?1.使用其他功能 2.離開:")) if continue1 == 2: break elif choice == 2: continue2 = 1 while continue2 == 1: print("您可以查詢以下幣別的匯率:") print(','.join(twder.currencies())) currency = input("請輸入您要查詢的幣別(請注意大小寫):") print("幣別:%s(%s)" % (currency, translate(currency))) print("現金買入匯率為:%2f" % (float(twder.now(currency)[1]))) print("現金賣出匯率為:%2f" % (float(twder.now(currency)[2]))) print("即期買入匯率為:%2f" % (float(twder.now(currency)[3]))) print("即期賣出匯率為:%2f" % (float(twder.now(currency)[4]))) continue2 = int(input("繼續查詢其他幣別?1.繼續 2.使用其他功能 3.離開:"))
def main(): today = date.today().strftime("%Y-%m-%d") # FROMAT='%(asctime)s-%(levelname)s-> %(message)s' # log_filename = "D:/python_crawler/log/exchange_rate/"+datetime.now().strftime("%Y-%m-%d_%H_%M_%S.log") #log_filename = "/Users/liuyukun/work/python_crawler/log/exchange_rate/"+datetime.now().strftime("%Y-%m-%d_%H_%M_%S.log") # logging.getLogger('').handlers=[] # logging.basicConfig(level=logging.DEBUG,filename=log_filename,format=FROMAT) config_path = 'D:\\Oracle' conf(config_path) #資料庫連線: #價格資料表 engine = create_engine('mysql+pymysql://' + conf(config_path)[2] + ':' + conf(config_path)[3] + '@' + conf(config_path)[4] + ':' + conf(config_path)[5] + '/' + conf(config_path)[0]) con = engine.connect() #爬蟲狀態資料表 engine2 = create_engine('mysql+pymysql://' + conf(config_path)[2] + ':' + conf(config_path)[3] + '@' + conf(config_path)[4] + ':' + conf(config_path)[5] + '/' + conf(config_path)[1]) con2 = engine2.connect() try: #資料list currencies = ['USD', 'CNY', 'JPY'] data_list = [] #開始時間 start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") #今天 #將貨幣帶入twder套件twder.now() for cu in currencies: data_list.append(twder.now(cu)) #logging.info(data_list) try: #貨幣日期判斷是否最新 for data, cc in zip(data_list, currencies): check_db_last_date = f'select max(date) from exchenge_rate where currency="{cc}"' #資料庫最後一天 last_date = con.execute( check_db_last_date).fetchone()[0].strftime('%Y-%m-%d') #爬蟲日期 data_date = datetime.strptime( data[0], "%Y/%m/%d %H:%M").strftime("%Y-%m-%d") logging.info(cc + "資料庫最後一天為:" + last_date + "。爬蟲日期為:" + data_date) if data_date != last_date: #logging.info(cc+"未更新至最新資料,資料整理中") time = datetime.strptime( data[0], "%Y/%m/%d %H:%M").strftime("%Y-%m-%d") cash_buy = float(data[1]) bank_buy = float(data[3]) create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = pd.DataFrame() dic = { 'date': time, 'currency': cc, 'cash_buy': cash_buy, 'bank_buy': bank_buy, 'create_time': create_time } df['date'] = dic['date'] df['currency'] = dic['currency'] df['cash_buy'] = dic['cash_buy'] df['bank_buy'] = dic['bank_buy'] df['create_time'] = dic['create_time'] df = df.append(dic, ignore_index=True) df.to_sql(name='exchenge_rate', con=con, if_exists='append', index=False) finish_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") t_num = len(currency_len(cc, today, con)) data_group = [ today, 'exchange_rate', cc, last_date, time, t_num, start_time, create_time, finish_time, 'T', 'python套件', 'exchenge_rate', datetime.now().strftime("%Y-%m-%d %H:%M:%S") ] sql = "insert into tool_crower_status2 (`time`,`crower_name`,`t_name`,`db_lastest_date`,`crower_date`,`t_num`,`start_time`,`update_time`,`finish_time`,`result`,`resource`,`for_table`,`create_time`) values('{}','{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}','{}')".format( data_group[0], data_group[1], data_group[2], data_group[3], data_group[4], data_group[5], data_group[6], data_group[7], data_group[8], data_group[9], data_group[10], data_group[11], data_group[12]) con2.execute(sql) else: #logging.info(cc+"資料庫已有最新檔案") finish_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") data_create_time = datetime.now().strftime( "%Y-%m-%d %H:%M:%S") t_num = 0 db_last_date = con.execute( check_db_last_date).fetchone()[0].strftime('%Y-%m-%d') crower_date = currency_len(cc, today, con)[0][0].strftime("%Y-%m-%d") data_group = [ today, 'exchange_rate', cc, db_last_date, crower_date, t_num, start_time, data_create_time, finish_time, 'T', 'python套件', 'exchenge_rate', data_create_time ] logging.info(data_group) sql = "insert into tool_crower_status2 (`time`,`crower_name`,`t_name`,`db_lastest_date`,`crower_date`,`t_num`,`start_time`,`update_time`,`finish_time`,`result`,`resource`,`for_table`,`create_time`) values('{}','{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}','{}')".format( data_group[0], data_group[1], data_group[2], data_group[3], data_group[4], data_group[5], data_group[6], data_group[7], data_group[8], data_group[9], data_group[10], data_group[11], data_group[12]) logging.info(sql) con2.execute(sql) except Exception as ee: logging.exception("=========Exception Logged=============") ee = str(ee) create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") error_sql = "insert tool_crower_status2 (`time`,`crower_name`,`crower_date`,`result`,`resource`,`for_table`,`error_message`,`create_time`) values('{}','{}','{}','{}','{}','{}','{}','{}')".format( today, 'exchange_rate', today, 'F', '網頁', 'exchenge_rate', ee, create_time) con2.execute(error_sql) con.close() con2.close() con.close() con2.close() except Exception as ee: logging.exception("=========Exception Logged=============") ee = str(ee) create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") error_sql = "insert tool_crower_status2 (`time`,`crower_name`,`crower_date`,`result`,`resource`,`for_table`,`error_message`,`create_time`) values('{}','{}','{}','{}','{}','{}','{}')".format( today, 'exchange_rate', today, 'F', '網頁', 'exchenge_rate', ee, create_time) con2.execute(error_sql) con.close() con2.close()
def sendLUIS(event, mtext): #LUIS try: r = requests.get( 'https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/你的Application ID?verbose=true&timezoneOffset=-360&subscription-key=你的授權碼&q=' + mtext) #終結點 result = r.json() city = '' money = '' if result['topScoringIntent']['intent'] == '縣市天氣': for en in result['entities']: if en['type'] == '地點': #由LUIS天氣類取得地點 city = en['entity'] break elif result['topScoringIntent']['intent'] == '匯率查詢': for en in result['entities']: if en['type'] == '幣別': #由LUIS匯率類取得幣別 money = en['entity'] break if not city == '': #天氣類地點存在 flagcity = False #檢查是否為縣市名稱 city = city.replace('台', '臺') #氣象局資料使用「臺」 if city in cities: #加上「市」 city += '市' flagcity = True elif city in counties: #加上「縣」 city += '縣' flagcity = True if flagcity: #是縣市名稱 weather = city + '天氣資料:\n' #由氣象局API取得氣象資料 api_link = "http://opendata.cwb.gov.tw/opendataapi?dataid=%s&authorizationkey=%s" % ( doc_name, user_key) report = requests.get(api_link).text xml_namespace = "{urn:cwb:gov:tw:cwbcommon:0.1}" root = et.fromstring(report) dataset = root.find(xml_namespace + 'dataset') locations_info = dataset.findall(xml_namespace + 'location') target_idx = -1 # 取得 <location> Elements,每個 location 就表示一個縣市資料 for idx, ele in enumerate(locations_info): locationName = ele[0].text # 取得縣市名 if locationName == city: target_idx = idx break # 挑選出目前想要 location 的氣象資料 tlist = ['天氣狀況', '最高溫', '最低溫', '舒適度', '降雨機率'] for i in range(5): element = locations_info[target_idx][i + 1] # 取出 Wx (氣象描述) timeblock = element[1] # 取出目前時間點的資料 data = timeblock[2][0].text weather = weather + tlist[i] + ':' + data + '\n' weather = weather[:-1] #移除最後一個換行 line_bot_api.reply_message(event.reply_token, TextSendMessage(text=weather)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='無此地點天氣資料!')) elif not money == '': #匯率類幣別存在 if money in keys: rate = float(twder.now(currencies[money])[3]) #由匯率套件取得匯率 message = money + '的匯率為 ' + str(rate) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=message)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='無此幣別匯率資料!')) else: #其他未知輸入 text = '無法了解你的意思,請重新輸入!' line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text)) except: line_bot_api.reply_message(event.reply_token, TextSendMessage(text='執行時產生錯誤!'))
def sendLUIS(event, mtext, userid): #LUIS try: #r = requests.get('https://westus.api.cognitive.microsoft.com/luis/v2.0/'+\ # 'apps/bb948c03-e76d-4568-b50b-3c6945e94ebb'+\ # '?staging=true&verbose=true&timezoneOffset=-480&'+\ # 'subscription-key=a6961e76af7a4698bf84b79b0ce3c5f7&q='+\ # mtext) #終結點 #result = r.json() city = '' money = '' #if result['topScoringIntent']['intent'] == '縣市天氣': mtext = mtext.replace('台', '臺') #氣象局資料使用「臺」 mtext = mtext.replace('中壢', '桃園') if mtext in cities or mtext in counties: # for en in result['entities']: # if en['type'] == '地點': #由LUIS天氣類取得地點 # city = en['entity'] # break city = mtext #elif result['topScoringIntent']['intent'] == '匯率查詢': # for en in result['entities']: # if en['type'] == '幣別': #由LUIS匯率類取得幣別 # money = en['entity'] # break elif mtext in keys: money = mtext if not city == '': #天氣類地點存在 flagcity = False #檢查是否為縣市名稱 city = city.replace('台', '臺') #氣象局資料使用「臺」 city = city.replace('中壢', '桃園') if city in cities: #加上「市」 city += '市' flagcity = True elif city in counties: #加上「縣」 city += '縣' flagcity = True if flagcity: #是縣市名稱 weather = city + '天氣資料:\n' #由氣象局API取得氣象資料 api_link = "http://opendata.cwb.gov.tw/opendataapi?dataid"\ +"=%s&authorizationkey=%s" % (doc_name,user_key) report = requests.get(api_link).text xml_namespace = "{urn:cwb:gov:tw:cwbcommon:0.1}" root = et.fromstring(report) dataset = root.find(xml_namespace + 'dataset') locations_info = dataset.findall(xml_namespace + 'location') target_idx = -1 # 取得 <location> Elements,每個 location 就表示一個縣市資料 for idx, ele in enumerate(locations_info): locationName = ele[0].text # 取得縣市名 if locationName == city: target_idx = idx break # 挑選出目前想要 location 的氣象資料 tlist = ['天氣狀況', '最高溫', '最低溫', '舒適度', '降雨機率'] for i in range(5): element = locations_info[target_idx][i + 1] # 取出 Wx (氣象描述) timeblock = element[1] # 取出目前時間點的資料 data = timeblock[2][0].text weather = weather + tlist[i] + ':' + data + '\n' weather = weather[:-1] #移除最後一個換行 line_bot_api.reply_message(event.reply_token,\ TextSendMessage(text=weather)) else: line_bot_api.reply_message(event.reply_token,\ TextSendMessage(text='無此地點天氣資料!')) elif not money == '': #匯率類幣別存在 tlist = ['現金買入', '現金賣出', '即期買入', '即期賣出'] message = '台灣銀行' + currencies[money] + '=' + money + '的匯率:\n' if money in keys: for i in range(4): exchange = twder.now(currencies[money])[i + 1] message = message + tlist[i] + '= ' + str(exchange) if i != 3: message = message + '\n' line_bot_api.reply_message(event.reply_token,\ TextSendMessage(text=message)) else: line_bot_api.reply_message(event.reply_token,\ TextSendMessage(text='無此幣別匯率資料!')) else: #其他未知輸入 #func8QnA.sendQnA(event, mtext, userid) #line_bot_api.reply_message(event.reply_token,\ # TextSendMessage(text='目前沒這功能喔')) mtext = mtext # ============================================================================= # text = '無法了解你的意思,請重新輸入!' # line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text)) # ============================================================================= except: line_bot_api.reply_message(event.reply_token,\ TextSendMessage(text='sendLUIS執行時產生錯誤!'))