python 實現微信發送消息


背景:利用Python來登入你個人的手機微信,之后向朋友發送消息,發送的消息可以來源於網頁。下面的例子就是取得當前日元的匯率,之后發送自己的某一個朋友的手機上

環境:Python3,JetBrains PyCharm Community Edition 2018.2.4 x64,window7

實現的效果如下:

匯率的消息來源於網頁

 

具體實現:

import json
from threading import Timer
from wxpy import *
import requests
import urllib.parse

def get_news():
    '''獲取金山詞霸每日一句'''
    url = 'http://open.iciba.com/dsapi'
    r = requests.get(url)
    content = r.json()['content']
    note = r.json()['note']
    return content, note

def send_news():
    val = getRequest()
    mssage = u'今天的日元匯率為:%s' % val
    bot = Bot()  # 連接微信,會出現一個登陸微信的二維碼
    try:
        # my_friends =bot.friends().search(u'XXX')[0]#這里是你微信好友的昵稱
        friends = bot.friends()
        for i in friends:
            name = i
            if "XXX" == name.name:
                print(name)
            else:
                print(name)
                break
        # my_friend.send(contents[0])
        # my_friend.send(contents[1])
        name.send(mssage)
        t = Timer(86400, send_news)  # 這里是一天發送一次,86400s = 24h
        t.start()
    except:
        my_friend = bot.friends().search('filehelper')[0]
        my_friend.send(u'今天消息發送失敗了')

def getRequest():
    _header = getHeader()
    _data = urllib.parse.urlencode(getData()).encode('utf-8')
    url = 'https://webapi.huilv.cc/api/trend/yaho'
    response = requests.post(url, data=_data, headers=_header)

    print(response.encoding)
    print(response.apparent_encoding)
    r = response.text
    result_text = json.loads(r, encoding='utf-8')
    val = result_text["obj"][len(result_text["obj"]) -1 ]["huilv"]
    return val

def getHeader():
    header = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Referer': 'https://www.huilv.cc/zoushitu?a=JPYCNY&time=d1',
        'Sec-Fetch-Mode': 'cors',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
    }
    return header

def getData():
    paydata = {
        'pinzhong': 'JPYCNY',
        'longs': 'd1'
    }
    return paydata

if __name__ == '__main__':
    get_news()
    send_news()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM