Web3.py – Resolving AttributeError for ‘shh’ Object

web3.py

  • Web3.py version: 4.2.1
  • Python: 3.5.2
  • OS: linux
  • geth version: 1.8.0-unstable
  • I am running geth with --shh flag and --rpcapi "admin,eth,net,web3,debug,shh"

from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('http://localhost:8545'))          

print ("web3 =", web3.version.api) #4.2.1
print(web3.shh) #error occurs

When I try to run following code above, I am having following error:

Traceback (most recent call last):
  File "dd.py", line 11, in <module>
    print(web3.shh)
AttributeError: 'Web3' object has no attribute 'shh'

[Q] How could I fix this error?

Best Answer

For web3.py==5.x.x

GethShh

The web3.geth.shh object exposes methods to interact with the RPC APIs under the shh_ namespace.


For web3.py==4.x.x

=> We have to add the following line of code in order to fix the error for the web3.py:

from web3.shh import Shh
Shh.attach(web3, "shh")

=> We also have to add the following line for web3.js. Than use shh.

var Shh = require('web3-shh');   
var shh = new Shh(Shh.givenProvider || 'http://localhost:8545'); 

Please see following solution for web3.py:

from web3 import Web3, HTTPProvider
web3 = Web3(HTTPProvider('http://localhost:8545'))

from web3.shh import Shh  # Added line
Shh.attach(web3, "shh")   # Added line

# Now we call web3.shh as we would like:

# Example
print(web3.shh.version) #5.0
kId = web3.shh.newKeyPair();    
print(kId)
print(web3.shh.getPrivateKey(kId))
...

Please see following solution for web3.js:

$ npm install web3-shh

Example code:

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));    
if(!web3.isConnected()){console.log("notconnected"); process.exit();}

var Shh = require('web3-shh');
// "Shh.providers.givenProvider" will be set if in an Ethereum supported browser.
var shh = new Shh(Shh.givenProvider || 'http://localhost:8545');

var kId = shh.newSymKey().then(console.log); //returns a valid value.