使用discord.py+PIL生成带成员数图片报错:int类型不可迭代
解决discord.py中PIL写入服务器成员数图片时的TypeError错误
问题描述
实现discord.py的on_message事件,当有消息发送时向频道发送一张通过PIL库写入服务器成员数(guild.member_count)的图片,但运行时报错。
错误信息(翻译后)
2022-12-30 09:48:45 ERROR discord.client Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\RainWon\PycharmProjects\bot\venv\lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "C:\Users\RainWon\PycharmProjects\bot\bot.py", line 108, in on_message pencil.text((28, 650), guild.member_count, font=font, fill='black', size=1000) File "C:\Users\RainWon\PycharmProjects\bot\venv\lib\site-packages\PIL\ImageDraw.py", line 422, in text if self._multiline_check(text): File "C:\Users\RainWon\PycharmProjects\bot\venv\lib\site-packages\PIL\ImageDraw.py", line 384, in _multiline_check return split_character in text TypeError: argument of type 'int' is not iterable
错误原因
- 参数类型不匹配:
guild.member_count返回整数类型,但PIL的ImageDraw.text()方法要求文本参数必须是字符串。方法内部会检查文本中是否包含换行符(需要迭代文本内容),整数无法被迭代,因此抛出TypeError。 - on_message事件参数错误:discord.py的
on_message事件接收的参数是message对象,不是ctx。 - 无效的服务器/频道获取方式:原代码中
guild = bot.get_guild(guild.id)属于循环引用,逻辑错误,无法正确获取服务器对象。 - 多余无效参数:
pencil.text()中的size=1000是无效参数,ImageDraw.text()没有该参数,字体大小已通过ImageFont.truetype设置。
修复后的代码
import discord from PIL import Image, ImageDraw, ImageFont import io # 假设bot已正确定义 @bot.event async def on_message(message): # 避免机器人响应自身消息,可按需移除 if message.author == bot.user: return guild = message.guild channel = message.channel # 打开基础图片 new_img = Image.open('image.png') # 设置字体 font = ImageFont.truetype("MabryPro-Regular.ttf", 100) draw = ImageDraw.Draw(new_img) # 将成员数转为字符串后写入图片 draw.text((28, 650), str(guild.member_count), font=font, fill='black') # 保存图片到内存并发送 with io.BytesIO() as image_binary: new_img.save(image_binary, 'PNG') image_binary.seek(0) await channel.send(file=discord.File(fp=image_binary, filename='image.png')) # 必须添加此行,否则默认消息处理逻辑会失效 await bot.process_commands(message)
额外说明
- 添加
if message.author == bot.user: return,避免机器人无限响应自身发送的图片消息。 - 最后添加
await bot.process_commands(message),确保其他命令逻辑能正常执行,否则定义的命令会失效。 - 确保
MabryPro-Regular.ttf字体文件存在于项目根目录,或提供正确的文件路径。
内容的提问来源于stack exchange,提问作者RainWon
相关产品推荐
相关产品推荐

