Go语言贴吧自动签到

和APP签到经验一样
和APP签到经验一样
和APP签到经验一样
重要的事情说三遍。

如果不合规我会删除该文章。

其中使用了gomod进行了导入包的版本管理,熟悉go语言的朋友知道怎么用,不熟悉怎么使用的可以留言我会解答。
全部代码下载链接: Go语言贴吧自动签到代码资源

话不多说,直接上main代码。

package main

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"os"
	"path"

	"flag"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/pkg/errors"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

var likedTiebaUrl = "https://tieba.baidu.com/mo/q/newmoindex"
var tbsUrl = "http://tieba.baidu.com/dc/common/tbs"
var signUrl = "http://c.tieba.baidu.com/c/c/forum/sign"

var BDUSS = ""
var cookies = "BDUSS=" + BDUSS

type TBSResult struct {
	Tbs     string `json:"tbs"`
	IsLogin int    `json:"is_login"`
	Error   error
}

type ForumInfo struct {
	ForumName string `json:"forum_name"`
	UserLevel string `json:"user_level"`
	UserExp   string `json:"user_exp"`
	ForumId   int64  `json:"forum_id"`
	IsLike    bool   `json:"is_like"`
	FavoType  int64  `json:"favo_type"`
	IsSign    int64  `json:"is_sign"`
}
type LikedBarsData struct {
	Uid       int64       `json:"uid"`
	Tbs       string      `json:"tbs"`
	ItbTbs    string      `json:"itb_tbs"`
	LikeForum []ForumInfo `json:"like_forum"`
}

type LIKEDBars struct {
	No              int64  `json:"no"`
	Error           string `json:"error"`
	Error2          error
	Data            LikedBarsData `json:"data"`
	UbsSampleIds    string        `json:"ubs_sample_ids"`
	UbsAbtestConfig interface{}   `json:"ubs_abtest_config"`
}

type SignResult struct {
	ErrorCode  string `json:"error_code"`
	ErrorMsg   string `json:"error_msg"`
	Info       interface{}
	Time       time.Duration `json:"time"`
	CTime      int           `json:"ctime"`
	LogId      int           `json:"logid"`
	ServerTime int           `json:"server_time"`
}

func ConfigLocalFileSystemLogger(logPath string, logFileName string, maxAge time.Duration, rotationTime time.Duration) {
	baseLogPath := path.Join(logPath, logFileName)
	fmt.Println("baseLogPath:", baseLogPath)
	writer, err := rotatelogs.New(baseLogPath+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(baseLogPath),
		rotatelogs.WithMaxAge(maxAge),
		rotatelogs.WithRotationTime(rotationTime))
	if err != nil {
		fmt.Println("config local file system logger error, detail err:", errors.WithStack(err))
	}

	lfHook := lfshook.NewHook(lfshook.WriterMap{
		logrus.DebugLevel: writer,
		logrus.InfoLevel:  writer,
		logrus.WarnLevel:  writer,
		logrus.ErrorLevel: writer,
		logrus.FatalLevel: writer,
		logrus.PanicLevel: writer}, &logrus.TextFormatter{})

	logrus.AddHook(lfHook)
}

var bduss = flag.String("bduss", "", "通过英文;隔开多个BDUSS")

func main() {
	flag.Parse()

	absDir, err := os.Getwd()
	if err != nil {
		fmt.Println("获取程序工作目录失败,错误描述:" + err.Error())
		return
	}
	logDir := absDir + "/logs"
	err = os.MkdirAll(logDir, 0777)
	if err != nil {
		fmt.Println("创建目录:", logDir, "失败")
		return
	}
	ConfigLocalFileSystemLogger("./logs", "log.log", 30*24*time.Hour, 24*time.Hour)

	if *bduss == "" {
		//get tbs
		tbsResult := GetTbs()
		if tbsResult.Error != nil {
			logrus.Errorf("获取TBS错误:%v", tbsResult.Error)
			return
		}

		//get all liked bars
		likeBars := GetAllBars()
		if likeBars.Error2 != nil {
			logrus.Errorf("获取关注的吧错误:%v", likeBars.Error2)
			return
		}

		logrus.Infof("总关注数量:%d", len(likeBars.Data.LikeForum))

		//签到
		TieBaSign(tbsResult, likeBars)
	} else {
		bdussArr := strings.Split(*bduss, ";")
		for item := range bdussArr {
			if bdussArr[item] == "" {
				continue
			}

			cookies = "BDUSS=" + bdussArr[item]

			//get tbs
			tbsResult := GetTbs()
			if tbsResult.Error != nil {
				logrus.Errorf("获取TBS错误:%v", tbsResult.Error)
				continue
			}

			//get all liked bars
			likeBars := GetAllBars()
			if likeBars.Error2 != nil {
				logrus.Errorf("获取关注的吧错误:%v", likeBars.Error2)
				continue
			}

			logrus.Infof("总关注数量:%d", len(likeBars.Data.LikeForum))

			//签到
			TieBaSign(tbsResult, likeBars)
		}
	}
}

func MD5Calc(arg string) string {
	ret := md5.New()
	ret.Write([]byte(arg))
	return hex.EncodeToString(ret.Sum(nil))
}

func GetTbs() TBSResult {
	client := &http.Client{Timeout: 5 * time.Second}

	var tbsResult TBSResult
	req, err := http.NewRequest("GET", tbsUrl, nil)
	if err != nil {
		logrus.Errorf("创建tbs请求错误:%v", err)
		tbsResult.Error = err
		return tbsResult
	}

	req.Header.Add("Cookie", cookies)

	resp, err := client.Do(req)
	if err != nil {
		logrus.Errorf("请求tbs错误:%v", err)
		tbsResult.Error = err
		return tbsResult
	}
	defer resp.Body.Close()

	bts, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logrus.Errorf("解析tbs请求结果错误:%v", err)
		tbsResult.Error = err
		return tbsResult
	}

	err = json.Unmarshal(bts, &tbsResult)
	if err != nil {
		logrus.Errorf("json结构化tbs请求结果错误:%v", err)
		tbsResult.Error = err
		return tbsResult
	}
	return tbsResult
}

func GetAllBars() LIKEDBars {
	var likeBars LIKEDBars
	client := &http.Client{Timeout: 5 * time.Second}
	req, err := http.NewRequest("GET", likedTiebaUrl, nil)
	if err != nil {
		logrus.Errorf("创建关注的吧请求错误:%v", err)
		likeBars.Error2 = err
		return likeBars
	}

	req.Header.Add("Cookie", cookies)

	resp, err := client.Do(req)
	if err != nil {
		logrus.Errorf("请求关注的吧错误:%v", err)
		likeBars.Error2 = err
		return likeBars
	}
	defer resp.Body.Close()

	bts, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logrus.Errorf("解析关注的吧请求结果错误:%v", err)
		likeBars.Error2 = err
		return likeBars
	}

	//fmt.Println("liked bars:", string(bts))
	err = json.Unmarshal(bts, &likeBars)
	if err != nil {
		logrus.Errorf("json结构化关注的吧请求结果错误:%v", err)
		likeBars.Error2 = err
		return likeBars
	}
	return likeBars
}

func TieBaSign(tbsResult TBSResult, likeBars LIKEDBars) {
	var i = 0
	var signedCnt = 0
	var signSuccessCnt = 0
	var otherSignCnt = 0
	client := &http.Client{Timeout: 5 * time.Second}
	for i < len(likeBars.Data.LikeForum) {
		forumName := likeBars.Data.LikeForum[i].ForumName
		s := strings.Replace(forumName, "+", "%2B", -1)
		if likeBars.Data.LikeForum[i].IsSign == 1 {
			fmt.Println("贴吧:" + s + "已经签过了")
			i = i + 1
			signedCnt += 1
			continue
		}
		fmt.Println("准备签到:", forumName)
		rotation := strings.Replace(s, "%2B", "+", -1)
		body := "kw=" + s + "&tbs=" + tbsResult.Tbs + "&sign=" + MD5Calc("kw="+rotation+"tbs="+tbsResult.Tbs+"tiebaclient!!!")

		b := bytes.NewBuffer([]byte(body))
		req, err := http.NewRequest("POST", signUrl, b)
		req.Header.Add("Cookie", cookies)

		resp, err := client.Do(req)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer resp.Body.Close()

		bts, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Println(err)
			return
		}

		//fmt.Println("sign Result:", string(bts))
		var signResult SignResult
		err = json.Unmarshal(bts, &signResult)
		if err != nil {
			fmt.Println("签到结果解析失败:", err)
			break
		}
		logrus.Infof("贴吧:%s 签到结果:%s 签到错误码:%s", forumName, signResult.ErrorMsg, signResult.ErrorCode)
		time.Sleep(5 * time.Second)
		if signResult.ErrorCode == "160002" {
			//亲,你之前已经签过了
		}
		if signResult.ErrorCode == "0" {
			fmt.Println("签到:" + s + " 成功")
			signSuccessCnt += 1
		} else {
			otherSignCnt += 1
			logrus.Warnf("有问题的贴吧:%s", forumName)
		}
		if signResult.ErrorCode == "340006" {
			//贴吧目录出问题啦,请到贴吧签到吧反馈
		}
		if signResult.ErrorCode == "110001" {
			//未对贴吧名字中的+号进行转义
		}
		i += 1
	}
	logrus.Infof("总关注数量:%d  已经签到个数:%d 成功签到个数:%d 未签到成功数量:%d", len(likeBars.Data.LikeForum), signedCnt, signSuccessCnt, otherSignCnt)
}

你可能感兴趣的:(go,golang,json,开发语言)