Python使用discord_webhook库调用Discord Webhook返回400错误如何解决
问题原因
Discord 对 webhook 请求有明确限制:单次请求携带的 embed 消息数量不能超过10个。你使用的discord_webhook库中,webhook对象会默认留存所有通过add_embed方法添加的embed内容,你在每次执行webhook.execute()发送消息后,没有清空已添加的embed列表,导致每次发送新消息时,embed列表长度持续累加,当累计到第11条时就触发了长度限制报错。
修复方案
有两种可行的修复方式:
- 方案1:每次发送完成后主动清空embed列表
在response = webhook.execute()代码后新增一行webhook.remove_embeds(),即可清空所有已添加的历史embed,避免列表累计。 - 方案2:直接在发送时传入embed参数,不使用全局累计列表
发送时直接将embed对象以列表形式传入execute方法,无需调用add_embed,自然不会出现累计超限问题。
另外你当前代码还有两个可以优化的点:
- 异步函数内不要使用同步的
time.sleep(1),会阻塞整个异步事件循环,建议替换为await asyncio.sleep(1) - 你当前是每个可用尺码单独发一次请求,你也可以选择最多凑齐10个embed批量发送,减少请求次数,降低触发Discord频率限制的概率。
修正后参考代码
import asyncio async def __scrape_api(session, pid): async with session.get(API_URL + pid) as response: data = await response.json() print(f"scrape {data}") if not __search_product(pid): name = data["name"] image_url = data['skus'][0]['image'] for size in data['skus']: if size['available']: print("sent") message = DiscordEmbed( title=f'{name}', url=f'{PRODUCT_URL_0}{size["sku"]}{PRODUCT_URL_1}', description=f'talla: {size["dimensions"]["Tallas Calzado"]}\nPrecio: {size["bestPriceFormated"]}' ) message.set_thumbnail(url=image_url) message.set_timestamp() # 直接传入embed发送,无全局累计问题 response = webhook.execute(embeds=[message]) # 异步sleep不阻塞事件循环 await asyncio.sleep(1) # 保存到数据库 __insert_new_product(pid, name, image_url, data['available'])
内容的提问来源于stack exchange,提问作者EDGAR MEDINA
相关产品推荐
相关产品推荐

