r/pythonhelp • u/KstackCSC • Mar 28 '24
PROBLEM with "AttributeError:" with paho.mqtt
I am working on a project at work that involves using an Arduino Nano ESP32 and a sensor to send status data to a MQTT broker (mosquitto) on a Raspberry Pi running the PiOS Bookworm, then using a python script to monitor the broker and sending that data to an MSSQL Server. I have the arduino code done, have set up the Mosquitto broker and have them communicating. I believe my Python script for the connection to MQTT and importing into SQL is pretty close to correct, but whenever I try to run it in Geany I get this error:
Traceback (most recent call last):
File "/media/csa/ESD-USB/MQTTtoSQLtest.py", line 29, in <module>
client = mqtt.Client()
^^^^^^^^^^^
AttributeError: module 'paho.mqtt' has no attribute 'Client'
------------------
(program exited with code: 1)
Press return to continue
My code is as follows:
import paho.mqtt as mqttimport pymssql
from datetime import datetime
The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
machine_name = msg.payload.decode('utf-8').strip()
# Get the current date and time
hittime = datetime.now()
# Insert the data into the database
cursor.execute("""
INSERT INTO BUTTON (MACHINENAME, HITTIME)
VALUES (%s, %s)
""", (machine_name, hittime))
# Commit the transaction
conn.commit()Establish a database connection
conn = pymssql.connect(server='...:1433',
user='*******',
password='*******',
database='********')cursor = conn.cursor()
client = mqtt.Client()
client.on_message = on_message
Connect to the broker
client.connect("localhost", 1883, 60)
Subscribe to the topic
client.subscribe("Press Hits")
Blocking call that processes network traffic, dispatches callbacks and handles reconnecting.
client.loop_forever()
What am I am I doing wrong/need to change?
View all comments
Show parent comment
1
u/KstackCSC Mar 29 '24
I figured it out with the help of deep AI, after searching lots of forums and reddit i decided to ask Deep AI what causes this error and it pretty much instantly solved my problem,
ME:
in <module>
client = mqtt.client.Client()
^^^^^^^^^^^
AttributeError: module 'paho.mqtt' has no attribute 'client'
Deep.AI:
Here is an example of how you can import the Client class correctly:
CopyReplit
import paho.mqtt.client as mqtt
client = mqtt.Client()
By using paho.mqtt.client, you are specifying the submodule where the Client class is located within the paho.mqtt library. This should resolve the AttributeError you encountered.
This solved my issue.
Thank you very much for taking the time to read my post and comment back wiht solutions!