1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【完成形】Pythonでワードプレスに記事を読み書き投稿するプログラム

1
Posted at

このコードでできること

  • ディレクトリを選択
  • 複数のWPアカウントから選択
  • ファイルを新規作成
  • ファイルを読み出し
  • 読み出し時に保存内容を確認
  • 編集時のスニペット登録・呼び出し
  • 投稿時に[下書き]or[公開]
  • 投稿時にカテゴリ追加
import os #フォルダの中身を探る
import sys #プログラム強制終了用
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
 
# スニペット中のendを入力するまで繰り返し書かせる子プログラムの定義
def write_roop():
    i=1
    while True:
        text=input('%s:' % i)
        if text=='end':
            break
        else:
            f.write('%s\n' % text)
            i+=1
            continue
 
# ディレクトリ選択
place=["Desktop","User"]
print("-----------------------")
for i in range(int(len(place))):
    print("%s:%s" % (i,place[i]))
print("-----------------------")
while True:
    select=input("どのディレクトリで作業しますか?:")
    if select=="0":
        directory="/Users/ユーザー名/Desktop"
        break
    elif select=="1":
        directory="/Users/ユーザー名"
        break
    else:
         continue
 
# どのアカウントを使用するか
account=["アカウント1","アカウント2"]
print("-----------------------")
for i in range(int(len(account))):
    print("%s:%s" % (i,account[i]))
print("-----------------------")
while True:
    page=input("どのアカウントで投稿しますか?:")
    if page=="0":
        url="アカウント1のURL"
        username="アカウント1のユーザー名"
        password="アカウント1ののパスワード"
        break
    elif page=="1":
        url="アカウント2のURL"
        username="アカウント2のユーザー名"
        password="アカウント2ののパスワード"
        break
    else:
         continue
 
while True: #最後の編集を続ける選択をした場合のループ
    #書き始めを決定します
    while True:
        new=input('\n新規作成?(y/n):')
        #新規作成を選んだ場合、タイトルを新たに決めて、ファイルを作成します
        if new == "y":
            while True:
                title=input('タイトルを入力:')
                if title=="":
                    print("タイトルが入力されていません。")
                else:
                    break
            break
        #既存のファイルを開く場合、指定ディレクトリのフォルダからファイル一覧を出し、選択させます
        elif new== "n":
            files = os.listdir(directory)
            while True:
                for i in range(len(files)) : #フォルダ内のファイルリストを表示
                    print("%s:%s" % (i,files[i]))
                #番号を入力させて、エラーが出なければbreakで次へ
                try:
                    title=str(files[int(input("番号入力:"))]).replace(".txt","")
                    f=open("%s/%s.txt" % (directory,title),"r",encoding="utf-8")
                    print('''
-----------------------
ファイルの内容
-----------------------
                    ''')
                    print(f.read())
                    print('''
-----------------------
-----------------------
                    ''')
                    f.close()
                    break
                #エラーが出れば(番号が違う、番号じゃないなど)ループさせる
                except:
                    print("番号を入力してください")
            break
        #endと入力した場合、強制終了
        elif new=="end":
            sys.exit()
        #yでもnでもendでもない入力の場合、ループさせる。
        else:
            continue
    f=open("%s/%s.txt" % (directory,title),"a",encoding="utf-8")
 
    #本文を繰り返し入力させる
    while True:
        content=input("文章を入力(or end):")
        #endと打てば本文入力終了
        if content=="end":
            break
 
        #見出し1
        elif content=='#':
            f.write('<h1>%s</h1>\n' % input("<h1>"))
            print('</h1>')#視覚的な補助
 
        #見出し2
        elif content=='##':
            f.write('<h2>%s</h2>\n' % input("<h2>"))
            print('</h2>')#視覚的な補助
 
        #見出し3
        elif content=='###':
            f.write('<h3>%s</h3>\n' % input("<h3>"))
            print('</h3>')#視覚的な補助
 
        #list
        #見出し3
        elif content=='li':
            f.write('<li>%s</li>\n' % input("<li>"))
            print('</>')#視覚的な補助
 
        #pre
        elif content=='pre':
            f.write('<pre>')
            print('<pre>')#視覚的な補助
            write_roop()
            f.write('</pre>\n')
            print('</pre>')#視覚的な補助
 
        #その他普通の文字列はそのまま書き込み
        else:
            f.write("%s\n" % content)
    #最後にファイルを閉じる
    f.close()
    print("保存しました。")
 
    #ワードプレスに投稿するかどうか
    doupost=input('ワードプレスに投稿しますか?(y)')
    if doupost=='y':
        f=open("%s/%s.txt" % (directory,title),"r",encoding="utf-8")
        #カテゴリー設定
        category=[]
        while True:
            cat=str(input("カテゴリーを入力:"))
            if cat=="end":
                break
            category.append(cat)
        while True:
            dp=input('下書き(draft)か公開(publish)を選択してください。(d/p)')
            if dp=='p':
                p_status='publish'
                break
            elif dp=='d':
                p_status='draft'
                break
            else:
                continue
        print('投稿しています...Wait for a second...')
 
        wp = Client('%s/xmlrpc.php' % url, username, password)
        post = WordPressPost()
        post.title = title
        post.content = f.read()
        post.terms_names = {'post_tag': [],'category': category}
        post.status=p_status
        wp.call(NewPost(post))
 
        f.close()
        print('投稿が完了しました。')
    else:
        print('投稿をやめました。')
 
    #最後に、編集を続けるかどうかの条件。yで、最初に戻り、新規作成と既存のファイルの編集が出来る。
    while True:
        conti=input("編集を続けますか?(y/n)")
        if conti=="y":
            break
        elif conti=="n":
            print("作業を終了します。")
            sys.exit()
        else:
            print("入力してください")
            continue
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?