leetcode 每日一题机器人推送

leetcode-question-today

github repo: 有用请点 star

leetcode 每日一题推送(目前支持 slack/wecom),写个机器人为了提醒自己写题。

主要原理

    获取每日一题链接
package api

import (
	"context"

	"github.com/machinebox/graphql"
)

func GetTodayQuestion(ctx context.Context) (*QuestionTodayResp, error) {
          
   
	// create a client (safe to share across requests)
	client := graphql.NewClient("https://leetcode.cn/graphql/")

	// make a request
	req := graphql.NewRequest(QuestionQuery)

	// set header fields
	req.Header.Set("Cache-Control", "no-cache")
	req.Header.Set("content-type", "application/json")
	req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36")
	req.Header.Set("referer", "https://leetcode.cn/problemset/all/")
	req.Header.Set("origin", "https://leetcode.cn")

	// run it and capture the response
	var resp QuestionTodayResp
	if err := client.Run(ctx, req, &resp); err != nil {
          
   
		return nil, err
	}

	return &resp, nil
}
    整合数据进行相关推送
// 获取每日一题,如果有则推送即可
	resp, err := api.GetTodayQuestion(context.TODO())
	if err != nil {
          
   
		log.Printf("获取每日一题发生错误: %v
", err)
		return
	}

	if len(resp.TodayRecord) <= 0 {
          
   
		log.Printf("todayRecord 长度为 0,请检查
")
		return
	}

	today := resp.TodayRecord[0]

	msgTemplate := `每日一题(%s)
Title: %s
Tags: %s
Link: %s
LinkCN: %s`
	date := today.Date
	title := fmt.Sprintf("%s(%s)", today.Question.TitleCn, today.Question.Title)
	tags := make([]string, 0)
	for _, tag := range today.Question.TopicTags {
          
   
		tags = append(tags, fmt.Sprintf("%s(%s)", tag.NameTranslated, tag.Name))
	}
	tagsValue := strings.Join(tags, "、")
	link := fmt.Sprintf("%s/problems/%s", api.Leetcode, today.Question.TitleSlug)
	linkCn := fmt.Sprintf("%s/problems/%s", api.LeetcodeCn, today.Question.TitleSlug)

	content := fmt.Sprintf(msgTemplate, date, title, tagsValue, link, linkCn)

usage

    fork 此仓库 Secrets Actions 中添加 SLACK_URL 为对应的 token 即可
    可自行拓展其他的通知方式

acknowledgement

    graphql leetcode
经验分享 程序员 微信小程序 职场和发展