Skip to content

Commit

Permalink
添加淘宝客优惠分享
Browse files Browse the repository at this point in the history
  • Loading branch information
dentonliu committed Aug 13, 2022
1 parent 1194b60 commit 888091b
Show file tree
Hide file tree
Showing 22 changed files with 1,943 additions and 371 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@
*/log
.env
*.memory-card.json
package-lock.json
package-lock.json
*.local
367 changes: 4 additions & 363 deletions README.md

Large diffs are not rendered by default.

21 changes: 17 additions & 4 deletions config/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
// 配置文件
module.exports = {
// 每日说配置项(必填项)
NAME: 'Leo_chen', //女朋友备注姓名
NICKNAME: 'Leo_chen', //女朋友昵称
NAME: '', //女朋友备注姓名
NICKNAME: '', //女朋友昵称
MEMORIAL_DAY: '2015/04/18', //你和女朋友的纪念日
CITY: '上海', //女朋友所在城市(城市名称,不要带“市”)
SENDDATE: '0 19 17 * * *', //定时发送时间 每天8点06分0秒发送,规则见 /schedule/index.js
TXAPIKEY: '天行key', //此处须填写个人申请的天行apikey,请替换成自己的 申请地址https://www.tianapi.com/signup.html?source=474284281
TXAPIKEY: '', //此处须填写个人申请的天行apikey,请替换成自己的 申请地址https://www.tianapi.com/signup.html?source=474284281

// 高级功能配置项(非必填项)
AUTOREPLY: true, //自动聊天功能 默认开启, 关闭设置为: false
DEFAULTBOT: '0', //设置默认聊天机器人 0 天行机器人 1 图灵机器人 2 天行对接的图灵机器人,需要到天行机器人官网充值(50元/年,每天1000次)
AUTOREPLYPERSON: ['Leo_chen','好友2备注'], //指定多个好友开启机器人聊天功能 指定好友的备注,最好不要带有特殊字符
AUTOREPLYPERSON: [''], //指定多个好友开启机器人聊天功能 指定好友的备注,最好不要带有特殊字符
TULINGKEY: '图灵机器人apikey',//图灵机器人apikey,需要自己到图灵机器人官网申请,并且需要认证

// (自定义) 如果你有 DIY 和基本的编程基础, 可以在这自己定义变量, 用于 js 文件访问, 包括设置简单的定时任务, 例如可以定义 task 数组
// tasks: [{nick: 'personA', time: '早上', emoji: '🌝', action: 'eat xx', date: '0 0 8 * * *'},
// {nick: 'personA', time: '午饭后', emoji: '🌞', action: 'eat xx', date: '0 0 12 * * *'},
// {nick: 'personB', time: '晚饭前', emoji: '🌔', action: 'eat xx', date: '0 0 18 * * *'},
// {nick: 'personC', time: '睡前', emoji: '🌚', action: 'sleep', date: '0 0 22 * * *'}],

// 定义优惠平台配置
coupons: {
taobao: {
enable: true,
appKey: '', // 淘宝开放平台申请的appkey
appSecret: '', // 淘宝开放平台申请的appkey
adzoneId: '', // 推广位id,格式如mm_xxx_xxx_xxx,只需要最后一个_后面的数字
groups: [
{groupName: '淘宝综合优惠群', groupMaterialId: '3756,28026,27446,13366,3786', schedule: '*/10 * * * * *'},
],
}
}
}
14 changes: 14 additions & 0 deletions coupon/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const config = require('../config/index.js')
const Taobao = require('./taobao')


function startCoupon(bot) {
if (!config.coupons) {
return
}

taobao = new Taobao(config.coupons.taobao || {})
taobao.start(bot)
}

module.exports = startCoupon
180 changes: 180 additions & 0 deletions coupon/taobao.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
const { FileBox } = require('file-box')

const ApiClient = require('./tbsdk').ApiClient
const schedule = require('../schedule')
const { wait } = require('../utils')

function Taobao(options) {
this.options = options // 加载配置
this.materials = new Map() // 初始化物料缓存
this.materialPage = new Map() // 初始化物料id的分页数据
}

/**
* 启动淘宝优惠分享
*
* @param {WechatyInterface} bot 微信机器人对象
*/
Taobao.prototype.start = function(bot) {
if (!this.options.enable) {
return
}

const groups = this.options.groups
for (let group of groups) {
schedule.setSchedule(group.schedule, async () => {
const mateiralIds = group.groupMaterialId.split(',')
this.sendMessage(bot, group.groupName, mateiralIds)
})
}
}

/**
* 发送消息
*
* @param {WechatyInterface} bot 微信机器人对象
* @param {String} groupName 群名
* @param {Array} mateiralIds 物料id数组
*/
Taobao.prototype.sendMessage = async function(bot, groupName, mateiralIds) {
// 从多个物料id中随机选取一个
const count = mateiralIds.length
const randomIndex = Math.floor(Math.random() * count)

let res = null
try {
res = await this.getMaterial(mateiralIds[randomIndex])
} catch(e) {
console.log(e)
return
}

if (res == null) {
return
}

const room = await bot.Room.find({ topic: groupName })
if (!room) {
console.log(`没有找到微信群:${groupName}`)
return
}

let shareUrl = ''
let couponAmount = 0

if (res.coupon_share_url) {
shareUrl = "https:" + res.coupon_share_url
couponAmount = res.coupon_amount
} else {
shareUrl = "https:" + res.click_url
}

const pictUrl = "https:" + res.pict_url
const title = res.title
const zkFinalPrice = res.zk_final_price
const finalPrice = (parseFloat(zkFinalPrice) - parseFloat(couponAmount)).toFixed(2)

console.log(`分享商品:${title}`)

// 发送图片
const fb = FileBox.fromUrl(pictUrl)
await room.say(fb)
await wait(2)

// 发送商品名和优惠
let text = `${title}\n【在售价】¥${zkFinalPrice}\n【券后价】¥${finalPrice}`
await room.say(text)
await wait(Math.round(Math.random() * 3))

// 发送淘口令
text = await this.createTaobaoPwd(shareUrl)
if (text === null) {
return
}

const firstIndex = text.indexOf('¥')
const lastIndex = text.indexOf('¥', firstIndex + 1)
text = text.substring(firstIndex, lastIndex + 1)
await room.say(text)
await wait(2)
}

/**
* 创建淘口令
* 接口详情:https://bigdata.taobao.com/api.htm?docId=31127&docType=2
*
* @param {String} url 联盟官方渠道获取的淘客推广链接
* @returns {String} 淘口令字符串
*/
Taobao.prototype.createTaobaoPwd = async function(url) {
try {
const res = await this.request('taobao.tbk.tpwd.create', {
url,
})

return res.data.model
} catch(e) {
console.log(e)
return null
}
}

/**
* 调用物料精选接口获取一条优惠数据
* 接口详情:https://bigdata.taobao.com/api.htm?docId=33947&docType=2
*
* @param {String|Number} materialId 官方的物料Id(详细物料id见:https://market.m.taobao.com/app/qn/toutiao-new/index-pc.html#/detail/10628875?_k=gpov9a)
* @returns {Object} 优惠信息对象
*/
Taobao.prototype.getMaterial = async function (materialId) {
if (this.materials.has(materialId) && this.materials.get(materialId).length > 0) {
return this.materials[materialId].pop()
}

let pageNo = 1
if (this.materialPage.has(materialId)) {
pageNo = this.materialPage.get(materialId) + 1
}
this.materialPage.set(materialId, pageNo)

try {
const res = await this.request('taobao.tbk.dg.optimus.material', {
'page_size': 10, // 每次取10条数据
'page_no': pageNo,
'adzone_id': this.options.adzoneId,
'material_id': materialId,
})

if (!res.result_list) {
return null
}

// 缓存数据,减少接口请求次数
this.materials[materialId] = res.result_list.map_data;
return this.materials[materialId].pop()
} catch(e) {
console.log(e)
return null
}
}

Taobao.prototype.request = function (apiname, params) {
const client = new ApiClient({
'appkey': this.options.appKey,
'appsecret': this.options.appSecret,
'REST_URL': 'http://gw.api.taobao.com/router/rest'
});

return new Promise(function(resolve, reject) {
client.execute(apiname, params, function(error, response) {
if (error) {
console.log(error)
reject(error)
}

resolve(response)
})
})
}

module.exports = Taobao
5 changes: 5 additions & 0 deletions coupon/tbsdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/Java/target
/java/.*
/bin/
/bin/
node_modules/
69 changes: 69 additions & 0 deletions coupon/tbsdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Taobao TOP API Node SDK

[淘宝开放平台](http://open.taobao.com/doc2/api_list.htm) API Node SDK

## Get Started

#### Rest API Demo
```js
ApiClient = require('../index.js').ApiClient;

var client = new ApiClient({
'appkey':'****',
'appsecret':'************************',
'REST_URL':'http://api.daily.taobao.net/router/rest'
});

client.execute('taobao.user.get',
{
'fields':'nick,type,sex,location',
'nick':'sandbox_c_1'
},
function (error,response) {
if(!error)
console.log(response);
else
console.log(error);
})
```

#### Top Message Demo

```js

var TmcClient = require('../index.js').TmcClient;

var tmcClient = new TmcClient('*******','************************','default');

tmcClient.connect('ws://mc.api.daily.taobao.net/',
function (message,status) {
console.log(message);
});

```

#### Dingtalk Message Demo

```js

DingtalkClient = require('../index.js').DingtalkClient;

var client = new DingtalkClient({
'appkey':'*****',
'appsecret':'**********************',
'REST_URL':'https://eco.taobao.com/router/rest'
});

client.execute('taobao.user.get',
{
'fields':'nick,type,sex,location',
'nick':'sandbox_c_1'
},
function (error,response) {
if(!error)
console.log(response);
else
console.log(error);
})

```
27 changes: 27 additions & 0 deletions coupon/tbsdk/examples/apiTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Module dependencies.
*/

ApiClient = require('../index.js').ApiClient;

var client = new ApiClient({
'appkey':'********',
'appsecret':'*********************',
'url':'http://gw.api.taobao.com/router/rest'
});

client.executeWithHeader('alipay.user.trade.search',
{
'page_no':1,
'page_size':100,
'start_time':'2017-03-21 00:00:00',
'end_time':'2017-03-23 23:59:59',
'session':'70000100f25719047abee9303ca8ee5d2e84f19cdd4edfb48d5e917a3e9a4aca99aaf042153472040'
},
{},
function (error,response) {
if(!error)
console.log(response);
else
console.log(error);
})
14 changes: 14 additions & 0 deletions coupon/tbsdk/examples/httpServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var http = require('http')
var spiUtil = require('../lib/spiUtil');

http.createServer(function (request, response) {
var body = [];
console.log(request.headers) ;
request.on('data', function (chunk) {
body.push(chunk);
}) ;
request.on('end', function () {
response.write(""+spiUtil.checkSignForSpi(request.url,body,request.headers,'********************'));
response.end();
});
}).listen(8888) ;
8 changes: 8 additions & 0 deletions coupon/tbsdk/examples/tmcTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var TmcClient = require('../index.js').TmcClient;

var tmcClient = new TmcClient('*****','************************','default');

tmcClient.connect('ws://mc.api.daily.taobao.net/',
function (message,status) {
console.log(message);
});
11 changes: 11 additions & 0 deletions coupon/tbsdk/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict';

var apiClient = require('./lib/api/topClient.js').TopClient;
var dingtalkClient = require('./lib/api/dingtalkClient.js').DingTalkClient;
var tmcClient = require('./lib/tmc/tmcClient.js').TmcClient;

module.exports = {
ApiClient: apiClient,
TmcClient: tmcClient,
DingTalkClient: dingtalkClient
};
Loading

0 comments on commit 888091b

Please sign in to comment.