最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

identical(?) discord webhook python requests getting different responses - Stack Overflow

programmeradmin11浏览0评论

I've written some code in python that scrapes a particular image url, and if it detects a change in the hash, it saves the new version, then uploads it to a discord webhook, or that's what it's supposed to do, but I'm getting a successful upload for the initial image, and a 400 error for the new image.

import requests
import hashlib
import logging
from datetime import datetime
from time import sleep as s
import discord_webhook
logging.basicConfig(level=logging.DEBUG)
webhook_url = "redacted"
webhook = discord_webhook.DiscordWebhook(url=webhook_url)
url = "redacted"
response = requests.get(url)
ct = datetime.now().strftime("%m-%d_%H-%M-%S")
fn = f"redacted_{ct}.jpg"
with open(fn, "wb") as f:
    f.write(response.content)
print(f"Image downloaded: {fn}")
try:
    while True:
        with open(fn, "rb") as f:
            webhook.add_file(file=f.read(), filename="image.jpg")
            resp = webhook.execute()
            if resp.status_code == 200:
                break
    print(f"{fn} uploaded!")
except Exception as e:
    print(e)
if response.status_code == 200:
    existing_hash = hashlib.md5(response.content).hexdigest()
while True:
    s(30)
    response = requests.get(url)
    if response.status_code == 200:
        new_hash = hashlib.md5(response.content).hexdigest()
        if new_hash != existing_hash:
            ct = datetime.now().strftime("%m-%d_%H-%M-%S")
            fn = f"redacted_{ct}.jpg"
            with open(fn, "wb") as f:
                f.write(response.content)
            print(f"Image downloaded: {fn}")
            try:
                while True:
                    with open(fn, "rb") as f:
                        webhook.add_file(file=f.read(), filename="image.jpg")
                        resp = webhook.execute()
                        if resp.status_code == 200:
                            break
                print(f"{fn} uploaded!")
            except Exception as e:
                print(e)
            existing_hash = new_hash
            continue
        else:
            print("Image is unchanged")

the hash checking, downloading of the new image, etc all work fine. It's just the upload to the webhook that I'm getting snagged on. The initial upload from when the bot first runs always gets a 200 response and works perfectly, and as far as I'm aware I used pretty much identical code in my loop, but that request gets a 400 response on every attempt. I've confirmed that the updated image is saving successfully and the filename is correct, but I get the same ERROR:discord_webhook.webhook:Webhook status code 400: {"attachments": ["0"]} error every time. I'm relatively new to python so overlook my clumsy code, please. Thanks in advance for any help.

发布评论

评论列表(0)

  1. 暂无评论