Python을 사용하여 Disqus 주석을 Utterances(GitHub 문제에서)로 마이그레이션

교체했을 때Jekyll
그리고 나의 Jekyll-ReadTheDocs theme
MkDocs
blog-customised version
Material for MkDocs theme,
내 게시물의 URL이 변경되었습니다.

나는 코멘트를 위해 Disqus을 사용하고 있었고,
스레드를 이전 URL에서 새 URL로 마이그레이션하는 방법을 제공합니다.
불행히도, 이번에는 어떤 이유로 작동하지 않았습니다.
(이미 예전에 한 번 해본 적이 있는데 잘 작동했습니다.)

사생활과 관련된 Disqus에 대한 비판을 점점 더 많이 읽었고,
그래서 대체품을 찾아봤습니다.
Disqus 스레드 마이그레이션이 작동하지 않아 완벽한 기회였습니다!

나는 몇 개의 웹 페이지를 읽었고 Isso 에 관심을 갖게 되었습니다.
유감스럽게도 다시 나는 did not manage
내 라즈베리 파이에 설치합니다.

그래서 훨씬 더 간단한 솔루션을 사용했습니다: Utterances .
기본적으로 저장소에서 GitHub 앱을 활성화합니다.
게시물 페이지에 스크립트를 추가하고 짜잔: 새 댓글 섹션
GitHub 문제로 구동됩니다.

독자가 로그인해야 하므로 완전히 만족하지 않습니다.
GitHub 계정으로 댓글을 달 수 있습니다(익명 댓글 없음).
그리고 중첩된 토론을 가질 수 없습니다(GitHub 문제와 마찬가지로).

하지만 설정은 정말 쉬웠어요 😄!

이제 Disqus 주석을 GitHub 문제로 마이그레이션하기만 하면 됩니다.
이를 반자동으로 수행하기 위해 다음 스크립트를 작성했습니다.
아직 "테스트"코멘트를 작성해야 했기 때문에 "반자동"
Utterances가 문제를 시작/생성할 수 있도록 각 게시물에서.
스크립트에서 직접 구현할 수 있다고 생각합니다.
그러나 나는 단지 수십 개의 게시물을 가지고 있었기 때문에 쉽고 반복적인 방법을 취했습니다.

스크립트



!!! 경고
스크립트를 실행하기 전에 초기 문제를 생성해야 합니다!
블로그를 로컬에서 제공하고 댓글이 있는 모든 게시물에 "테스트"댓글을 작성하세요.

먼저 export your Disqus comments .

그런 다음 두 개의 Python 라이브러리가 필요합니다.
  • pygithub
  • xmltodict

  • 또한 GitHub에서 토큰을 생성해야 합니다.public repos 액세스 권한만 있으면 됩니다.

    파일에 다음 환경 변수를 작성하십시오.
    그리고 그것을 소스.

    export FILEPATH="comments.xml"
    export USERNAME="yourUsername"
    export TOKEN="yourToken"
    export REPOSITORY="yourUsername/yourUsername.github.io"
    export BASE_URL="https://yourUsername.github.io/"
    

    이제 다음 스크립트를 복사/붙여넣기 및 실행할 수 있습니다.

    import xmltodict
    from github import Github
    
    FILEPATH = os.environ["FILEPATH"]
    USERNAME = os.environ["USERNAME"]
    TOKEN = os.environ["TOKEN"]
    REPOSITORY = os.environ["REPOSITORY"]
    BASE_URL = os.environ["BASE_URL"]
    
    
    def disqus_to_github():
        g = Github(TOKEN)
        repo = g.get_repo(REPOSITORY)
        issues = repo.get_issues()
    
        with open(FILEPATH) as fd:
            data = xmltodict.parse(fd.read())
    
        data = data["disqus"]
    
        threads = [dict(t) for t in data["thread"]]
        posts = sorted((dict(p) for p in data["post"]), key=lambda d: d["createdAt"])
    
        # only keep threads with comments
        twc_ids = set(p["thread"]["@dsq:id"] for p in posts)
        threads = {t["@dsq:id"]: t for t in threads if t["@dsq:id"] in twc_ids}
    
        # associate the thread to each post
        for post in posts:
            post["thread"] = threads[post["thread"]["@dsq:id"]]
    
        # associate the related GitHub issue to each thread
        # warning: the issues need to exist before you run this script!
        # write a "test" comment in each one of your post with comments
        # to make Utterances create the initial issues
        for thread in threads.values():
            for issue in issues:
                if issue.title == thread["link"].replace(BASE_URL, ""):
                    thread["issue"] = issue
                    break
    
        # iterate on posts and create issues comments accordingly
        for i, post in enumerate(posts, 1):
            name = post["author"]["name"]
            user = post["author"].get("username")
            mention = " @" + user if user and not user.startswith("disqus_") else ""
            date = post["createdAt"]
            message = post["message"]
            issue = post["thread"]["issue"]
            body = f"*Original date: {date}*\n\n{message}"
            # don't add original author when it's you
            if user != USERNAME:
                body = f"*Original author:* **{name}{mention}**  \n{body}" 
            print(f"Posting {i}/{len(posts)} to issue {issue.number}    \r", end="")
            issue.create_comment(body)
    
        print()
    
    
    if __name__ == "__main__":
        disqus_to_github()
    

    저는 이 글을 개인적인 용도로만 1회 작성했으며,
    그래서 당신이 그것을 시도할 때 쉽게 충돌할 수 있습니다!
    Python 기술을 사용하고 적용하십시오 😉

    좋은 웹페이지 즐겨찾기