之前写了一篇python基于个人微信的机器人用python自己开发一个返利机器人_悦拜邀请码168000-CSDN博客文章浏览阅读4.6k次,点赞4次,收藏19次。用python自己租一个返利机器人,对应的平台是悦拜,邀请:DHPIHT_悦拜邀请码168000 https://blog.csdn.net/weixin_40894428/article/details/129677196?ops_request_misc=%257B%2522request%255Fid%2522%253A%25229cac2546ddcdf69757793eeacff1c494%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=9cac2546ddcdf69757793eeacff1c494&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-6-129677196-null-null.142^v102^pc_search_result_base2&utm_term=%E8%BF%94%E5%88%A9%E6%9C%BA%E5%99%A8%E4%BA%BA&spm=1018.2226.3001.4187但因为itchat这个模块经常掉线,故而把机器人转移到微信公众号(目前没有掉线过),这次我打算把代码开源(这篇文章只是教大家部署,有疑问的可以给我留言一下 ),分享给大家(也希望大家注册时填一下我的要庆马:DHPIHT,也算是物质交换了,因为邀请朋友是可以升级,后续fanli更多的),本文章,需要有一点python基础和想赚点外快的同学使用

准备工作
1.一台服务器(我买的腾讯云的99一年,刚好有活动)
2.一个微信公众号
3.一个域名(也是在腾讯云买的,可以不用备案,但最好备案一下)


需要改成自己的参数
1.悦拜的token
2.邮箱及邮箱授权码
3.自己的mysql数据库信息
4.自己的悦拜邀请码

公众号的配置
1.填写自己的域名
2.令牌(可随便填)
 

配置起来不麻烦,下面先上代码(一共3个py文件)

demo.py 

# coding:utf-8
from flask import Flask, request, abort, Response, jsonify
import xmltodict
import re
import requests
import base64
import datetime
import json
from mysqlClient import MysqlClient
from config_report import *
import time
from loguru import logger
import threading
import yagmail
import hashlib
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

app = Flask(__name__)


# 时间戳转base码
def str2base(timeStamp):
    time_base64 = base64.b64encode(timeStamp.encode())
    return time_base64.decode()


# 获取13位时间戳
def getStamp():
    timestamp = int(datetime.datetime.now().timestamp() * 1000)
    return str(timestamp)


# 加盐算法
def calculate_signature(timestamp, base64_timestamp):
    secret = "YEqQJIyOzUABvTon"
    step1 = timestamp + base64_timestamp
    hash1 = hashlib.md5(step1.encode()).hexdigest()
    step2 = hash1 + secret
    signature = hashlib.md5(step2.encode()).hexdigest()
    return signature


# 把新用户写入userTable表中
def insertUser2table(nickName):
    createTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    insertSql = '''INSERT IGNORE INTO usertable (nickName, createTime) value ("%s", "%s");''' % (str(nickName), createTime)
    mysql_client.insert(insertSql)


# 把商品信息写入goodstable表中
def insertGoods2table(nickName, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney):
    createTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    insertSql = '''INSERT INTO goodstable (nickName, goodsName, url_tkl, returnMoney, price, specialPrice, orderStatus, createTime, isReply) value ("%s", "%s", "%s", "%s","%s", "%s","%s", "%s", "%s");''' % (
        nickName, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney, '0', createTime, '0')
    mysql_client.insert(insertSql)


# 更新商品表(已付款)
def updateGoods2tablePaid(type, orderId, goodsName, returnMoney):
    # updateTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # goodsName = '%' + str(re.sub(r'^【.*?】', '', goodsName))  # , count=1

    preSql = '''SELECT goodsname FROM goodstable WHERE goodsName = "%s" AND orderId IS NOT NULL and orderStatus not in (0, 2, 3, 4) and isReply != "0";''' % goodsName
    preDate = mysql_client.select(preSql)
    if len(preDate) >= 1:
        pass
    else:
        updateSql = '''UPDATE goodstable SET orderStatus = "%s", orderId = "%s", returnMoney = "%s", isReply = '1' WHERE goodsName = "%s" AND isReply = '0' and orderId IS NULL order by createTime  desc LIMIT 1;''' % (type, orderId, returnMoney, goodsName)
        mysql_client.update(updateSql)

# 更新商品表(已结算)
def updateGoods2tableSettled(type, orderId, goodsName, returnMoney):
    updateSql = '''update goodstable set orderStatus = "%s", returnMoney = "%s"  where goodsName = "%s" and orderId = "%s" and orderStatus != "4"''' % (type, returnMoney, goodsName, orderId)
    mysql_client.update(updateSql)

# 更新商品表(已失效)
def updateGoods2tableExpired(type, orderId, goodsName, returnMoney):
    # updateTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # goodsName = '%' + str(re.sub(r'^【.*?】', '', goodsName))  # , count=1
    updateSql = '''update goodstable set orderStatus = "%s", returnMoney = "%s"  where goodsName = "%s" and orderId = "%s"''' % (type, returnMoney, goodsName, orderId)
    mysql_client.update(updateSql)


# 通过商品链接获取商品信息
def getInfo(site, name):
    # 用于x-auth-timestamp的值
    timeStamp = getStamp()
    # 用于x-auth-random的值
    randomBase = str2base(timeStamp)
    x_auth_signature = calculate_signature(timeStamp, randomBase)
    url = 'https://app.jingxi.site/api/Goods/convertLink'
    header = {}
    header['Accept'] = 'application/json, text/plain, */*'
    header['Accept-Language'] = 'zh-CN,zh;q=0.9'
    header['Connection'] = 'keep-alive'
    header['Content-Length'] = '200'
    header['Content-Type'] = 'application/x-www-form-urlencoded'
    header['Host'] = 'app.jingxi.site'
    header['Origin'] = 'http://www.yuebai.co'
    header['Referer'] = 'http://www.yuebai.co/'
    header['sec-ch-ua'] = '"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"'
    header['sec-ch-ua-mobile'] = '?0'
    header['sec-ch-ua-platform'] = '"Windows"'
    header['Sec-Fetch-Dest'] = 'empty'
    header['Sec-Fetch-Mode'] = 'cors'
    header['Sec-Fetch-Site'] = 'cross-site'
    header[
        'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
    header['x-auth-random'] = randomBase
    header['x-auth-signature'] = x_auth_signature
    header['x-auth-timestamp'] = timeStamp

    data = {}
    data['invitation'] = 'DHPIHT'    # 这里需要换成你自己的验证码
    data['content'] = site
    data['convert_type'] = '0'
    # data['tkl_type'] = '2'
    try:
        response = requests.post(url, headers=header, data=data, verify=False)

    except Exception as e:
        monitor(f'请求故障,请联系管理员查看机器人是否故障,报错:{e}')
        logger.error(f'请求故障,请联系管理员查看机器人是否故障,报错:{e}')

    try:
        html = json.loads(response.text)
        print('wujunling', html)
        # 商品名称
        tradeName = html['data']['goods'][0]['goods_title']
        print('tradeName', tradeName)
        # 下单链接或者淘口令
        if html['data']['content'].find('http') == -1:
            selfUrl = str(html['data']['content']).replace('/', '¥')
        if html['data']['content'].find('http') != -1:
            selfUrl = html['data']['content']
            if selfUrl.find('pinduoduo') != -1 and name not in whiteList:
                return '因拼多多算法问题,现屏蔽拼多多返利...'
        # 返利金额
        rebateMoney = str(round(float(html['data']['goods'][0]['pre_commission']) * 0.9, 2))
        # 原价
        originalMoney = html['data']['goods'][0]['price']
        # 券后价格
        discountMoney = html['data']['goods'][0]['after_coupon_price']
    except Exception as e:
        if str(site).find('yangkeduo') != -1:
            return '拼多多链接不支持'
        return '这商家太抠门了!该宝贝暂无返利!'
    if selfUrl.find('http') == -1:
        info = '#######################' + '\n' + '商品名称:' + tradeName + '\n' + '口令:' + selfUrl + '\n' + '预计返利:' + rebateMoney + '元' + '\n' + '原    价:' + originalMoney + '元' + '\n' + '券后价格:' + discountMoney + '元' + '\n' + '#######################\n复制整段话打开淘宝/抖音' + '\n' + '【返利步骤】\n1.淘宝/天猫/京东/抖音链接发送给我\n2.点击返回的链接并下单\n3.到货确认收货后发起提现即可\n\n回复"返利",查看提现金额和冻结金额\n回复"提现",进行提现(微信转账)\n回复"查询",查询刚下单的订单状态\n#######################\n请注意:使用红包下单不返利(用券就可以),请自行衡量是否使用机器人下单'
    if selfUrl.find('http') != -1:
        info = '#######################' + '\n' + '商品名称:' + tradeName + '\n' + '下单链接:' + selfUrl + '\n' + '预计返利:' + rebateMoney + '元' + '\n' + '原    价:' + originalMoney + '元' + '\n' + '券后价格:' + discountMoney + '元' + '\n' + '#######################' + '\n' + '【返利步骤】\n1.淘宝/天猫/京东链接发送给我\n2.点击返回的链接并下单\n3.到货确认收货后发起提现即可\n\n回复"返利",查看提现金额和冻结金额\n回复"提现",进行提现(微信转账)\n回复"查询",查询刚下单的订单状态\n#######################\n请注意:使用红包下单不返利(用券就可以),请自行衡量是否使用机器人下单'
    # print('qwer', info, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney)
    return info, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney


# 获取已付款,已结算,已失效订单信息,返回3个列表,格式[[商品名称,订单号],[商品名称,订单号],[商品名称,订单号]]
def getOderInfo():
    paidList = []  # 已付款列表                   #[[商品名称,订单号,预计返利金额]]
    settledList = []  # 已结算列表
    expiredList = []  # 已失效列表
    for i in range(1, 3):
        # 用于x-auth-timestamp的值
        timeStamp = getStamp()
        # 用于x-auth-random的值
        randomBase = str2base(timeStamp)
        x_auth_signature = calculate_signature(timeStamp, randomBase)
        url = 'https://app.yuebuy.cn/api/order/search'
        header = {}
        header['Host'] = 'app.yuebuy.cn'
        header['push-token'] = '191e35f7e0a8884bb78'
        header['User-Agent'] = 'YueBuy/4.1.2 (iPhone; iOS 14.5; Scale/2.00)'
        header['Content-Encoding'] = 'gzip, deflate, br'
        header['x-auth-timestamp'] = timeStamp
        header['x-auth-random'] = randomBase
        header['system'] = '14.5'
        header['version'] = 'v1'
        header['x-auth-signature'] = x_auth_signature
        header['x-auth-token'] = x_auth_token
        header['Content-Length'] = '66'
        header['platform'] = 'iOS'
        header['Connection'] = 'keep-alive'
        header['Accept-Language'] = 'zh-Hans-CN;q=1'
        header['model'] = 'iPhone XR'
        header['Accept'] = '*/*'
        header['Content-Type'] = 'application/x-www-form-urlencoded'
        # header['Accept-Encoding'] = 'gzip, deflate, br'
        header['app'] = '4.5.1'
        header['idfa'] = '00000000-0000-0000-0000-000000000000'
        data = {}
        data['keyword'] = ''
        # data['date'] = 90
        data['page'] = int(i)
        data['page_size'] = 500
        data['page_source'] = 'list'
        data['role'] = 'self'
        data['scroll_id'] = ''
        # data['status'] = ''
        response = requests.post(url, headers=header, data=data)
        result = json.loads(response.text)
        # logger.info(f'niubi:{result}')
        if str(result).find('登录状态已失效请重新登录') != -1:
            monitor(f'悦拜token失效了')
        # 这里加个[1:]是因为前面一个是没有status_name字段的, 且把< 0.01过滤掉
        # logger.info(f"fanjiawei:{result['data']['data'][1:]}")
        # try:
        #     logger.info(f"niubi22:{result['data']['data'][1:]}")
        # except Exception as e:
        #     logger.error(f"niubi11:{e}")
        for item in result['data']['data']:
            # logger.info(f'niubi1212:{item}\n')
            try:
                # 商品名称要处理一下
                goodsTitle = process_string(item['goods_title'])
                orderId = item['order_id']
                # 如果分割有3份,那这个就是京东的链接,需要对订单号做修改
                if len(str(item['order_id']).split('_')) == 3:
                    orderId = str(item['order_id']).split('_')[0] + '_' + str(item['order_id']).split('_')[2]
                    # logger.info(f'订单:{orderId}')
                if item['status_name'] == '已付款' and item['pre_commission'] != "< 0.01":
                    paidList.append([goodsTitle, orderId, item['pre_commission']])
                if item['status_name'] == '已结算' and item['pre_commission'] != "< 0.01":
                    settledList.append([goodsTitle, orderId, item['pre_commission']])
                try:
                    if item['status_name'] == '已失效' and item['pre_commission'] != "< 0.01":
                        expiredList.append([goodsTitle, orderId, item['pre_commission']])
                except:
                    if item['status_name'] == '已失效' and item['status_title'] == '无效-拆单':        # 这里如果是有无效-拆单,就找不到pre_commission这个键,会报错
                        expiredList.append([goodsTitle, orderId, '0'])
            except Exception as e:
                logger.error(f'商品信息入库时报错:{item},报错信息:{e},{item["status_name"]}')
                continue
    # print(f'已付款:{paidList}')
    # print(f'已结算:{settledList}')
    # print(f'已失效:{expiredList}')

    return paidList, settledList, expiredList

# 匹配商品名称,为了解决入库的商品名称和请求回来的商品名称有差异
def process_string(goodName):
    # result= re.findall(r'(^【.*?】)|^【.*?】(.*?)】', goodName)
    # resulr = re.findall(r'^(?:【.*?】)+', goodName)
    result = re.findall(r'【.*?】', str(re.findall(r'^(?:【.*?】)+', goodName)))
    if len(result) == 1:
        for j in result:
            goodName = goodName.replace(j, '')
            return goodName
    elif len(result) >= 2:
        for i in result:
            goodName = goodName.replace(i, '')
        # print(result[-1] + goodName)
        return result[-1] + goodName
    else:
        return goodName



# 字典转xml,用户被动回复用户, selfOpenId需要换成你自己的公众号openId
def dictToXml(userOpenId, content, selfOpenId="gh_491fd0885904"):
    respDict = {
        "xml": {
            "ToUserName": userOpenId,
            "FromUserName": selfOpenId,
            "CreateTime": int(time.time()),
            "MsgType": "text",
            "Content": content
        }
    }
    # 将字典转换为xml字符串
    respXmlStr = xmltodict.unparse(respDict)
    # print('111', respXmlStr)
    return respXmlStr


@app.route('/', methods=['GET', 'POST'])
def wechatBoat():
    if request.method == 'GET':
        token = 'fanjiawei'
        timestamp = request.args.get('timestamp', '')
        nonce = request.args.get('nonce', '')
        echostr = request.args.get('echostr', '')
        signature = request.args.get('signature', '')
        # 进行字典序排序
        sort_list = [token, timestamp, nonce].sort()
        # 拼接字符串并进行sha1加密
        try:
            result = hashlib.sha1(''.join(sort_list).encode('utf-8')).hexdigest()
        except:
            logger.warning(f'不知道哪里来的请求,,随便打发一下,请求的url:{request.url},')
            # postUrl()
            return ''
        # 判断参数是否相同
        if result == signature:
            return echostr

    if request.method == 'POST':
        # 获取微信服务器发过来的xml信息
        xmlStr = request.data
        # 把xml转换成字典
        xmlDict = xmltodict.parse(xmlStr).get('xml')
        # msgType = xmlDict.get("xml")
        msgType = xmlDict.get('MsgType')

        # 获取文本信息
        if msgType == 'text':
            # 用户id
            userOpenId = xmlDict.get('FromUserName')
            content = xmlDict.get('Content')
            # 从用户发过来的信息中提取出url链接
            url = re.findall(r'http[s]?://(?:[a-za-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fa-f][0-9a-fa-f]))+', content)
            # print('boom:', url)
            if len(url) != 0 and str(url[0]).find('eyny.com') == -1:
                # 如果是新用户,则写进usertable表中
                insertUser2table(userOpenId)
                # 获取返利的商品信息
                try:
                    try:
                        result, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney = getInfo(url[0], userOpenId)
                        logger.info(f'{userOpenId}:{result}')
                        # 把每一次客户查询的订单都写入到数据表goodstable中
                        insertGoods2table(userOpenId, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney)
                    except:
                        result = getInfo(url[0], userOpenId)
                except Exception as e:
                    return dictToXml(userOpenId, '这商家太抠门了!该宝贝暂无返利!')
                # 字段转换成xml,为了返回信息给用户
                respXmlStr = dictToXml(userOpenId, result)
                return respXmlStr

            elif content == '返利':
                # 返回返利信息时,先更新数据表
                updateUserTable(True)
                updategoodsTable(True)

                info = mysql_client.select('select returnMoney, iceMoney from usertable where nickName = "%s";' % userOpenId)
                try:
                    returnMoney = str(round(float(info[0]['returnMoney']), 2))
                except:
                    returnMoney = info[0]['returnMoney']

                try:
                    iceMoney = str(round(float(info[0]['iceMoney']), 2))
                except:
                    iceMoney = info[0]['iceMoney']
                return dictToXml(userOpenId, str('可提现金额为:' + returnMoney + '\n' + '冻结金额为:' + iceMoney + '\n下单后返利可能有延迟(不超过30分钟),有疑问请联系管理员V:FJW344326300').replace('None', '0'))


            elif content == '提现':
                # 返回提现信息时,先更新数据表
                updateUserTable(True)
                updategoodsTable(True)
                # 提现时更新提现时间
                withdrawalTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                updateSql = '''update usertable set withdrawalTime = "%s" where nickName = "%s";''' % (withdrawalTime, userOpenId)
                mysql_client.update(updateSql)
                info = mysql_client.select('select returnMoney, iceMoney from usertable where nickName = "%s";' % userOpenId)
                returnMoney = info[0]['returnMoney']
                if returnMoney == None or returnMoney == '0' or returnMoney == 'None':
                    return dictToXml(userOpenId, '可提现金额为0,请下单确认收货后再提现!')

                else:
                    monitor(str(userOpenId) + ':发起提现')
                    return dictToXml(userOpenId, '已发起提现申请,审核后打款!\n注:因公众号不能发转账,请提供收款码或者支付宝手机号')
            elif content == '查询':
                updateUserTable(True)
                updategoodsTable(True)
                # 下单成功返回给用户的逻辑
                info = mysql_client.select(
                    "select nickName, goodsName, url_tkl, returnMoney, orderId FROM goodstable where orderStatus = '1' and (isReply != '2' or isReply is NULL) and nickName = '%s';" % userOpenId)
                # logger.info(f'111{info}')
                if len(info) != 0:
                    # logger.info('king')
                    # for item in range(len(info)):
                    freezedMoney = mysql_client.select('''select sum(returnMoney) as freezedMoney from goodstable where nickName = "%s" and orderStatus = '1';''' % (userOpenId))
                    returnMoney = mysql_client.select('''select sum(returnMoney) as returnMoney from goodstable where nickName = "%s" and orderStatus = '2';''' % (userOpenId))

                    freezedMoney = freezedMoney[0]['freezedMoney']  # 冻结金额
                    returnMoneyMain = returnMoney[0]['returnMoney']  # 返利金额
                    nickName = info[0]['nickName']
                    goodsName = info[0]['goodsName']
                    url_tkl = info[0]['url_tkl']
                    returnMoney = info[0]['returnMoney']
                    orderId = info[0]['orderId']
                    response = f'''#########下单成功########\n商品名称:{goodsName}\nurl/口令:{url_tkl}\n返    利:{returnMoney}\n\n冻结金额:{str(freezedMoney).replace('None', '0')}\n可提金额:{str(returnMoneyMain).replace('None', '0')}\n#######################\n回复"返利",查看提现金额和冻结金额\n回复"提现",进行提现(微信转账)'''
                    print(response)
                    respXmlStr = dictToXml(userOpenId, response)
                    print(respXmlStr)
                    mysql_client.update(f"UPDATE `goodstable` SET `isReply` = '2' WHERE `nickName` = '{userOpenId}' AND `orderId` = '{orderId}'")
                    logger.info(f"boom{nickName}")
                    return respXmlStr
                else:
                    response = '没有在下订单或者后台还没更新,请几分钟后再尝试'
                    respXmlStr = dictToXml(userOpenId, response)
                    return respXmlStr
            else:
                return ''

        elif msgType == 'event':
            content = '感谢关注!!!\n本公众号是由我独立开发出来的,旨在帮助用户日常购物中返利\n\n使用方法:\n1.把你要购买的商品链接发送给我(淘宝,京东,抖音)\n2.我会返回一个链接或者口令,你点击链接或者口令去下单\n3.等你收到货并确认收获后,发送“提现”给我即可提现'
            respDict = {
                "xml": {
                    "ToUserName": xmlDict.get('FromUserName'),
                    "FromUserName": xmlDict.get('ToUserName'),
                    "CreateTime": int(time.time()),
                    "MsgType": "text",
                    "Content": content
                }
            }
            # 将字典转换为xml字符串
            respXmlStr = xmltodict.unparse(respDict)
            return respXmlStr

        else:
            respDict = {
                "xml": {
                    "ToUserName": xmlDict.get('FromUserName'),
                    "FromUserName": xmlDict.get('ToUserName'),
                    "CreateTime": int(time.time()),
                    "MsgType": "text",
                    "Content": '暂不支持出文本外的消息...'
                }
            }
            # 将字典转换为xml字符串
            respXmlStr = xmltodict.unparse(respDict)
            return respXmlStr


# 周期更新userTable表数据,返利总额,冻结金额
def updateUserTable(status=0):
    while True:
        try:
            n_time = int(time.time())
            sl_time = userTableTime - n_time % userTableTime
            logger.info(f'等待{str(sl_time)}秒后更新数据表userTable...')
            # time.sleep(sl_time)
            # 获取所有的客户微信名称
            allUserList = []
            user = mysql_client.select('select nickName from usertable;')
            for item in user:
                allUserList.append(item['nickName'])
            for item in allUserList:
                # 查冻结的金额
                selectSql = '''select sum(returnMoney) as freezedMoney from goodstable where nickName = "%s" and orderStatus = '1';''' % (item)
                # 查已经返利金额
                selectSqlOk = '''select sum(returnMoney) as returnMoney from goodstable where nickName = "%s" and orderStatus = '2';''' % (item)
                freezedMoney = mysql_client.select(selectSql)
                returnMoney = mysql_client.select(selectSqlOk)
                updateSql = '''update usertable set returnMoney = "%s", iceMoney = "%s" where nickName = "%s";''' % (returnMoney[0]['returnMoney'], freezedMoney[0]['freezedMoney'], item)
                mysql_client.update(updateSql)
            if status == True:
                logger.info('userTable表更新完成...')
                break
            else:
                time.sleep(sl_time)
        except:
            continue


# 周期更新goods表的订单状态
def updategoodsTable(status=0):
    while True:
        try:
            n_time = int(time.time())
            sl_time = goodsTableTime - n_time % goodsTableTime
            logger.info(f'等待{str(sl_time)}秒后更新数据表goodsTable...')
            # time.sleep(sl_time)
            # 查询后台哪些订单付款的,结算的,失效的
            paidList, settledList, expiredList = getOderInfo()
            # 失效的订单
            # expiredList = setList(paidList, expiredList)

            for paidListItem in paidList:
                updateGoods2tablePaid('1', paidListItem[1], process_string(paidListItem[0]), round(float(paidListItem[2]) * 0.9, 2))          # orderid(订单号)--》paidListItem[1], goodName(商品名称) -->> paidListItem[0]
            for settledListItem in settledList:
                updateGoods2tableSettled('2', settledListItem[1], process_string(settledListItem[0]),round(float(settledListItem[2]) * 0.9, 2))  # orderid(订单号)--》settledListItem[1], goodName(商品名称) -->> settledListItem[0]
            for expiredListItem in expiredList:
                updateGoods2tableExpired('3', expiredListItem[1], process_string(expiredListItem[0]), round(float(expiredListItem[2]) * 0.9, 2))  # orderid(订单号)--》expiredListItem[1], goodName(商品名称) -->> expiredListItem[0]
            if status == True:
                print('goodsTable表更新完成...')
                break
            else:
                time.sleep(sl_time)
        except Exception as e:
            logger.error(f'报错:{e}')
            continue


# 去除已失效中的已付款元素
def setList(paidList, expiredList):
    chongfuList = []
    for i in paidList:
        for j in expiredList:
            if i[0] == j[0]:
                chongfuList.append(j)
    for j in chongfuList:
        try:
            expiredList.remove(j)
        except:
            continue
    return expiredList

# 邮件监控,password是邮件的授权码(不是邮件密码)
def monitor(content):
    yag = yagmail.SMTP(user="344326300@qq.com", password="uljmefqjecabc", host='smtp.qq.com')
    # 发送邮件
    yag.send(
        # to 收件人,如果一个收件人用字符串,多个收件人用列表即可
        to='344326300@qq.com',
        # subject 邮件主题(也称为标题)
        subject='派大星故障',
        # contents 邮件正文
        contents=content,
    )
    # 记得关掉链接,避免浪费资源
    yag.close()


def main():
    # 创建用户表
    mysql_client.create(createUserTableSql)
    # 创建商品表
    mysql_client.create(createGoodsTable)
    t = threading.Thread(target=updateUserTable)
    t1 = threading.Thread(target=updategoodsTable)
    t.start()
    t1.start()


if __name__ == '__main__':
    logger.add('bot.log')
    mysql_client = MysqlClient()
    mysql_client.connect_mysql()
    app.run(debug=True, port=80, host='0.0.0.0')

config_report.py

# coding:utf-8

# mysql数据库
mysql_host = 'localhost'         # 数据库地址
mysql_port = 3306                # 数据库端口
mysql_user = 'root'              # 数据库账号
mysql_password = ''              # 数据库密码
mysql_db = 'sys'

# 悦拜的token,下文会有获取方式
x_auth_token = '367122232994041856-2289452-17916172'   
                
# 代理设置
#proxy = {"http": "http://127.0.0.1:7897", "https": "https://127.0.0.1:7897"}
#proxy = {"https": "https://127.0.0.1:19180"}
# 更新userTable表的数据(返利总额,冻结金额)
userTableTime = 600
# 更新goodsTable表数据(订单状态,订单号)
goodsTableTime = 600

# 拼多多白名单
# whiteList = ['要想给人留下深刻印象名字一定要长', '不是一颗星星','小乌堆', '墨守白','~白云']


# 用户表
createUserTableSql = '''CREATE TABLE If Not Exists `usertable` (
  `nickName` varchar(255) NOT NULL COMMENT '微信名字',
  `returnMoney` varchar(255) DEFAULT NULL COMMENT '返利总金额',
  `iceMoney` varchar(255) DEFAULT NULL COMMENT '冻结金额',
  `createTime` datetime DEFAULT NULL COMMENT '创建时间',
  `withdrawalTime` varchar(255) DEFAULT NULL COMMENT '提现时间',
  PRIMARY KEY (`nickName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'''


# 商品表
createGoodsTable = '''CREATE TABLE If Not Exists `goodstable` (
  `nickName` varchar(255) DEFAULT NULL COMMENT '微信名字',
  `goodsName` varchar(255) DEFAULT NULL COMMENT '商品名称',
  `url_tkl` varchar(255) DEFAULT NULL COMMENT '淘口令/下单链接',
  `returnMoney` varchar(255) DEFAULT NULL COMMENT '返利金额',
  `price` varchar(255) DEFAULT NULL COMMENT '原价',
  `specialPrice` decimal(10,2) DEFAULT NULL COMMENT '券后价',
  `orderStatus` varchar(255) DEFAULT NULL COMMENT '订单状态,0未付款,1已付款,2已结算,3已失效',
  `orderId` varchar(255) DEFAULT NULL COMMENT '订单号',
  `createTime` datetime DEFAULT NULL COMMENT '创建时间',
  `updateTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'''

mysqlClient.py

# coding:utf-8
import pymysql
from loguru import logger
import time
from config_report import *


class MysqlClient(object):
    def __init__(self):
        """
        :param host: mysql的ip
        :param port: mysql的端口
        :param user: 用户名
        :param password: 密码
        :param db: 数据库名称
        :param reconnect_num: mysql重连次数
        """
        self.host = mysql_host
        self.port = mysql_port
        self.user = mysql_user
        self.password = mysql_password
        self.db = mysql_db
        self.cursorclass = pymysql.cursors.DictCursor
        self.reconnect_num = 99999                  # 重试次数

    def connect_mysql(self):
        # 连接数据库
        try:
            self.db = pymysql.connect(host=self.host,
                                      port=self.port,
                                      user=self.user,
                                      passwd=self.password,
                                      db=self.db,
                                      cursorclass=self.cursorclass,
                                      autocommit=True,
                                      use_unicode=True,
                                      charset='utf8'
                                      )
            logger.info(f'mysql连接成功...')
        except Exception as e:
            logger.error(f'mysql连接失败,报错{e}进行重连...')
            self.reconnect_num -= 1
            if self.reconnect_num == 0:
                logger.error('连接mysql失败')
            time.sleep(5)
            self.connect_mysql()
        # 创建游标
        self.cursor = self.db.cursor()

    def select(self, sql):
        '''查询'''
        self.db.ping(reconnect=True)
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result

    def insert(self, sql):
        '''插入'''
        self.db.ping(reconnect=True)
        try:
            result = self.cursor.execute(sql)
            self.db.commit()
            return result
        except Exception as e:
            logger.error(f"插入数据异常{e},sql:{sql}")
            self.db.rollback()

    def delete(self, sql):
        '''删除'''
        self.db.ping(reconnect=True)
        try:
            result = self.cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            logger.error(f"删除数据异常{e},sql:{sql}")
            self.db.rollback()

    def create(self, sql):
        '''创建'''
        self.db.ping(reconnect=True)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            logger.error(f"创建表异常{e},sql:{sql}")
            self.db.rollback()

    def update(self, sql):
        '''更新'''
        self.db.ping(reconnect=True)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as e:
            logger.error(f"更新表异常{e},sql:{sql}")
            self.db.rollback()

    def close(self):
        '''关闭'''
        self.cursor.close()
        self.db.close()

# if __name__ == '__main__':
#     mysqlClient = MysqlConnet()
#     mysqlClient.connect_mysql()
#     mysqlClient.select('show databases;')


现在说一下悦拜的token怎么获取(用悦拜的网页版),登录自己的账号后按下面的步骤获取
悦拜: 网购用悦拜, 省的多赚的快, 一个为你的品牌生活提供性价比的创业平台网购优惠券https://www.yuebai.co/priceParity

公众号部分,去注册自己的公众号(图片不能贴出来)
微信公众平台

openid这里复制和域名的配置

运行成功截图

这是我自己的公众号机器人,你们部署成功后也是一样的功能






部署上可能有一些小细节没表达清楚,可自行通过ai解决,或者留言给我。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐