Python Script: Rename Tasmota Webbuttons to the corresponding OpenHAB Item Label

Just spent the first quiet afternoon I’ve had in about six weeks sitting outside and cleaning up my fleet of tasmota items - firmware, web colors, etc. and started thinking about a script that would change the ‘webbutton’ in the UI to the linked item in OpenHAB instead of just reading ‘Power 1’, ‘Power 2’ etc.

I’m not a great coder but feel like I finally have something worth contributing…

it is far from perfect but good enough for how I use these, and may need to be adapted to your environment, but in short it:

iterates through all things
if the thing has ‘tasmota’ in the name, it iterates through the channels
if the channel only has one linked item and the statetopic contains ‘tasmota’ it
splits out the statetopic to send a command to the tasmota to rename the button

use at your discretion, obviously, and if you make any improvements, I’d love to see them.

import requests
import json
import paho.mqtt.client as mqtt


def getOpenHABThings():
    url = 'http://pi-openhab:8080/rest/things/'
    headers = {
        'accept': '*/*',
        'Content-Type': 'text/plain',
        'Authorization': 'Bearer YOURKEYHERE',
    }
    r = requests.get(url, headers=headers)
    data = json.loads(r.text)
    return data

def OpenHABNameToLabel(item):
    url = 'http://pi-openhab:8080/rest/items/' + item
    headers = {
        'accept': '*/*',
        'Content-Type': 'text/plain',
        'Authorization': 'Bearer YOURKEYHERE',
    }
    r = requests.get(url, headers=headers)
    label = json.loads(r.text)['label']
    return label

things = getOpenHABThings()
client = mqtt.Client(client_id="ButtonRenamer", transport='tcp', protocol=mqtt.MQTTv311, clean_session=True)
client.connect("192.168.99.99")
for thing in things:
    if 'TASMOTA' in thing['label'].upper():
        print(thing['label'])
        for item in thing['channels']:
            if len(item['linkedItems']) == 1: # don't try to assign button if 0 or more than one linked items
                name = OpenHABNameToLabel(item['linkedItems'][0])
                mqtt = item['configuration'].get('stateTopic') or ''
                if mqtt != '':
                    uid = json.dumps(item['uid'])
                    if(uid.split(':')[-1][0:5]) in ['relay', 'power']:
                        button = uid[-2]
                        channel = 'cmnd/' + '/'.join(mqtt.split('/')[1:-1]) + '/webbutton' + str(button)
                        client.publish(channel, name)
                        print('Renamed ' + name)