title: How to use both subscribe and publish at the same time in mqtt python?
body: <p>I am working with a device that publishes to the topic <code>test/123</code>, where <code>123</code> is the name of the device. I need to subscribe to that topic (and processes received messages); in addition I also need to send a word to the same topic (<code>test/123</code>). The device only looks at this topic.</p>
  <p>How can I distinguish between incoming and outgoing by content? More precisely, how to send correctly. In the <code>on_message</code> method you need to do this or you need to create another method, but then how to receive incoming messages there. From the incoming messages I need to get the name of the device and then work with it.</p>
  <pre><code>import paho.mqtt.client as mqtt
  import paho.mqtt.publish as publish
  # The callback for when the client receives a CONNACK response from the server.
  def on_connect(client, userdata, flags, rc):
      print(&quot;Connected with result code &quot;+str(rc))
  
      # Subscribing in on_connect() means that if we lose the connection and
      # reconnect then subscriptions will be renewed.
      client.subscribe(&quot;/test/#&quot;)
  
  
  # The callback for when a PUBLISH message is received from the server.
  def on_message(client, userdata, msg):
      print(msg.topic+&quot; &quot;+str(msg.payload))
      imei = msg.topic.split('test/')[1]
      data = msg.payload.decode()
      print(imei)
      print(data)
      publish(imei)
      
  
  def publish(imei):
      client = mqtt.Client()
      user = 'test'
      passw = '1111'
      client.username_pw_set(user,passw)
      client.connect(&quot;localhost&quot;,1883)
      
      topic = '/test/'+ imei
      client.publish(topic,'hello')
      print('SEND')
      client.disconnect()
      
  
  client = mqtt.Client()
  user = 'test'
  passw = '1111'
  client.username_pw_set(user,passw)
  client.on_connect = on_connect
  client.on_message = on_message
  
  client.connect(&quot;localhost&quot;, 1883, 60)
  
  client.loop_forever()
  </code></pre>