You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py报错:'str'对象没有'url'属性 求解决方案

问题分析

错误'str' object has no attribute 'url'出现在profile_image = await load_image_async(str(member.avatar.url))这一行,核心原因是当用户未设置自定义头像时,member.avatar会返回None,此时尝试访问None的url属性会引发错误;少数情况下可能是代码逻辑意外将member.avatar转换为字符串,导致无法访问url属性。

解决方案

1. 改用display_avatar获取用户头像

member.display_avatar会自动返回用户当前显示的头像(包括系统默认头像),避免member.avatar为None的情况,是更可靠的获取方式。

2. 增加系统频道存在性检查

member.guild.system_channel可能为None(服务器未设置系统频道),需要先判断再发送消息,避免报错。

3. 优化头像URL的获取方式

直接使用member.display_avatar.url即可,无需额外转换(load_image_async可以直接接受URL对象或字符串)。

修正后的代码
import discord
from discord.ext import commands
from easy_pil import Editor, load_image_async, Font

bot = commands.Bot(command_prefix='!', intents = discord.Intents.all())

@bot.event
async def on_ready():
    print('logged in problemless as {0.user}'.format(bot))

@bot.event
async def on_member_join(member):
    # 检查系统频道是否存在
    channel = member.guild.system_channel
    if not channel:
        print("服务器未设置系统频道,无法发送欢迎消息")
        return
    
    background = Editor("background.jpg")
    # 使用display_avatar获取头像URL,处理无自定义头像的情况
    profile_image = await load_image_async(str(member.display_avatar.url))

    profile = Editor(profile_image).resize((150,150)).circle_image()
    poppins = Font.poppins(size=50, variant="bold")
    poppins_small = Font.poppins(size=20, variant ="light")
    
    background.paste(profile, (325,90))
    background.ellipse((325, 90), 150, 150, outline="white",stroke_width=5)

    background.text((400, 260), f"Welcome {member.guild.name}", color="white", font=poppins, align="center")
    background.text((400,325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small,align="center")

    file = discord.File(fp=background.image_bytes, filename="background.jpg")
    await channel.send(f"Hello {member.mention}! Welcome To **{member.guild.name}**")
    await channel.send(file=file)

bot.run('你的机器人Token')
额外说明
  • display_avatar是discord.py v1.5+新增的属性,确保你的discord.py版本符合要求(可以用pip install -U discord.py更新)。
  • 如果仍遇到问题,检查background.jpg文件路径是否正确,确保该文件存在于代码运行的目录下。

内容的提问来源于stack exchange,提问作者sh4p3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:35:24