'Auto BNB Transfer Bot throws up error after the first transaction

import config 
from decimal import Decimal
from web3 import Web3
while True:
bsc = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc))
balance_wei=web3.eth.get_balance(config.address1)
balance=web3.fromWei(balance_wei,'ether')
nonce=web3.eth.getTransactionCount(config.address1)
gas=21000
max_transfer=balance-Decimal(0.000105)
print (max_transfer)

if max_transfer>0:

    tx= {
        'nonce':nonce,
        'to':config.address2,
        'value':web3.toWei(max_transfer,'ether'),
        'gas':gas,
        'gasPrice':web3.toWei('5','gwei')


    }
    signed_tx=web3.eth.account.signTransaction(tx, config.private_key)
    tx_hash=web3.eth.sendRawTransaction(signed_tx.rawTransaction)
    print(web3.toHex(tx_hash))

I am building a bot that auto transfer BNB from my account that was recently hacked.After setting the continuous loop using the while statement and run the code, everything works fine for just the first transaction. I throws the below error immediately after auto transferring the bnb and kills the program. I have to manually run the program again. What I am trying to achieve is a continuous program that will keep on running 24/7 without me having to rerun each time a transaction is made. A kind assistance will be welcomed to protect my valuable assets.

Generated error after first transaction.

return self.formatted_response(response,
  File "C:\Users\m2jto\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 171, in formatted_response
    raise ValueError(response["error"])
ValueError: {'code': -32000, 'message': 'already known'}


Solution 1:[1]

I was able to solve the problem by just putting the tx_Hash in a try:,except: block and adding a sleep function. This did the magic as I tested my bot severally by sending in bnb many times and it auto send out without it crashing. I believe this method of using try and except block with time.sleep() function can be used to solve many valueError. see below

try:
        signed_tx=web3.eth.account.signTransaction(tx, config.private_key)
        tx_Hash=web3.eth.sendRawTransaction(signed_tx.rawTransaction)
        print(web3.toHex(txHash))
except:
        time.sleep(3)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Engr. Sule Muhammed Abba