1. 程式人生 > >使用Python wxpy介面對自動對微信群朋友定時問候(傳送天氣預報、黃曆、每日一句)

使用Python wxpy介面對自動對微信群朋友定時問候(傳送天氣預報、黃曆、每日一句)

     在昨天的部落格https://blog.csdn.net/cskywit/article/details/81506517中使用itchat介面實現每天上午對群成員進行問候,程式比較混亂,今天看到網上對wxpy庫的使用,嘗試了一下,看了wxpy庫的文件,該庫是基於itchat的封裝,API使用更方便,於是使用之。

    採用的資料來源如下:

      每日一句:愛詞霸  http://open.iciba.com/

      以上API除了老黃曆介面均免費,返回資料均為JSON格式

     wxpy參考文件見h https://wxpy.readthedocs.io/zh/latest/bot.html

     程式碼比較簡單,使用了schedule庫對實現定時呼叫,這個是個輕量級實現定時任務的庫。程式碼附上:

# coding=utf-8
import schedule
from wxpy import *
import  json
import requests
from urllib.parse import urlencode
from datetime import datetime
import time

bot=Bot(cache_path=True) #Windows上登陸網頁微信,並儲存登陸狀態
#bot=Bot(cache_path=True,console_qr=2) #Linux伺服器終端介面上使用:
WEATHER_KEY = 'XXXXX'  # 這裡填拿到的圖靈機器人key
HUANGLI_KEY = "XXXXX"  #這裡填寫拿到的老黃曆key
def get_weather():
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key': WEATHER_KEY,
        'info': '北京今天天氣', #這裡換成你自己所在城市
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        weather=r.get('text').split(':')[1]
        return "北京今日天氣:"+weather+"\n"
    except:
        return "查詢天氣資訊失敗\n"

def get_huangli():
    data = {}
    data["appkey"] = HUANGLI_KEY
    data["year"] = datetime.now().year
    data["month"] = datetime.now().month
    data["day"] = datetime.now().day
    url_values = urlencode(data)
    url = "http://api.jisuapi.com/huangli/date" + "?" + url_values
    r = requests.get(url)
    jsonarr = json.loads(r.text)
    if jsonarr["status"] != u"0":
        print(jsonarr["msg"])
        return "今日無黃曆資訊"
    result = jsonarr["result"]
    content1='天干地支:' + ','.join(result['suici'])
    content2='今日應當注意的生肖:' + result["chong"]
    content3='宜:' + ','.join(result['yi'])
    content4='忌:' + ','.join(result['ji'])
    return '今日黃曆:'+content1+'\n'+content2+'\n'+content3+'\n'+content4+"\n"

def get_everydayWords():
    url = 'http://open.iciba.com/dsapi/'
    r =requests.get(url)
    content = json.loads(r.text)
    return '每日一句:\n'+content['content'] +'\n'+content['note']+"\n"

def get_context():
    return "美好的一天從我的問候開始:各位早上好!\n"+get_weather()+get_huangli()+get_everydayWords()+"傳送資訊時間:"+datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def SentChatRoomsMsg(name, context):
    my_group = bot.groups().search(name)[0]
    my_group.send(context)

def job():
    group_list = ['男朋友們','女朋友們']  #這裡填寫群名字,可以傳送至多個群
    content = get_context()
    for group_name in group_list:
        SentChatRoomsMsg(group_name, content)
        print('sended msg to ' + group_name +"\n"+ " content: " + content+"\n")

schedule.every().day.at("7:30").do(job)
while True:
    schedule.run_pending()#確保schedule一直執行
    time.sleep(1)
bot.join() #保證上述程式碼持續執行