如何使用Nextcord API获取Discord线程的首张/末张图片?
使用Nextcord获取Discord线程的首张/末张图片
不需要用requests.get去获取图片URL,Nextcord的消息对象自带附件信息,直接从消息的attachments属性里就能提取图片链接。
核心逻辑
遍历线程消息历史,筛选出带有图片类型附件的消息,根据遍历顺序(正序/倒序)拿到首张或末张图片:
- 要首张图片:按消息发送顺序正序遍历(
oldest_first=True),找到第一个带图片的消息 - 要末张图片:按消息发送顺序倒序遍历(
oldest_first=False),找到第一个带图片的消息
完整代码示例
# 获取线程的首张图片 if message.flags.has_thread: async for m in message.thread.history(limit=None, oldest_first=True): # 筛选消息中的图片附件 for attachment in m.attachments: if attachment.content_type.startswith('image/'): first_image_url = attachment.url print(f"首张图片URL: {first_image_url}") # 找到后立即终止遍历 break else: # 当前消息无图片,继续下一条 continue break # 获取线程的末张图片 if message.flags.has_thread: async for m in message.thread.history(limit=None, oldest_first=False): for attachment in m.attachments: if attachment.content_type.startswith('image/'): last_image_url = attachment.url print(f"末张图片URL: {last_image_url}") break else: continue break
关键说明
attachment.url就是图片的直接访问链接,可直接用于下载或展示,无需额外请求content_type.startswith('image/')用于过滤图片类型附件,排除文档、视频等非图片内容limit=None会遍历线程全部消息,若只需限定数量,替换为具体数值(比如limit=100)即可
内容的提问来源于stack exchange,提问作者fabmilo
相关产品推荐
相关产品推荐

