功能
定時給女朋友發送每日天氣、提醒、每日一句。
數據來源
每日一句和上面的大佬一樣也是來自ONE·一個
天氣信息來自SOJSON
實現效果
代碼說明
目錄結構
city_dict.py :城市對應編碼字典
config.yaml :設置定時時間,女友微信名稱等參數
GFWeather.py:核心代碼
requirements.txt:需要安裝的庫
run.py:項目運行類
核心代碼
GFWeather.py
class gfweather:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
}
# 女朋友的用戶id
bf_wechat_name_uuid = ''
def __init__(self):
self.city_code, self.start_datetime, self.bf_wechat_name, self.alarm_hour, self.alarm_minute = self.get_init_data()
def get_init_data(self):
'''
初始化基礎數據
:return:
'''
with open('config.yaml', 'r', encoding='utf-8') as f:
config = yaml.load(f)
city_name = config.get('city_name').strip()
start_date = config.get('start_date').strip()
wechat_name = config.get('wechat_name').strip()
alarm_timed = config.get('alarm_timed').strip()
init_msg = f"每天定時發送時間:{alarm_timed}\n女友所在城市名稱:{city_name}\n女朋友的微信暱稱:{wechat_name}\n在一起的第一天日期:{start_date}"
print(u"*" * 50)
print(init_msg)
# 根據城市名稱獲取城市編號,用於查詢天氣。查看支持的城市爲:http://cdn.sojson.com/_city.json
city_code = city_dict.city_dict.get(city_name)
if not city_code:
print('您輸出城市無法收取到天氣信息')
start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
hour, minute = [int(x) for x in alarm_timed.split(':')]
# print(hour, minute)
return city_code, start_datetime, wechat_name, hour, minute
def is_online(self, auto_login=False):
'''
判斷是否還在線,
:param auto_login:True,如果掉線了則自動登錄。
:return: True ,還在線,False 不在線了
'''
def online():
'''
通過獲取好友信息,判斷用戶是否還在線
:return: True ,還在線,False 不在線了
'''
try:
if itchat.search_friends():
return True
except:
return False
return True
if online():
return True
# 僅僅判斷是否在線
if not auto_login:
return online()
# 登陸,嘗試 5 次
for _ in range(5):
# 命令行顯示登錄二維碼
# itchat.auto_login(enableCmdQR=True)
itchat.auto_login()
if online():
print('登錄成功')
return True
else:
return False
def run(self):
# 自動登錄
if not self.is_online(auto_login=True):
return
# 定時任務
scheduler = BlockingScheduler()
# 每天9:30左右給女朋友發送每日一句
scheduler.add_job(self.start_today_info, 'cron', hour=self.alarm_hour, minute=self.alarm_minute)
scheduler.start()
def start_today_info(self):
print("*" * 50)
print('獲取相關信息...')
dictum_msg = self.get_dictum_info()
today_msg = self.get_weather_info(dictum_msg)
print(f'要發送的內容:\n{today_msg}')
if self.is_online(auto_login=True):
# 獲取好友username
if not self.bf_wechat_name_uuid:
friends = itchat.search_friends(name=self.bf_wechat_name)
if not friends:
print('暱稱錯誤')
return
self.bf_wechat_name_uuid = friends[0].get('UserName')
itchat.send(today_msg, toUserName=self.bf_wechat_name_uuid)
print('發送成功..\n')
def get_dictum_info(self):
'''
獲取格言信息(從『一個。one』獲取信息 http://wufazhuce.com/)
:return: str 一句格言或者短語
'''
print('獲取格言信息..')
user_url = 'http://wufazhuce.com/'
resp = requests.get(user_url, headers=self.headers)
soup_texts = BeautifulSoup(resp.text, 'lxml')
# 『one -個』 中的每日一句
every_msg = soup_texts.find_all('div', class_='fp-one-cita')[0].find('a').text
return every_msg
def get_weather_info(self, dictum_msg=''):
'''
獲取天氣信息。網址:https://www.sojson.com/blog/305.html
:param dictum_msg: 發送給朋友的信息
:return:
'''
print('獲取天氣信息..')
weather_url = f'http://t.weather.sojson.com/api/weather/city/{self.city_code}'
resp = requests.get(url=weather_url)
if resp.status_code == 200 and resp.json().get('status') == 200:
weatherJson = resp.json()
# 今日天氣
today_weather = weatherJson.get('data').get('forecast')[1]
locale.setlocale(locale.LC_CTYPE, 'chinese')
today_time = datetime.now().strftime('"%Y年%m月%d日 %H:%M:%S"')
# 今日天氣注意事項
notice = today_weather.get('notice')
# 溫度
high = today_weather.get('high')
high_c = high[high.find(' ') + 1:]
low = today_weather.get('low')
low_c = low[low.find(' ') + 1:]
temperature = f"溫度 : {low_c}/{high_c}"
# 風
fx = today_weather.get('fx')
fl = today_weather.get('fl')
wind = f"{fx} : {fl}"
# 空氣指數
aqi = today_weather.get('aqi')
aqi = f"空氣 : {aqi}"
day_delta = (datetime.now() - self.start_datetime).days
delta_msg = f'寶貝這是我們在一起的第 {day_delta} 天'
today_msg = f'{today_time}\n{delta_msg}。\n{notice}\n{temperature}\n{wind}\n{aqi}\n{dictum_msg}\n來自最愛你的我。'
return today_msg
項目運行
安裝依賴
使用 pip install -r requirements.txt 安裝所有依賴
參數配置
config.yaml
#每天定時發送的時間點,如:8:30
alarm_timed: '9:30'
# 女友所在城市名稱
city_name: '桂林'
# 你女朋友的微信名稱
wechat_name: '古典'
# 從那天開始勾搭的
start_date: '2017-11-11'
小編最近整理了一套Python學習教程,有需要的小夥伴,記得來小編的交流羣:556370268,即可免費領取一套Python學習教程哦