常用库、框架

itchat:https://itchat.readthedocs.io/zh/latest/
wxpy:https://wxpy.readthedocs.io/zh/latest/


微信开发

获取token

import json
import requests

def request_token():
    # 超过两小时,重新获取
    print("重新获取Token")
    payload = {
        'grant_type': 'client_credential',
        'appid': AppID,  # 公众号appid,按自己实际填写
        'secret': AppSecret,  # 待按自己实际填写
    }
    url = "https://api.weixin.qq.com/cgi-bin/token?"

    try:
        respone = requests.get(url, params=payload, timeout=50)
        if respone.json().get('errcode') == 40164:
            raise Exception(f'当前IP不在微信白名单!:{respone.text}')
            # return respone.json().get('errmsg')
        access_token = respone.json().get("access_token")
        content = {
            'access_token': str(access_token),
            'time': str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        }
        # 写入文件
        json_data = json.dumps(content)
        with open("access_token.txt", "w") as f:
            f.write(json_data)
        print("get_token", access_token)
        return access_token
    except Exception as e:
        logging.error(f'{e}')
        print(f'出错啦:{e}')


def get_token():
    if os.path.exists('access_token.txt'):
        with open("access_token.txt", "r") as f:
            content = f.read()
            data_dict = json.loads(content)
            time = datetime.datetime.strptime(data_dict["time"], '%Y-%m-%d %H:%M:%S')
        if (datetime.datetime.now() - time).seconds < 7000:
            print("未到两小时,从文件读取Token")
            return data_dict["access_token"]
        else:
            # 超过两小时
            # os.remove('access_token.txt')
            request_token()
    else:
        # 文件不存在
        request_token()

发文本消息给用户

import json
import requests

def push_msg_to_user(openid, msg):
    """
    发送信息给用户
    :param openid: openid或者FromUserName
    :param msg:
    :return:
    """
    try:
        body = {
            "touser": openid,
            "msgtype": "text",
            "text": {"content": msg}
        }
        r = requests.post(
            url="https://api.weixin.qq.com/cgi-bin/message/custom/send", params={'access_token': get_token()},
            # 发送的消息,必须是bytes类型
            data=bytes(json.dumps(body, ensure_ascii=False), encoding='utf-8')
        )
        return r.text
    except Exception as e:
        # print('发送信息失败:', e)
        logging.error(f'发送信息失败:{str(e)}')
        return False

参考:
https://www.cnblogs.com/xiao987334176/articles/9469235.html
https://blog.csdn.net/qq_29027865/article/details/81488654


小程序

小程序开发

开源小程序推荐:https://mp.weixin.qq.com/s/lNVjpp2G2ZTVCenUesb-Vg


小程序反编译

小程序反编译:https://www.jianshu.com/p/b7fdc8d1db86


杂项

扩展个人微信号

http://python.jobbole.com/84918/
http://python.jobbole.com/86532/


微信撤回消息查看

https://www.jianshu.com/p/712d19374b2e



微信硬件平台

https://iot.weixin.qq.com/wiki/new/index.html

文章作者: Leo
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LeoLan的小站
Dev Python wechat python
喜欢就支持一下吧