Browse Source

自动化预约抢购支持,程序自动去茅台页面获取下一次抢购时间

1、预约(jd_seckill reserve)成功后自动填写conf.ini中的buy_time

2、优化抢购(jd_seckill seckill)启动前的时间判断
main
pppscn 4 years ago
parent
commit
2af77d0720
  1. 3
      README.md
  2. 10
      cmd/reserve.go
  3. 79
      cmd/seckill.go
  4. 2
      cmd/version.go
  5. 19
      common/lib.go
  6. 2
      conf.ini
  7. 128
      jd_seckill/seckill.go

3
README.md

@ -3,7 +3,7 @@ helloworld
### 不定时开放群链接:https://t.me/joinchat/GsDnhtkdKJ4nbwJh ### 不定时开放群链接:https://t.me/joinchat/GsDnhtkdKJ4nbwJh
> ⚠ 此项目是[python jd_seckill](https://github.com/huanghyw/jd_seckill) 的go版本实现,旨在降低使用门和相互学习而创建。 > ⚠ 此项目是[python jd_seckill](https://github.com/huanghyw/jd_seckill) 的go版本实现,旨在降低使用门和相互学习而创建。
**go版本的jd_seckill,京东抢茅台神器,支持跨平台,使用者请在发布页下载可执行文件,欢迎pr。** **go版本的jd_seckill,京东抢茅台神器,支持跨平台,使用者请在发布页下载可执行文件,欢迎pr。**
@ -28,7 +28,6 @@ go get github.com/ztino/jd_seckill
``` ```
## 待办 ## 待办
- 自动化预约抢购支持,程序自动去茅台页面获取下一次抢购时间
- 跨平台桌面端支持,打算使用:https://github.com/therecipe/qt - 跨平台桌面端支持,打算使用:https://github.com/therecipe/qt
## 使用 ## 使用

10
cmd/reserve.go

@ -18,13 +18,13 @@ var reserveCmd = &cobra.Command{
} }
func startReserve(cmd *cobra.Command, args []string) { func startReserve(cmd *cobra.Command, args []string) {
session:=jd_seckill.NewSession(common.CookieJar) session := jd_seckill.NewSession(common.CookieJar)
err:=session.CheckLoginStatus() err := session.CheckLoginStatus()
if err!=nil { if err != nil {
log.Println("预约失败,请重新登录") log.Println("预约失败,请重新登录")
}else{ } else {
//开始预约,预约过的就重复预约 //开始预约,预约过的就重复预约
seckill:=jd_seckill.NewSeckill(common.Client,common.Config) seckill := jd_seckill.NewSeckill(common.Client, common.Config)
seckill.MakeReserve() seckill.MakeReserve()
} }
} }

79
cmd/seckill.go

@ -2,7 +2,6 @@ package cmd
import ( import (
"errors" "errors"
"fmt"
"github.com/Albert-Zhan/httpc" "github.com/Albert-Zhan/httpc"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
@ -11,13 +10,14 @@ import (
"github.com/ztino/jd_seckill/log" "github.com/ztino/jd_seckill/log"
"net/http" "net/http"
"os" "os"
"regexp"
"strconv" "strconv"
"time" "time"
) )
func init() { func init() {
rootCmd.AddCommand(seckillCmd) rootCmd.AddCommand(seckillCmd)
seckillCmd.Flags().BoolP("run","r",false,"Run directly without waiting for the time to buy") seckillCmd.Flags().BoolP("run", "r", false, "Run directly without waiting for the time to buy")
} }
var seckillCmd = &cobra.Command{ var seckillCmd = &cobra.Command{
@ -28,45 +28,70 @@ var seckillCmd = &cobra.Command{
func startSeckill(cmd *cobra.Command, args []string) { func startSeckill(cmd *cobra.Command, args []string) {
//获取是否直接运行抢购 //获取是否直接运行抢购
isRun,_:=cmd.Flags().GetBool("run") isRun, _ := cmd.Flags().GetBool("run")
session:=jd_seckill.NewSession(common.CookieJar) session := jd_seckill.NewSession(common.CookieJar)
err:=session.CheckLoginStatus() err := session.CheckLoginStatus()
if err!=nil { if err != nil {
log.Println("抢购失败,请重新登录") log.Println("抢购失败,请重新登录")
}else{ } else {
//活跃用户会话,当会话失效自动退出程序 //活跃用户会话,当会话失效自动退出程序
user:=jd_seckill.NewUser(common.Client,common.Config) user := jd_seckill.NewUser(common.Client, common.Config)
go KeepSession(user) go KeepSession(user)
seckill := jd_seckill.NewSeckill(common.Client, common.Config)
//直接运行抢购跳过等待抢购时间 //直接运行抢购跳过等待抢购时间
if !isRun { if !isRun {
//获取本地时间与京东云端时间差
diffTime := seckill.GetDiffTime()
//获取抢购时间
buyDate := common.Config.MustValue("config", "buy_time", "")
buyTimeReg := regexp.MustCompile(`(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})`)
buyTimeArr := buyTimeReg.FindAllString(buyDate, 1)
if len(buyTimeArr) == 1 {
buyDate = buyTimeArr[0]
} else {
_, buyTimeArr, err := seckill.GetWareBusiness()
if err != nil || len(buyTimeArr) != 2 {
log.Println("请设置conf.ini中的抢购时间(buy_time)")
os.Exit(0)
}
buyDate = buyTimeArr[0] + ":00"
}
//计算抢购时间 //计算抢购时间
nowLocalTime:=time.Now().UnixNano()/1e6
jdTime,_:=GetJdTime()
buyDate:=common.Config.MustValue("config","buy_time","")
loc, _ := time.LoadLocation("Local") loc, _ := time.LoadLocation("Local")
t,_:=time.ParseInLocation("2006-01-02 15:04:05",buyDate,loc) t, _ := time.ParseInLocation("2006-01-02 15:04:05", buyDate, loc)
buyTime:=t.UnixNano()/1e6 buyTime := t.UnixNano()/1e6 + diffTime
diffTime:=nowLocalTime-jdTime
log.Println(fmt.Sprintf("正在等待到达设定时间:%s,检测本地时间与京东服务器时间误差为【%d】毫秒",buyDate,diffTime)) //抢购总时间读取配置文件
timerTime:=(buyTime+diffTime)-jdTime str := common.Config.MustValue("config", "seckill_time", "2")
if timerTime<=0 { seckillTime, err := strconv.Atoi(str)
log.Println("请设置抢购时间") if err != nil {
seckillTime = 2
}
timerTime := buyTime - time.Now().UnixNano()/1e6
if timerTime >= 0 { //等待抢购
log.Println("还没到达抢购时间:", buyDate, ",等待中...")
time.Sleep(time.Duration(timerTime) * time.Millisecond)
log.Println("时间到达,开始抢购……")
} else if timerTime <= int64(-seckillTime*6e4) {
log.Println("已经超过抢购时间(", buyDate, ")不止", seckillTime, "分钟,败局已定,下次请早!")
os.Exit(0) os.Exit(0)
} else {
log.Println("您已经错过抢购时间,但还在抢购总时间(", seckillTime, "分钟)内,直接执行抢购,祝您好运!")
} }
//等待抢购 } else {
time.Sleep(time.Duration(timerTime)*time.Millisecond)
//开始抢购
log.Println("时间到达,开始执行……")
}else{
log.Println("开始执行……") log.Println("开始执行……")
} }
seckill:=jd_seckill.NewSeckill(common.Client,common.Config)
//开启抢购任务,第二个参数为开启几个协程 //开启抢购任务,第二个参数为开启几个协程
//怕封号的可以减少协程数量,相反抢到的成功率也减低了 //怕封号的可以减少协程数量,相反抢到的成功率也减低了
//抢购任务数读取配置文件 //抢购任务数读取配置文件
str:=common.Config.MustValue("config","task_num","5") str := common.Config.MustValue("config", "task_num", "5")
taskNum,_:=strconv.Atoi(str) taskNum, _ := strconv.Atoi(str)
Start(seckill,taskNum) Start(seckill, taskNum)
} }
} }

2
cmd/version.go

@ -15,6 +15,6 @@ var versionCmd = &cobra.Command{
Use: "version", Use: "version",
Short: "Print the version number of jd_seckill", Short: "Print the version number of jd_seckill",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println(fmt.Sprintf("%s version %s %s %s/%s",common.SoftName,common.SoftName,common.Version,runtime.GOOS,runtime.GOARCH)) fmt.Println(fmt.Sprintf("%s version %s %s %s/%s", common.SoftName, common.SoftName, common.Version, runtime.GOOS, runtime.GOARCH))
}, },
} }

19
common/lib.go

@ -101,7 +101,7 @@ func Exists(path string) bool {
} }
func OpenImage(qrPath string) { func OpenImage(qrPath string) {
if runtime.GOOS == "windows" {//windows if runtime.GOOS == "windows" { //windows
cmd := exec.Command("cmd", "/c", "rundll32.exe", "C:\\Windows\\System32\\shimgvw.dll,ImageView_FullscreenA", qrPath) cmd := exec.Command("cmd", "/c", "rundll32.exe", "C:\\Windows\\System32\\shimgvw.dll,ImageView_FullscreenA", qrPath)
_ = cmd.Start() _ = cmd.Start()
//扫码后二维码自动删除,自动关闭照片查看器 //扫码后二维码自动删除,自动关闭照片查看器
@ -114,10 +114,10 @@ func OpenImage(qrPath string) {
} }
} }
}() }()
}else if runtime.GOOS == "darwin" {//Macos } else if runtime.GOOS == "darwin" { //Macos
cmd := exec.Command("open", qrPath) cmd := exec.Command("open", qrPath)
_ = cmd.Start() _ = cmd.Start()
}else{ } else {
//linux或者其他系统 //linux或者其他系统
file, _ := os.Open(qrPath) file, _ := os.Open(qrPath)
img, _, _ := image.Decode(file) img, _, _ := image.Decode(file)
@ -129,3 +129,16 @@ func OpenImage(qrPath string) {
fmt.Println(qr.ToSmallString(false)) fmt.Println(qr.ToSmallString(false))
} }
} }
//指定位数随机数
func RandomNumber(len int) string {
var container string
var str = "0123456789"
b := bytes.NewBufferString(str)
length := b.Len()
rand.Seed(time.Now().UnixNano())
for i := 0; i < len; i++ {
container += string(str[rand.Intn(length)])
}
return container
}

2
conf.ini

@ -9,7 +9,7 @@ fp =
sku_id = 100012043978 sku_id = 100012043978
# 抢购数量 # 抢购数量
seckill_num = 2 seckill_num = 2
# 抢购开始时间设定 2021-01-01 09:59:59 # 抢购开始时间设定 2021-01-01 09:59:59 (PS.预约成功后会自动更新)
buy_time = 2021-01-01 09:59:59 buy_time = 2021-01-01 09:59:59
# 抢购总时间,单位:分钟,默认两分钟 # 抢购总时间,单位:分钟,默认两分钟
seckill_time = seckill_time =

128
jd_seckill/seckill.go

@ -11,6 +11,9 @@ import (
"github.com/ztino/jd_seckill/log" "github.com/ztino/jd_seckill/log"
"github.com/ztino/jd_seckill/service" "github.com/ztino/jd_seckill/service"
"net/http" "net/http"
"net/url"
"os"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -42,7 +45,103 @@ func (this *Seckill) SkuTitle() (string, error) {
return strings.TrimSpace(doc.Find(".sku-name").Text()), nil return strings.TrimSpace(doc.Find(".sku-name").Text()), nil
} }
func (this *Seckill) GetDiffTime() int64 {
log.Println("获取本地时间与京东云端时间差")
localTime := time.Now().UnixNano() / 1e6
log.Println("本地系统时间:", time.Unix(0, localTime*1e6))
jdTime := localTime
req := httpc.NewRequest(common.Client)
resp, body, err := req.SetUrl("https://a.jd.com//ajax/queryServerData.html").SetMethod("get").Send().End()
if err != nil || resp.StatusCode != http.StatusOK {
log.Println("获取京东服务器时间失败,以本地时间为准")
} else {
jdTime = gjson.Get(body, "serverTime").Int()
}
log.Println("京东云端时间:", time.Unix(0, jdTime*1e6))
delayTime := time.Now().UnixNano()/1e6 - localTime
log.Println("网络请求延时:", delayTime, "ms")
diffTime := localTime - jdTime + delayTime/2
log.Println("实际时间误差:", diffTime, "ms (本地时间-京东云端时间+网络请求延时/2)")
return diffTime
}
func (this *Seckill) GetWareBusiness() ([]string, []string, error) {
log.Println("获取商品的预约时间、抢购时间")
skuId := this.conf.MustValue("config", "sku_id", "") //商品ID
cat := "12259,12260,9435" //分类路径,TODO:适配其他商品时要调整
area := "16_1303_3484_0" //配送至,TODO:适配其他商品时要调整成购买者实际地区
shopId := "1000085463" //卖家ID
venderId := "1000085463" //供应商ID
paramJson := "{\"platform2\":\"1\",\"specialAttrStr\":\"p0pp1pppppppppppppppp\",\"skuMarkStr\":\"00\"}" //TODO:不知道干嘛用的?
num := this.conf.MustValue("config", "seckill_num", "1") //购买数量
req := httpc.NewRequest(this.client)
req.SetHeader("User-Agent", this.getUserAgent())
req.SetHeader("Referer", fmt.Sprintf("https://item.jd.com/%s.html", skuId))
resp, body, err := req.SetUrl(fmt.Sprintf("https://item-soa.jd.com/getWareBusiness?callback=jQuery%s&skuId=%s&cat=%s&area=%s&shopId=%s&venderId=%s&paramJson=%s&num=%s&_=%s",
common.RandomNumber(7),
skuId,
cat,
area,
shopId,
venderId,
url.QueryEscape(paramJson),
num,
strconv.Itoa(int(time.Now().Unix()*1000)),
)).SetMethod("get").Send().End()
var yuyueTimeArr []string
var buyTimeArr []string
if err != nil || resp.StatusCode != http.StatusOK {
log.Println("获取商品详情失败", resp, body, err)
return yuyueTimeArr, buyTimeArr, errors.New("访问商品详情失败")
}
if !gjson.Get(body, "yuyueInfo").Exists() || !gjson.Get(body, "yuyueInfo.yuyueTime").Exists() || !gjson.Get(body, "yuyueInfo.buyTime").Exists() {
log.Println("获取商品预约信息失败", body)
return yuyueTimeArr, buyTimeArr, errors.New("获取商品预约信息失败")
}
yuyueTime := gjson.Get(body, "yuyueInfo.yuyueTime").String()
buyTime := gjson.Get(body, "yuyueInfo.buyTime").String()
log.Println("预约起止时间:", yuyueTime)
log.Println("购买起止时间:", buyTime)
reg := regexp.MustCompile(`(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2})`)
yuyueTimeArr = reg.FindAllString(yuyueTime, 2)
buyTimeArr = reg.FindAllString(buyTime, 2)
return yuyueTimeArr, buyTimeArr, nil
}
func (this *Seckill) MakeReserve() { func (this *Seckill) MakeReserve() {
yuyueTimeArr, buyTimeArr, err := this.GetWareBusiness()
if err == nil && len(yuyueTimeArr) == 2 {
diffTime := this.GetDiffTime()
loc, _ := time.LoadLocation("Local")
yuyueTimeBegin, _ := time.ParseInLocation(common.DateTimeFormatStr, yuyueTimeArr[0]+":00", loc)
yuyueTimeEnd, _ := time.ParseInLocation(common.DateTimeFormatStr, yuyueTimeArr[1]+":59", loc)
beginTime := yuyueTimeBegin.UnixNano()/1e6 + diffTime
endTime := yuyueTimeEnd.UnixNano()/1e6 + diffTime
diffTime = beginTime - time.Now().UnixNano()/1e6
if diffTime > 0 {
log.Println("还没到预约时间,等待", diffTime, "ms 后开始预约")
time.Sleep(time.Duration(diffTime) * time.Millisecond)
}
diffTime = time.Now().UnixNano()/1e6 - endTime
if diffTime > 0 {
log.Println("您已经错过预约时间,下次请早!")
os.Exit(0)
}
} else {
log.Println("预约起始时间获取失败,立即尝试预约:", err, yuyueTimeArr)
}
user := NewUser(this.client, this.conf) user := NewUser(this.client, this.conf)
userInfo, _ := user.GetUserInfo() userInfo, _ := user.GetUserInfo()
log.Println("用户:" + userInfo) log.Println("用户:" + userInfo)
@ -63,9 +162,26 @@ func (this *Seckill) MakeReserve() {
reserveUrl := gjson.Get(body, "url").String() reserveUrl := gjson.Get(body, "url").String()
req = httpc.NewRequest(this.client) req = httpc.NewRequest(this.client)
_, _, _ = req.SetUrl("https:" + reserveUrl).SetMethod("get").Send().End() _, _, _ = req.SetUrl("https:" + reserveUrl).SetMethod("get").Send().End()
msg := "预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约![我的预约](https://yushou.jd.com/member/qualificationList.action)" msg := "商品名称《" + shopTitle + "》预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约!\n\n[我的预约](https://yushou.jd.com/member/qualificationList.action)"
_ = service.SendMessage(this.conf, "茅台抢购通知", msg) _ = service.SendMessage(this.conf, "京东秒杀通知", msg)
log.Println(msg) log.Println(msg)
//更新购买时间
if len(buyTimeArr) == 2 {
confFile := "./conf.ini"
cfg, err := goconfig.LoadConfigFile(confFile)
if err != nil {
log.Println("配置文件不存在,程序退出")
os.Exit(0)
}
buyTime := buyTimeArr[0] + ":00"
cfg.SetValue("config", "buy_time", buyTime)
if err := goconfig.SaveConfigFile(cfg, confFile); err != nil {
log.Println("保存配置文件失败,请手动修改conf.ini,buy_time =", buyTime)
}
log.Println("下一次抢购开始时间设定已经更新:", buyTime)
}
} }
} }
@ -237,13 +353,13 @@ func (this *Seckill) SubmitSeckillOrder() bool {
resp, body, err := req.SetUrl("https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action?skuId=" + skuId).SetMethod("post").Send().End() resp, body, err := req.SetUrl("https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action?skuId=" + skuId).SetMethod("post").Send().End()
if err != nil || resp.StatusCode != http.StatusOK { if err != nil || resp.StatusCode != http.StatusOK {
log.Println("抢购失败,网络错误") log.Println("抢购失败,网络错误")
_ = service.SendMessage(this.conf, "茅台抢购通知", "抢购失败,网络错误") _ = service.SendMessage(this.conf, "京东秒杀通知", "抢购失败,网络错误")
return false return false
} }
if !gjson.Valid(body) { if !gjson.Valid(body) {
log.Println("抢购失败,返回信息:" + body) log.Println("抢购失败,返回信息:" + body)
_ = service.SendMessage(this.conf, "茅台抢购通知", "抢购失败,返回信息:"+body) _ = service.SendMessage(this.conf, "京东秒杀通知", "抢购失败,返回信息:"+body)
return false return false
} }
if gjson.Get(body, "success").Bool() { if gjson.Get(body, "success").Bool() {
@ -251,11 +367,11 @@ func (this *Seckill) SubmitSeckillOrder() bool {
totalMoney := gjson.Get(body, "totalMoney").String() totalMoney := gjson.Get(body, "totalMoney").String()
payUrl := "https:" + gjson.Get(body, "pcUrl").String() payUrl := "https:" + gjson.Get(body, "pcUrl").String()
log.Println(fmt.Sprintf("抢购成功,订单号:%s, 总价:%s, 电脑端付款链接:%s", orderId, totalMoney, payUrl)) log.Println(fmt.Sprintf("抢购成功,订单号:%s, 总价:%s, 电脑端付款链接:%s", orderId, totalMoney, payUrl))
_ = service.SendMessage(this.conf, "茅台抢购通知", fmt.Sprintf("抢购成功,订单号:%s, 总价:%s, 电脑端付款链接:%s", orderId, totalMoney, payUrl)) _ = service.SendMessage(this.conf, "京东秒杀通知", fmt.Sprintf("抢购成功,订单号:%s, 总价:%s, 电脑端付款链接:%s", orderId, totalMoney, payUrl))
return true return true
} else { } else {
log.Println("抢购失败,返回信息:" + body) log.Println("抢购失败,返回信息:" + body)
_ = service.SendMessage(this.conf, "茅台抢购通知", "抢购失败,返回信息:"+body) _ = service.SendMessage(this.conf, "京东秒杀通知", "抢购失败,返回信息:"+body)
return false return false
} }
} }

Loading…
Cancel
Save