0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordからQiitaへ:GPT-4o×CLIで自動記事生成・投稿システム構築

Posted at
# 自動Qiita記事生成・投稿CLIツールの紹介

この記事では、WordファイルからMarkdown形式の技術記事を自動生成し、Qiitaへ投稿するCUIベースのCLIツールについて紹介します。このツールの開発経緯や機能概要を、初心者にもわかりやすく説明します。

## 背景と目的

従来、Qiitaに記事を投稿するには、構成の検討、Markdown記述、手動投稿という複数の工程が必要でした。本プロジェクトは、これらのプロセスを自動化し、効率的なナレッジ共有と発信を支援することを目的としています。

## システム構成

本システムは、以下の主要コンポーネントにより構成されています:

- **Python 3.11+**
- **OpenAI(GPT-4o API)**
- **python-docx(Word読み込み)**
- **python-dotenv(APIキー管理)**
- **requests(Qiita API通信)**

## 処理フロー

以下の手順で処理を進めます:

1. Word(.docx)ファイルをCLIで指定
2. GPT-4oでQiita記事構成を自動生成(Markdown形式)
3. 生成結果をMarkdownファイルとして保存
4. CLIから投稿タイトル・公開設定を入力
5. Qiita APIを使って記事を非公開または公開で投稿

## 実装コード概要

### 1. Wordファイルの読み込み

```python
from docx import Document

def read_docx(path):
    doc = Document(path)
    return "\n".join([para.text for para in doc.paragraphs if para.text.strip()])

指定したWordファイル(.docx)を開き、空行を除いて本文を結合して返します。

2. GPT-4oによるMarkdown生成

from openai import OpenAI

client = OpenAI(api_key=openai_api_key)

def generate_qiita_structure(docx_text, style_hint="Beginner-friendly technical article"):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are an assistant that structures and edits articles for Qiita."},
            {"role": "user", "content": f"Generate a Qiita-style Markdown article:\n{docx_text}"}
        ],
        temperature=0.7,
    )
    return response.choices[0].message.content

Wordから取得した本文をもとに、GPT-4oにより技術記事の構成をMarkdown形式で自動生成します。

3. Qiitaへの投稿処理

import requests

def post_to_qiita(title, body, token, tags=["Python", "GPT-4", "Qiita"], private=True):
    headers = {"Authorization": f"Bearer {token}"}
    data = {
        "title": title,
        "body": body,
        "private": private,
        "tags": [{"name": tag} for tag in tags]
    }
    response = requests.post("https://qiita.com/api/v2/items", json=data, headers=headers)
    return response.status_code, response.json()

タイトル・本文・タグを指定して、Qiita APIを使い自動的に記事を投稿します。

実行例

CLI実行時の標準的な出力例です:

Enter the .docx filename: example.docx
[INFO] Markdown saved to: example_qiita.md
Enter Qiita post title: test02
Make it private? (y/n): y
[✅] Successfully posted to Qiita!
URL: https://qiita.com/ramalong/private/xxxxxxxxxxxxxxxxxx

おわりに

本CLIツールにより、文章作成からQiita投稿までの流れが一貫して自動化されました。今後は、タグ自動提案、記事の一括投稿、既存記事の更新、記事ID管理などの機能拡張も検討しています。

このツールを活用して、より効率的な情報共有を実現しましょう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?