[PYTHON] I made a POST script to create an issue on Github and register it in the Project

Create an issue in any repository on Github and register it in the column of any project

Work below

First, get your Github token

Get the necessary information with curl It seems that api has to add a strange header like a trial period First, you need the id of the project and the id of the columns created by the project, so save it to get it.

curl -H "Accept: application/vnd.github.inertia-preview+json" -u "username:token" https://api.github.com/repos/Team name/Repository name/projects
curl -H "Accept: application/vnd.github.inertia-preview+json" -u "username:token" https://api.github.com/repos/Team name/Repository name/projects/(The id of the project obtained above)/columns

Make a note of the id obtained here as it will be used in the following script. Also, it is easier to get a token of Authorization: Basic with wireshark or something. (I should encode username: token to base64, but I got bad because I got a communication.)

All you have to do is assign the required values to the script below.

Python version

# -*- coding: utf-8 -*-
import requests
import json
import sys

response = {}
ownr = ''
repo = ''
column_id = ''
issue_url = "https://api.github.com/repos/" + ownr + "/" + repo + "/issues"
project_url = "https://api.github.com/repos/" + ownr + "/" + repo + "/projects/columns/" + column_id + "/cards"
headers = {
    "Authorization": "Basic base64 version username:token",
    "Accept": "application/vnd.github.inertia-preview+json",
    "Content-Type": "application/json",
}
argvs = sys.argv
"""---------------Create Issue---------------------"""
params = {"title": argvs[1]}
res = requests.post(issue_url, data=json.dumps(params), headers=headers)
"""---------Register created issue to Project------"""
params = {"content_id": int(res.json()['id']), "content_type": "Issue"}
res = requests.post(project_url, data=json.dumps(params), headers=headers)
print(res.status_code)

Go version

I didn't want to put token in plain text in the script, so I recreated it with Go so that it can be binarized and operated. (I'm not saying it's safe) Error handling is texto, so please do it well


package main

import (
        "bytes"
        "encoding/json"
        "flag"
        "fmt"
        "io/ioutil"
        "net/http"
        "strconv"
        "time"
)

func HttpPost(url, param string) (interface{}, error) {
        req, err := http.NewRequest(
                "POST",
                url,
                bytes.NewBuffer([]byte(param)),
        )
        if err != nil {
                return nil, err
        }
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("Authorization", "Basic base64 version username:token")
        req.Header.Set("Accept", "application/vnd.github.inertia-preview+json")

        client := &http.Client{Timeout: time.Duration(10 * time.Second)}
        resp, err := client.Do(req)
        defer resp.Body.Close()
        if err != nil {
                return nil, err
        }
        var response interface{}
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
                return nil, err
        }
        err = json.Unmarshal(body, &response)
        return response, err
}

func main() {
        flag.Parse()
        if len(flag.Args()) < 1 {
                fmt.Println("no issue title")
                return
        }
        issue_title := flag.Args()[0]
        ownr := ""
        repo := ""
        column_id := ""
        issue_url := "https://api.github.com/repos/" + ownr + "/" + repo + "/issues"
        project_url := "https://api.github.com/repos/" + ownr + "/" + repo + "/projects/columns/" + column_id + "/cards"

        params := `{"title": "` + issue_title + `"}`
        res, err := HttpPost(issue_url, params)
        if err != nil {
                fmt.Println(err)
        }
        id := res.(map[string]interface{})["id"].(float64)
        params = `{"content_id": ` + strconv.Itoa(int(id)) + `, "content_type": "Issue"}`
        res, err = HttpPost(project_url, params)
        if err != nil {
                fmt.Println(err)
        }
        fmt.Println(200)
}

How to use

./ (script or binary) issue_title An issue with issue_title should have been created and registered in any project.

Recommended Posts

I made a POST script to create an issue on Github and register it in the Project
I want to create a pipfile and reflect it in docker
I want to create a histogram and overlay the normal distribution curve on it. matplotlib edition
I made an appdo command to execute a command in the context of the app
I made an image classification model and tried to move it on mobile
I made a script to put a snippet in README.md
[Python] I made a script that automatically cuts and pastes files on a local PC to an external SSD.
I tried to create a Python script to get the value of a cell in Microsoft Excel
An easy way to view the time taken in Python and a smarter way to improve it
I don't like to be frustrated with the release of Pokemon Go, so I made a script to detect the release and tweet it
I converted the time to an integer, factored it into prime factors, and made a bot to tweet the result (xkcd material)
Disguise the grass on GitHub and try to become an engineer.
I tried to register a station on the IoT platform "Rimotte"
I made a command to display a colorful calendar in the terminal
Hannari Python At the LT meeting in December, I made a presentation on "Python and Bayesian statistics".
I made a script to display emoji
I made a kitchen timer to be displayed on the status bar!
[Python] Create a linebot to write a name and age on an image
I made a script in python to convert .md files to Scrapbox format
I made a program to check the size of a file in Python
I tried to make a system to automatically acquire the program guide → register it in the calendar in one day
I want to pass an argument to a python function and execute it from PHP on a web server
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Script to use multiple github accounts properly in the same repository on the same machine
I want to create a window in Python
I made a tool to notify Slack of Connpass events and made it Terraform
I want to write an element to a file with numpy and check it.
How to save the feature point information of an image in a file and use it for matching
Create a Django project and application in a Python virtual environment and start the server
Define a division value in Django and easily reflect it on the screen
I want to convert horizontal text to vertical text and post it on Twitter etc.
I made a program to look up words on the window (previous development)
I made a script to record the active window using win32gui of Python
Create a filter to get an Access Token in the Graph API (Flask)
I made a package to create an executable file from Hy source code
I made a tool in Python that right-clicks an Excel file and divides it into files for each sheet.
When I tried to create a project using Python on Docker with PyCharm, it didn't work, but it worked with Docker Compose.
I made a plug-in from the Japan Meteorological Agency GPV to easily create an animated contour diagram with QGIS.
A Python script that crawls RSS in Azure Status and posts it to Hipchat
It was a life I wanted to OCR on AWS Lambda to locate the characters.
I want to replace the variables in the python template file and mass-produce it in another file.
sphinx-quickstart got messy and I tried to create an alternative command and the stress disappeared
I made a command to markdown the table clipboard
Create a shape on the trajectory of an object
It is difficult to install a green screen, so I cut out only the face and superimposed it on the background image
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
"Stop committing Japanese files to git on Mac> <" For the time being, I wrote a script to search for incompatible Japanese files on Mac and Linux.
I made a script in Python to convert a text file for JSON (for vscode user snippet)
When I tried to install PIL and matplotlib in a virtualenv environment, I was addicted to it.
I made a class to get the analysis result by MeCab in ndarray with python
A script that makes it easy to create rich menus with the LINE Messaging API
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
Create a script for your Pepper skill in a spreadsheet and load SayText directly from the script
Recursively get the Excel list in a specific folder with python and write it to Excel.
Steps to create a Job that pulls a Docker image and tests it with Github Actions
I made a program to collect images in tweets that I liked on twitter with Python
I made a server with Python socket and ssl and tried to access it from a browser
I want to copy an English paper from pdf and put it in Google Translate
I made a function to crop the image of python openCV, so please use it.
I also tried to imitate the function monad and State monad with a generator in Python
I made a tool to automatically generate a simple ER diagram from the CREATE TABLE statement