5

I am trying to create a python filter to read events from Smart contract but I am not successful so far. below is the sample python code and I have used "Instructor" event in solidity and trying to define "my_callback" function below whenever instructor event is fired from solidity program. Can you please help ?

import random
import sys
import os

from web3 import Web3, HTTPProvider, IPCProvider
from web3.contract import ConciseContract
import json
from web3.providers.rpc import HTTPProvider


def my_callback():
    print ('Instructor event  is fired from contract')

contractAddress = '0x2818129b6306be2a337b31d83ff9bdf6da067a41'
web3 = Web3(HTTPProvider('http://localhost:8545'))
#open("C:/Users/XXX/Documents/50_states.csv",mode='w')
with open("C:/Users/XXX/Documents/ourfirsttoken.json", mode='r') as abi_definition:
    abi = json.load(abi_definition)

fContract = web3.eth.contract(abi,contractAddress)

transfer_filter = fContract.on('Instructor',my_callback())

fContract.transact({'from': web3.eth.accounts[0]}).setInstructor('XYsdgdsZ',3255)
print('contract get instructor function ' + str(fContract.call().getInstructor()[0]))
user19510
  • 27,999
  • 2
  • 30
  • 48
Arun Kuduva
  • 51
  • 1
  • 3

1 Answers1

2

event_filter = fContract.events.Instructor.createFilter(fromBlock='latest') while True: for event in event_filter.get_new_entries(): my_callback(event) time.sleep(2)

For more check out the documentation

L12
  • 66
  • 3
  • Thanks! Any idea why web3.py doesn’t support watchers? What’s the advantage of using a websocket then? – coccoinomane Jan 29 '22 at 07:53
  • When you use websocket, you save a lot on API calls. If you use for example Infura, it has limited calls something like 100k per day, which seem like a lot, but if you run your event listener for several hours, you may get maxed out on those calls. – f22daniel Jan 28 '23 at 11:26