首页 > 解决方案 > AttributeError:“WindowsPath”对象没有 Discord.py 的“编码”属性

问题描述

我正在用 python 编写一个不和谐的机器人。这个机器人需要枕头和路径库。我有一个在图像上绘制的函数,但我总是遇到一个我无法解决的错误。根据我的调试器,该错误发生在这一行:

font = ImageFont.truetype(font_path, 15)

我总是收到这个错误:

AttributeError: 'WindowsPath' object has no attribute 'encode' with Discord.py

这是完整的代码:

class MaccaudCog(commands.cogs, name="Command !maccaud"):
    def __init__(self, bot):
        self.bot = bot

    async def maccaud(self, ctx, *, sentence=None):

        maccaud_sentence=['some sentences,some sentences']

        def draw(sentence):
            # Decode sentence sended if non latin-1 characters are present
            sentence = sentence.encode('latin-1', 'replace').decode('latin-1')

            # Set relative paths
            mod_path = Path(__file__).parent

            relative_path_1 = '../assets/maccaud/base_maccaud.jpg'
            maccaud_base = (mod_path / relative_path_1).resolve()

            relative_path_2 = '../assets/fonts/impact.ttf'
            font_path = (mod_path / relative_path_2).resolve()

            relative_path_3 = '../assets/maccaud/edited_maccaud.jpg'
            maccaud_edited = (mod_path / relative_path_3).resolve()

            # Draw on img
            img = Image.open(maccaud_base)
            draw = ImageDraw.Draw(img)
            font = ImageFont.truetype(font_path, 15)
            W,H = img.size
            w, h = draw.multiline_textsize(sentence)
            width = (W-w)/2
            height = (H-h)/1.25
            draw.multiline_text((width,height), sentence, (255,255,255), font=font, align="center")
                
            # Save and return file
            img.save(maccaud_edited)
            file = discord.File(maccaud_edited, filename="edited_maccaud.jpg")
            return file

        file = draw(sentence)
        embed = discord.Embed(title="", description="", colour=discord.Color.green())
        embed.set_image(url="attachment://edited_maccaud.jpg")
        await self.client.send(file=file, embed=embed)

def setup(bot):
    bot.add_cog(MaccaudCog(bot))

这是回溯:

Traceback (most recent call last):
  File "D:\pythonProjects\cog_bot\new\cogs\maccaud.py", line 96, in draw
    font = ImageFont.truetype(font_path, 15)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 655, in truetype
    return freetype(font)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 652, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\site-packages\PIL\ImageFont.py", line 184, in __init__
    font_bytes_path = font if isinstance(font, bytes) else font.encode()
AttributeError: 'WindowsPath' object has no attribute 'encode'

你有解决方案吗?

标签: pythonpython-3.xdiscord.py

解决方案


尝试这个:

font = ImageFont.truetype(str(font_path), 15)

这将确保您font_path是一个字符串


推荐阅读