看了市面上有很多返利机器人,自己也想动手做一个,首先我们得了解一下返利机器人的原理

返利机器人的原理是利用一种算法来跟踪和获取网络上的可用优惠券和促销活动,然后自动将这些优惠券和促销活动推送给指定的目标客户,以满足客户的需求。返利机器人能够跟踪客户的购买行为,并自动地推送更加合适的优惠券和促销活动,以提高客户的购买力和购买欲望。

第一步我们首先需要找一个平台,我找了“悦拜”这个平台,手机搜索“悦拜”,然后邀请码填一下我的吧(DHPIHT

1.首先我们要导入我们要用到的库

# coding:utf-8

import itchat
import re
import requests
import base64
import datetime
import uuid
import json
from mysqlClient import MysqlClient
from config_report import *
import time
from loguru import logger
import threading
import yagmail

2.先理清逻辑,我们建2个表吧(用户表,商品表)

# 用户表
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 DEFAULT NULL COMMENT '更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'''

3.然后写一个查询是否有返利的商品方法,这里返回的信息不要学我的写法太乱了

# 获取商品信息
def getInfo(site):
    # 用于x-auth-timestamp的值
    timeStamp = getStamp()
    # 用于x-auth-random的值
    randomBase = str2base(timeStamp)
    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'] = str(uuid.uuid4()).replace('-', '')
    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)
    except Exception as e:
        monitor(f'请求故障,请联系管理员查看机器人是否故障,报错:{e}')
        logger.error(f'请求故障,请联系管理员查看机器人是否故障,报错:{e}')

    try:
        html = json.loads(response.text)
        # 商品名称
        tradeName = html['data']['goods'][0]['goods_title']
        # 下单链接或者淘口令
        if html['data']['content'].find('http') == -1:
            selfUrl = str(html['data']['content']).replace('/', '¥')
        if html['data']['content'].find('http') != -1:
            selfUrl = html['data']['content']
        # 返利金额
        rebateMoney = str(round(float(html['data']['goods'][0]['pre_commission']) / 2, 2))
        # 原价
        originalMoney = html['data']['goods'][0]['price']
        # 券后价格
        discountMoney = html['data']['goods'][0]['after_coupon_price']
    except Exception as e:
        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回复"提现",进行提现(微信转账)'
    if selfUrl.find('http') != -1:
        info = '#######################' + '\n' + '商品名称:' + tradeName + '\n' + '下单链接:' + selfUrl + '\n' + '返利金额:' + rebateMoney + '元' + '\n' + '原    价:' + originalMoney + '元' + '\n' + '券后价格:' + discountMoney + '元' + '\n' + '#######################' + '\n' + '【返利步骤】\n1.淘宝/拼多多/京东链接发送给我\n2.点击返回的链接并下单\n3.到货确认收货后发起提现即可\n\n回复"返利",查看提现金额和冻结金额\n回复"提现",进行提现(微信转账)'

    return info, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney

4.如果客户通过你返回的链接下单了,那是不是要追踪订单信息,比如是,写一段追踪订单信息的方法

# 获取已付款,已结算,已失效订单信息,返回3个列表,格式[[商品名称,订单号],[商品名称,订单号],[商品名称,订单号]]
def getOderInfo():
    # 用于x-auth-timestamp的值
    timeStamp = getStamp()
    # 用于x-auth-random的值
    randomBase = str2base(timeStamp)
    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'
    header['x-auth-timestamp'] = timeStamp
    header['x-auth-random'] = randomBase
    header['system'] = '14.5'
    header['version'] = 'v1'
    header['x-auth-signature'] = str(uuid.uuid4()).replace('-', '')
    header['x-auth-token'] = x_auth_token
    header['Content-Length'] = '56'
    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.1.2'
    header['idfa'] = '00000000-0000-0000-0000-000000000000'
    data = {}
    data['date'] = 90
    data['page'] = 1
    data['page_size'] = 10000
    data['page_source'] = 'list'
    data['scroll_id'] = ''
    data['status'] = ''
    response = requests.post(url, headers=header, data=data)
    result = json.loads(response.text)

    paidList = []  # 已付款列表
    settledList = []  # 已结算列表
    expiredList = []  # 已失效列表
    try:
        for item in result['data']['data']:
            # print(item)
            if item['status_name'] == '已付款':
                paidList.append([item['goods_title'], item['order_id']])
            if item['status_name'] == '已结算':
                settledList.append([item['goods_title'], item['order_id']])
            if item['status_name'] == '已失效':
                expiredList.append([item['goods_title'], item['order_id']])
    except Exception as e:
        monitor(f'悦拜token可能失效了,报错:{e}')
        logger.error(f'悦拜token可能失效了,报错:{e}')
    return paidList, settledList, expiredList

5.追踪到订单信息后,要更新两个数据表

# 周期更新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()
            for paidListItem in paidList:
                updateGoods2table('1', paidListItem[1], paidListItem[0])
            for settledListItem in settledList:
                updateGoods2table('2', settledListItem[1], settledListItem[0])
            for expiredListItem in expiredList:
                updateGoods2table('3', expiredListItem[1], expiredListItem[0])
            if status == True:
                print('1212')
                break
            else:
                time.sleep(sl_time)
        except Exception as e:
            logger.error(f'报错:{e}')
            continue
# 周期更新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:
                print('2323')
                break
            else:
                time.sleep(sl_time)
        except:
            continue

 6.我们要做成微信机器人的,所以需要itchat模块(该模块现在很多微信都不能用了,笔者的微信还能用itchat,所以笔者决定用微信做机器人,也可以拿其他媒介做机器人的,比如企业微信,钉钉等等)

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    # 获取好友发送消息的内容
    content = msg['Content']
    # 匹配出消息中是否有url
    url = re.findall(r'http[s]?://(?:[a-za-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fa-f][0-9a-fa-f]))+', content)
    # 获取微信名字
    nickName = msg['User']['NickName']

    if len(url) != 0 and str(url[0]).find('eyny.com') == -1:
        # 如果是新用户,则写进userTable表中
        insertUser2table(nickName)
        # 获取返利的商品信息
        try:
            result, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney = getInfo(url[0])
            logger.info(f'{nickName}:{result}')
            # 把每一次客户查询的订单都写入到数据表goodstable中
            insertGoods2table(nickName, tradeName, selfUrl, rebateMoney, originalMoney, discountMoney)
        except:
            return '这商家太抠门了!该宝贝暂无返利!!!'
        # users = itchat.search_friends(msg['User']['NickName'])
        # userName = users[0]['UserName']
        # print(users)
        # print(userName)
        # itchat.send(result, toUserName=userName)
        # msg.user.send(result)
        return result

if __name__ == "__main__":
    logger.add('bot.log')
    itchat.auto_login(hotReload=True)
    itchat.run()

 7.返利微信机器人大概逻辑就上面所展示的,我们可以再优化一下,做一个邮件报警功能,机器人挂了第一时间通知自己,减少自己的损失,这里我们用到的是yagmail模块

# 监控模块
def monitor(content):为标题)
        subject='机器人故障',
        # contents 邮件正文
        contents=content,
    )
    # 记得关掉链接,避免浪费资源
    yag.close()