Skip to content

Instantly share code, notes, and snippets.

@fukaz55
Created January 15, 2026 04:49
Show Gist options
  • Select an option

  • Save fukaz55/a06188d8673243e16c5891dc7d3c74a7 to your computer and use it in GitHub Desktop.

Select an option

Save fukaz55/a06188d8673243e16c5891dc7d3c74a7 to your computer and use it in GitHub Desktop.
Mastodonのエクスポートデータから作成した sqlite3 の DB を読み込み、hugo で使用可能な Markdown 形式のファイルを作成する
import sqlite3
import os
# Mastodonのエクスポートデータから作成したsqliteのDBを読み込み、hugoで使用可能なMarkdown形式のファイルを作成する
DB_FILE = 'mastodon_posts.db'
BASE_DIR = '/path/to/hugo/'
BLOG_PATH = 'blog' # hugoの公開URLがサブディレクトリだった場合、ここにパスを記述
MD_DIR = BASE_DIR + BLOG_PATH + '/content/posts' # 作成したmdファイルを保存する content ディレクトリ
def main():
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
# 日付を列挙
dated = []
sql = "select distinct dated from posts"
cursor.execute(sql)
res = cursor.fetchall()
for rec in res:
dated.append(rec['dated'])
# 日付毎に読み込み、エントリを作成する
for date in dated:
text = "---\n\n"
taglist = []
sql = "select id, published, content, attachment, tag from posts where dated = ? order by published"
cursor.execute(sql, [date, ])
res = cursor.fetchall()
for rec in res:
# 本文
text += rec['content'] + " \n"
# 添付画像
if rec['attachment'] != '':
attachs = rec['attachment'].split()
for attach in attachs:
url = '/' + BLOG_PATH + attach
text += f"![]({url})\n"
# 日付と投稿場所
server = 'mastodon-japan.net'
text += f"_{rec['published']}, {server}_\n\n"
text += "---\n\n"
post_date = rec['published'][0:10] + 'T' + rec['published'][12:] + '+09:00'
# ハッシュタグ
if rec['tag'] != '':
tags = rec['tag'].split()
for tag in tags:
if tag not in taglist:
tag = f'"{tag}"'
taglist.append(tag)
# hugoのヘッダ
tagtext = ','.join(taglist)
title = date.replace('-', '/')
header = f'''
---
title: "{title}"
date: {post_date}
tags: [{tagtext}]
params:
showdate: false
---
'''
# 出力
fn = MD_DIR + '/' + date + '.md'
print(f'{fn}...')
with open(fn, "w") as o:
print(header, file=o)
print(text, file=o)
except Exception as e:
print(f"エラーが発生しました: {e}")
finally:
conn.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment