LoginSignup
0
0

More than 1 year has passed since last update.

Discordに送信されたPDFファイルを画像ファイルに変換して送信

Last updated at Posted at 2022-06-01

身内用に作ったもののメモ書き

環境

CodeSpaces

  • Python3.8

使用ライブラリ

  • discord.py 1.7.3
  • pdf2image 1.16.0
  • pillow 9.1.1

インストール

$ pip install -U pdf2image

$ sudo apt install poppler-utils poppler-data

処理の流れ

  • 添付ファイルの形式を確認
  • PDFだったらダウンロードして変換
  • ページごとに画像を書き出して送信&削除
  • ダウンロードしたPDFファイルを削除

ファイル名がかぶるのを避けるため、下記のコードではmessage.idをファイル名に使用

コード

async def on_message(message):
    if message.author.bot:
        return
    for attachment in message.attachments:
        if attachment.content_type != "application/pdf":
            continue
        await attachment.save(f"{message.id}.pdf")
        images = pdf2image.convert_from_path(f"{message.id}.pdf")
        for index, image in enumerate(images):
            image.save(f"{message.id}-{str(index+1)}.jpg")
            await message.channel.send(file=discord.File(f"{message.id}-{str(index+1)}.jpg"))
            os.remove(f"{message.id}-{str(index+1)}.jpg")
        os.remove(f"{message.id}.pdf")

10枚ずつ出力すれば高速化できそうな気もするが、時間がなかったので割愛

参考文献

pdf2image リポジトリ

0
0
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
0