基于Nextcord机器人调用Pexels API获取随机图片的技术问询
Pexels API调用与Nextcord机器人问题排查
问题背景
我想在Nextcord机器人的斜杠命令中调用Pexels API获取随机图片,并将机器人部署在Repl.it平台上,以下是编写的代码,需要排查问题:
@client.slash_command(name = "init", description = "Get Images for your inits", guild_ids=[testServerId]) async def init(interaction: Interaction): await interaction.response.defer() async with aiohttp.ClientSession()as session: async with session.get(url = "https://api.pexels.com/v1/curated", headers = {'Authorization': "23456789"}, data = {"per_page": "1"}) as response: raw = await response.text() raw = raw.replace('[', '').replace(']', '') init = json.loads(raw) url = init["url"] myobj = {'per_page':'1'} embed = nextcord.Embed(page = init["page"], timestamp = datetime.now(), color = nextcord.Colour.green()) try: embed.add_field(name = "Copyright", value = init["copyright"]) except KeyError: pass embed.set_image(url = url, myobj = myobj) embed.set_footer(text = f"From {init['date']}") await interaction.followup.send(embed = embed)
排查出的问题及修正方案
- GET请求参数传递错误:GET请求不能通过
data字段传参,per_page需作为URL查询参数拼接,正确的请求URL应为https://api.pexels.com/v1/curated?per_page=1。 - JSON解析逻辑错误:Pexels接口返回的结构是
{"photos": [...], "page": ...},直接替换括号会破坏JSON结构,正确做法是先解析完整响应,再取photos数组的第一个元素。 - Embed初始化参数错误:
nextcord.Embed不存在page参数,若需展示页码,应通过add_field添加。 - 图片URL获取错误:Pexels图片的实际地址在
src对象中,需通过photo["src"]["original"](或其他尺寸字段)获取,而非init["url"]。 - set_image方法参数错误:该方法仅接受
url和proxy_url参数,无需传递myobj。 - 字段取值错误:Pexels返回的图片对象中,摄影师信息对应
photographer字段,无直接的copyright和date字段,需调整取值逻辑。 - API密钥未替换:代码中的
23456789是占位符,需替换为真实的Pexels API密钥,否则请求会返回401未授权。 - 缺失必要导入:需确保已导入
aiohttp、json、datetime等模块。
修正后的代码
import aiohttp import json from datetime import datetime import nextcord from nextcord import Interaction @client.slash_command(name="init", description="Get Images for your inits", guild_ids=[testServerId]) async def init(interaction: Interaction): await interaction.response.defer() # 替换为你的真实Pexels API密钥 API_KEY = "你的Pexels API密钥" url = "https://api.pexels.com/v1/curated?per_page=1" async with aiohttp.ClientSession() as session: async with session.get(url, headers={"Authorization": API_KEY}) as response: if response.status != 200: await interaction.followup.send("获取图片失败,请稍后重试") return data = await response.json() # 取返回的第一张图片 photo = data["photos"][0] # 获取原图地址,也可选择medium/large等其他尺寸 image_url = photo["src"]["original"] photographer = photo["photographer"] page = data["page"] embed = nextcord.Embed(title="随机精选图片", timestamp=datetime.now(), color=nextcord.Colour.green()) embed.add_field(name="摄影师", value=photographer, inline=False) embed.add_field(name="页码", value=str(page), inline=False) embed.set_image(url=image_url) embed.set_footer(text="来源:Pexels") await interaction.followup.send(embed=embed)
内容的提问来源于stack exchange,提问作者ai manifest
相关产品推荐
相关产品推荐

