Open source weapon sharing: BitBar sit and see how many star s your project has increased today

At the beginning of today, I want to say a few words about my recent feelings. In this era of information explosion and Internet. I am always surrounded by all kinds of anxious information,
I don't know if there are any friends like me. Seeing all kinds of great Xia who have great powers and play with life, I looked down at my current situation and life and sighed silently.

For a long time, I was in the anxiety of being bombarded by information. I felt that I had no praiseworthy achievements and could not catch up with them no matter how hard I tried. It's just like that there are too many things to do, so I can't start, so I just let him go,
But doing nothing leads to more and more things to be done, which will lead to more anxiety. This state lasted for two months. By chance, I found a way to relieve this pressure - reading.

Your problem is mainly that you don't read much but think too much—— Yang Jiang

Some technical books could not be chewed any more, so I went to see the collection of birds, which seemed to be calmer. It reduces the access to all kinds of information, and looks at the world in the eyes of the wise from the book.

When we rejoice in our fullness, then we can part with our fruits with joy.

When we find happiness in the pursuit of fulfillment, we can happily break up with the goal of results—— Collection of birds

Focus on doing what you are doing now and at hand, invest precious time, and let time make ordinary things extraordinary. I think happiness always comes slowly, but it will never be absent.

Author: HelloGitHub- marinated egg

1, Introduction

Well, the above is my mental journey and some clumsy experience. Let's start with our main topic:

Project address:

https://github.com/matryer/bitbar

Today, we recommend an open source Mac OSX Menu Bar tool on GitHub: BitBar, which can load various types of script output information. For example, monitor the number of stars on GitHub on the Menu Bar. The information displayed depends entirely on the script you write.
Let me tell you how fragrant it is. Let's first look at a rendering:

2, Get started

  1. Download address: https://github.com/matryer/bitbar/releases/tag/v1.9.2

  2. decompression

  3. Download plugins: https://getbitbar.com/plugins/BitBar

  4. The above plug-in shows the BitBar version, and the effect shows:

In this way, the whole program will run. If you are not a programmer, you can directly select the plug-in on the official website of step 3. Next, I will write a Python script to get the number of stars in GitHub, which can facilitate the dynamic attention to the star information and growth of my HelloGitHub project.

3, Script

Because I am good at python, I use Python scripts for development. Of course, BitBar supports many languages, such as Ruby, JS, Go, Swift, etc.

Without considering how to display to the Menu Bar, first solve how to obtain the project star on GitHub. In order to make the whole process simple without considering the environment, the following script will use Python's standard library.

3.1 applying for GitHub token

You must have a token to obtain data through the GitHub interface, so you need to apply for a token on your GitHub first( https://github.com/settings/tokens/new )Do not check any additional permissions, and then click Generate token at the bottom.

Then copy the generated token and save it for later use!

3.2 GitHub API

The GitHub API is used to obtain data. The document address is: https://developer.github.com/v3/ .

For example, the HelloGitHub project:

First verify the interface of the token:curl -H "Authorization: token the token you applied" request through the command line

curl -H "Authorization: token xxxx" https://api.github.com/repos/521xueweihan/HelloGitHub
{
  "id": 580xxx,
  "node_id": "MDEwOlJlcG9xxxxxODAzOA==",
  "name": "HelloGitHub",
  "full_name": "521xueweihan/HelloGitHub",
  "private": false,
  ...
  "temp_clone_token": "",
  "allow_squash_merge": true,
  "allow_merge_commit": true,
  "allow_rebase_merge": true,
  "delete_branch_on_merge": false,
  "network_count": 4752,
  "subscribers_count": 2085
}

3.3 start coding

The above interface and token are ready, and the following is the script.

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
#   Author  :   XueWeiHan
#   E-mail  :   595666367@qq.com
#   Date    :   2020-07-10 15:18
#   Desc    :   BitBar GitHub Python plugin
import json
import datetime
from urllib import request

REPO_NAME = "HelloGitHub" # Project name
USER_NAME = "521xueweihan" # user name
TOKEN = "xxx" # TOKEN

def fetch_data(url):
    """
    Request and resolution GitHub API function
    """
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Authorization': 'token ' + TOKEN,
    }
    req = request.Request(url, headers=headers)  # GET method
    response = request.urlopen(req).read()
    data = response.decode('utf-8')
    # Parse data
    info_dict = json.loads(data)
    return info_dict

def get_star_count():
    """
    obtain star Total
    """
    url = "https://api.github.com/repos/{}/{}".format(USER_NAME, REPO_NAME)
    repo_info_dict = fetch_data(url)
    star_count = repo_info_dict["stargazers_count"]
    return star_count

def get_today_star():
    """
    Get today star Number of increases
    """
    today_star_count = 0
    page = 1
    # Is this the identifier of today's event
    is_today_event = True
    # Today's event is used to judge events
    today = datetime.datetime.now().date()
    url = "https://api.github.com/users/{}/received_events".format(USER_NAME)
    url += "?page={}&per_page=200"
    while is_today_event:
        event_info_list = fetch_data(url.format(page))
        for event_info in event_info_list:
            create_at_str = event_info["created_at"]
            create_at_obj = datetime.datetime.strptime(
                create_at_str, '%Y-%m-%dT%H:%M:%SZ')
            # Date converted to Beijing time
            create_at_date_obj = (create_at_obj + datetime.timedelta(hours=8)).date()
            # Determine whether it is today's event
            if create_at_date_obj < today:
                # End acquisition
                is_today_event = False
                break
            # Filter star events for the specified item
            if event_info["type"] == "WatchEvent" \
               and event_info.get("payload", {}).get("action") == "started" \
               and event_info.get("repo", {}).get("name") == USER_NAME + "/" + REPO_NAME:
                today_star_count += 1
        page += 1
    return today_star_count

if __name__ == '__main__':
    try:
        star_count = get_star_count()
        today_star_count = get_today_star()
        print("{} Growth today: {}✨Total:{}k🌟".format(
            REPO_NAME, today_star_count, int(star_count/1000)))
    except Exception as e:
        print("ERROR:{}".format(e))

The script is very simple. It is a method to request and parse the GitHub API, and then get the total number of stars of the project and the growth of today's stars. The entire script can be used directly. Just write your own information and token on the top constant parameters. The running results are as follows:

HelloGitHub Growth today: 62✨Total:32k🌟

3.4 running through BitBar

  1. First create a directory, and then put the written script into it. The naming rule of the script is: name Running interval File suffix, such as github 30m Py is executed every half an hour.

  2. Then add the execution permission to the script. The command is: chmod +x file name. (important)

  3. Finally, click the Choose Plugin Folder of BitBar and select the directory where the script is located.

  4. Refresh all refresh manually. The final effect is as follows:

4, End

Due to the lack of time, I only wrote a simple example showing the star of the GitHub project. Interested partners can write and customize data scripts for information they care about.
OK, are you satisfied with today's project? Also want to see those projects welcome to leave a message and tell me ~

The HelloGitHub exchange group is now fully open, and wechat is added: HelloGitHub is a group of friends, who can chat and exchange technology with the front-end, Java, Go and other leaders from all walks of life~

Posted by crazy_carl on Tue, 31 May 2022 13:31:32 +0530