import requests
from bs4 import BeautifulSoup as bs4
from threading import Thread
import json
import time
from datetime import datetime
import _thread
webhook = ("https://hooks.slack.com/services/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")
s = requests.session()
payload={"channel": "#bot-monitor", "username": "Astro-bot", "text": "<https://www.astro-bot.io/astro/buyme-asdf-j4wrj-ypzkf|Astro Bot Restock! Click to Purchase>", "icon_emoji": ":rocket:"}
response = s.get('https://www.astro-bot.io/api/commerce/inventory/stock/?crumb=BQXy6KNmMGWENWE3YWQzMTc3MDU5NzE1ODdkNDNiM2RmZTEyNjg4&itemId=5b0dc9172b6a283905dabe08')
data = json.loads(response.text)
stock = data['results'][0]['qtyInStock']
def checkstock():
response = s.get('https://www.astro-bot.io/api/commerce/inventory/stock/?crumb=BQXy6KNmMGWENWE3YWQzMTc3MDU5NzE1ODdkNDNiM2RmZTEyNjg4&itemId=5b0dc9172b6a283905dabe08')
data = json.loads(response.text)
stock = data['results'][0]['qtyInStock']
print(stock)
def post():
global stock
if stock in [0]:
print("Out of stock! LOL!")
time.sleep(3)
checkstock()
else:
if stock > (0):
s.post(webhook, json=payload)
def main():
checkstock()
post()
if __name__ == '__main__':
main()
代码工作一次,然后当它再次检查库存时,我得到:
从None中提出JSONDecodeError(&#34;期望值&#34;,s,err.value) json.decoder.JSONDecodeError:期望值:第1行第1列(char 0)。
请建议。
答案 0 :(得分:0)
我很有礼貌,但是代码片段是反模式的集合(全局变量,重复代码,函数外部代码,错流控制),因此很难激励进行调试。越快越深入重构该代码对您的项目越有利。
话虽如此,我认为更短的代码可能会执行所请求的任务,并且它没有JSONDecodeError
:
import requests
import time
ASTRO_URL = 'https://www.astro-bot.io/api/commerce/inventory/stock/?crumb=BQXy6KNmMGWENWE3YWQzMTc3MDU5NzE1ODdkNDNiM2RmZTEyNjg4&itemId=5b0dc9172b6a283905dabe08'
WEBHOOK_URL = 'https://hooks.slack.com/services/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'
def qty_in_stock(url):
data = requests.get(url).json()
return data['results'][0]['qtyInStock']
def do_something():
pass
def main():
stock = qty_in_stock(ASTRO_URL)
if stock == 0:
print('out ot stock!')
time.sleep(3)
stock = qty_in_stock(ASTRO_URL)
print(stock)
else:
do_something()
if __name__ == '__main__':
main()