我的Neverening“while”循环正在运行,但会在“重要”迭代时被回溯终止。Opensea销售获取程序

2024-04-20 09:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在制作一个discord webhook,在Opensea上有一个新的出售我的NFT收藏中的NFT的地方,它获取它并通过webhook将它发送到discord。 唯一的问题是,我需要在一个永无止境的循环中这样做,因为Opensea的API不提供“流”,只提供一次请求。 长话短说,该程序在while循环的第一次迭代中将最近的销售额发送给discord,但在第一次迭代之后,它似乎不再捕捉到这些销售额

值得一提的是openSea.get_response(After, Before)AssettoEmbedBundletoEmbed等其他函数以及distribute(After, Before)的实际内容都是在第一次迭代中工作的函数。所有的工作都正常,因为我已经测试了好几次,并且从这个小项目开始它就一直在工作。 因此,我的主要关注点可能是导致此问题的原因:

  • 异步代码
  • 使用distribute()的每次调用打开新会话

如果你们中有人知道为什么在循环的第一次迭代之后,它实际上没有赶上销售,我很乐意听到

以下是我为启动销售回迁而运行的主要功能: (我用异步代码编写了它,我不需要这样做。请忽略)

async def start():
  print("session starting")
  while True:
    await distribute(datetime.datetime.fromisoformat(db['timestampAfter']), datetime.datetime.fromisoformat(db['timestampBefore']))
    db['timestampAfter'] = db['timestampBefore']
    db['timestampBefore'] = datetime.datetime.now().isoformat()
    await asyncio.sleep(10)
  print("session died")
async def distribute(After=None, Before=None):
    book = openSea.get_response(After, Before)
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(hook, adapter=AsyncWebhookAdapter(session))
        for sale in book:
            if sale['asset'] != None:
                await webhook.send(embed=AssettoEmbed(sale))
            elif sale['asset_bundle'] != None:
                await webhook.send(embeds=BundletoEmbed(sale))
def get_response(After, Before):
    response = requests.request("GET", url, params={**querystring, **{"occurred_before":Before, "occurred_after":After}})
    sales = json.loads(response.text)
    return sales["asset_events"][::-1]

重要编辑: 我在运行此程序的云源(repl.it)上捕获了这些回溯;它们每隔几个小时就会出现一次,具有讽刺意味的是,在销售之前:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connection.py", line 169, in _new_conn
    conn = connection.create_connection(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/util/connection.py", line 96, in create_connection
    raise err
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/util/connection.py", line 86, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 382, in _make_request
    self._validate_conn(conn)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 1010, in _validate_conn
    conn.connect()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connection.py", line 353, in connect
    conn = self._new_conn()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connection.py", line 181, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f9ae5a4f760>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/urllib3/util/retry.py", line 573, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='kv.replit.com', port=443): Max retries exceeded with url: /v0/eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTcxNjgwNzEsImlhdCI6MTYxNzA1NjQ3MSwiaXNzIjoiY29ubWFuIiwiZGF0YWJhc2VfaWQiOiIzOTAwZTk5NS0zNTRjLTQ4NmQtOTU5NC03YjY5MDZmMmM0NzEifQ.DzSMWXog6bqPhfC74A-zzmDDIQxaPMsNDiTArcWdg8wX07EI090XPxSEs7vtdgJU83EU2Jx6hLh1ZvF5xl-qcw/timestampAfter (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f9ae5a4f760>: Failed to establish a new connection: [Errno 111] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    asyncio.run(start())
  File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/Cryptomon-Sales-Bot/distributing.py", line 108, in start
    await distribute(datetime.datetime.fromisoformat(db['timestampAfter']), datetime.datetime.fromisoformat(db['timestampBefore']))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 434, in __getitem__
    raw_val = self.get_raw(key)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 472, in get_raw
    r = self.sess.get(self.db_url + "/" + urllib.parse.quote(key))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='kv.replit.com', port=443): Max retries exceeded with url: /v0/eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTcxNjgwNzEsImlhdCI6MTYxNzA1NjQ3MSwiaXNzIjoiY29ubWFuIiwiZGF0YWJhc2VfaWQiOiIzOTAwZTk5NS0zNTRjLTQ4NmQtOTU5NC03YjY5MDZmMmM0NzEifQ.DzSMWXog6bqPhfC74A-zzmDDIQxaPMsNDiTArcWdg8wX07EI090XPxSEs7vtdgJU83EU2Jx6hLh1ZvF5xl-qcw/timestampAfter (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f9ae5a4f760>: Failed to establish a new connection: [Errno 111] Connection refused'))

Tags: inpydbdatetimelibpackageslinesite