python自動給微信好友傳送天氣預報
阿新 • • 發佈:2019-02-01
主要思路:
1.從wxpy獲取好友列表,也可發給指定好友
2.建立定時器,也可以隨時傳送
3.定時器觸發函式
4.函式執行,遍歷好友列表
5.好友物件執行帶參函式,引數為該好友城市
6.函式中請求百度天氣介面,得到該好友對應天氣資料,解析處理資料,傳送天氣資訊,完成該物件傳送。
7.遍歷結束,傳送完畢
完整程式碼(程式碼具體功能參照註釋)
from wxpy import * import requests from datetime import datetime import time from apscheduler.schedulers.blocking import BlockingScheduler#定時框架 bot = Bot(cache_path=True) tuling = Tuling(api_key='4a0488cdce684468b95591a641f0971d') #機器人api def send_weather(location): #準備url地址 path ='http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?' url = path % location response = requests.get(url) result = response.json() #如果城市錯誤就按照長春傳送天氣 if result['error'] !=0: location ='長春' url = path % location response = requests.get(url) result = response.json() str0 = (' 你好!這是今天的天氣預報!\n機器人:PyChatBot\n') results = result['results'] # 取出資料字典 data1 = results[0] # 取出城市 city = data1['currentCity'] str1 =' 你的城市: %s\n' % city # 取出pm2.5值 pm25 = data1['pm25'] str2 =' Pm值 : %s\n' % pm25 # 將字串轉換為整數 否則無法比較大小 pm25 = int(pm25) if pm25 =='': pm25 =0 # 通過pm2.5的值大小判斷汙染指數 if 0 <= pm25 <35: pollution ='優' elif 35 <= pm25 <75: pollution ='良' elif 75 <= pm25 <115: pollution ='輕度汙染' elif 115 <= pm25 <150: pollution ='中度汙染' elif 150 <= pm25 <250: pollution ='重度汙染' elif pm25 >=250: pollution ='嚴重汙染' str3 =' 汙染指數: %s\n' % pollution result1 = results[0] weather_data = result1['weather_data'] data = weather_data[0] temperature_now = data['date'] str4 =' 當前溫度: %s\n' % temperature_now wind = data['wind'] str5 =' 風向 : %s\n' % wind weather = data['weather'] str6 =' 天氣 : %s\n' % weather str7 =' 溫度 : %s\n' % data['temperature'] message = data1['index'] str8 =' 穿衣 : %s\n' % message[0]['des'] str9 =' 我很貼心: %s\n' % message[2]['des'] str10 =' 運動 : %s\n' % message[3]['des'] str11 =' 紫外線 : %s\n' % message[4]['des'] str12="\n祝您生活愉快--微笑向暖\n" str = str0 + str1 + str2 + str3 + str4 + str5 + str6 + str7 + str8 + str9 + str10 + str11+ str12 return str #好友列表 #my_friends = [] #my_friends = bot.friends() #my_friends.pop(0) friend = bot.friends().search('好友暱稱或好友備註')[0]#好友的微信暱稱,或者你存取的備註 print(friend) #傳送函式 def send_message(): #給全體好友傳送------------------ # for friend in my_friends: # friend.send(send_weather(friend.city)) #------------------------------------- #給單個好友傳送訊息----------------- friend.send(send_weather(friend.city)) #傳送成功通知我 bot.file_helper.send(send_weather('長春')) bot.file_helper.send('傳送完畢') #定時器 print('star') """ #定時操作 sched = BlockingScheduler() sched.add_job(send_message,'cron',month='1-12',day='1-31',hour=15,minute =49)#設定傳送的時間 sched.start() """ send_message()#執行程式時直接傳送
執行效果:
傳送成功後,檔案助手有所提示: