import asyncio
import aiohttp
import time
import datetime

from web3 import Web3

bscscan_api_key = '<TRUFFLEHOG_REDACTED_BSCSCAN>'

# Create a semaphore with a limit of 3
semaphore = asyncio.Semaphore(1)

abi = [{"constant": True, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}]

w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))

async def get_contract_details(contract_address):
    try:
        checksum_address = Web3.to_checksum_address(contract_address)
        contract = w3.eth.contract(address=checksum_address, abi=abi)
        name = contract.functions.name().call()
    except Exception as e:
        print(f"Error getting contract details: {e}")
        return None

    return {"name": name}

async def get_latest_block_number():
    async with aiohttp.ClientSession() as session:
        url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}'
        async with session.get(url) as response:
            data = await response.json()
            return int(data['result'], 16)

async def get_external_transactions(block_number):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'

            try:
                async with session.get(url) as response:
                    data = await response.json()
            except Exception as e:
                print(f'Error in API request: {e}')
                return []

            if data['result'] is None or isinstance(data['result'], str):
                print(f"Error: Cannot find the block")
                return []

            return data['result'].get('transactions', [])

async def get_contract_address(tx_hash):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'

            try:
                async with session.get(url) as response:
                    data = await response.json()
            except Exception as e:
                print(f'Error in API request: {e}')
                return None

            if data['result'] is None or not isinstance(data['result'], dict):
                print(f"Error: Cannot find the address")
                return None

            return data['result'].get('contractAddress')

def check_method_id(input_data):
    method_id = input_data[:10]
    return method_id[-4:] == '6040'

async def get_block_details(block_number):
    try:
        block = w3.eth.getBlock(block_number)
    except Exception as e:
        print(f"Error getting block details: {e}")
        return None

    return {"timestamp": block['timestamp']}

async def process_block(block_number_int):
    block_number = hex(block_number_int)
    transactions = await get_external_transactions(block_number)

    if not transactions:
        print(f'No transactions found in block {block_number_int}')
    else:
        print(f'Transactions in block {block_number_int}:')
        for tx in transactions:
            if check_method_id(tx['input']):
                if tx['to'] is None:
                    contract_address = await get_contract_address(tx['hash'])
                    contract_details = await get_contract_details(contract_address)
                    if contract_details:
                        block_details = await get_block_details(block_number_int)
                        contract_age = datetime.datetime.now() - datetime.datetime.fromtimestamp(block_details["timestamp"])
                        print(f"New contract creation with TokenTracker details: Contract Address: {contract_address}, Creator Address: {tx['from']}, Name: {contract_details['name']}, BlockNumber: {block_number_int}, Contract Age: {contract_age}")
        print("\n")  # Print an empty line between blocks

async def display_transactions(block_start, block_end):
    tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
    await asyncio.gather(*tasks)

async def main():
    block_start = await get_latest_block_number()  # Start with the latest block number
    block_end = block_start + 10  # Process 10 blocks initially

    while True:
        await display_transactions(block_start, block_end)

        # Update block_start and block_end to check for new blocks every 5 seconds
        block_start = block_end + 1
        block_end = await get_latest_block_number()
        time.sleep(5)

asyncio.run(main())

The code above throws the following error

Transactions in block 29240837:

Error getting block details: 'Eth' object has no attribute 'getBlock'
Traceback (most recent call last):
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 123, in <module>
    asyncio.run(main())
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 116, in main
    await display_transactions(block_start, block_end)
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 109, in display_transactions
    await asyncio.gather(*tasks)
  File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 103, in process_block
    contract_age = datetime.datetime.now() - datetime.datetime.fromtimestamp(block_details["timestamp"])
                                                                             ~~~~~~~~~~~~~^^^^^^^^^^^^^
Fix it
TypeError: 'NoneType' object is not subscriptable