Add names to relay bridge messages

This commit is contained in:
Tanner Collin 2023-06-26 18:51:12 +00:00
parent 7a81684a03
commit 7a053a51fe

56
main.py
View File

@ -12,8 +12,27 @@ from asyncio_mqtt import Client
import settings import settings
STORAGE_FILE = 'data/data.json'
storage = dict(nodes={})
def save_data():
with open(STORAGE_FILE, 'w') as f:
json.dump(storage, f, sort_keys=True, indent=4)
try:
storage = json.load(open(STORAGE_FILE))
except FileNotFoundError:
save_data()
bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN) bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN)
def int_to_mesh_id(num):
# converts signed 32-bit ints to unsigned hex meshtastic IDs
# example: -697240346 to !d670f4e6
hex_str = hex(num & 0xFFFFFFFF)
return '!' + hex_str[2:]
async def process_text(data): async def process_text(data):
msg_to = data.get('to', None) msg_to = data.get('to', None)
@ -23,12 +42,40 @@ async def process_text(data):
try: try:
msg_text = data['payload']['text'] msg_text = data['payload']['text']
sender = data['from']
except KeyError: except KeyError:
logging.info('Invalid payload: %s', str(data)) logging.info('Invalid payload: %s', str(data))
return return
logging.info('Channel message: %s', msg_text) sender_id = int_to_mesh_id(sender)
await bot.send_message(settings.CHAT_ID, msg_text)
try:
from_name = storage['nodes'][sender_id]['long_name']
except KeyError:
from_name = 'Unknown sender'
logging.info('Channel message from %s: %s', from_name, msg_text)
msg = from_name + ': ' + msg_text
await bot.send_message(settings.CHAT_ID, msg)
async def process_info(data):
try:
node_id = data['payload']['id']
long_name = data['payload']['longname']
short_name = data['payload']['shortname']
except KeyError:
logging.info('Invalid payload: %s', str(data))
return
logging.info('Node %s info: %s (%s)', node_id, long_name, short_name)
storage['nodes'][node_id] = dict(
node_id=node_id,
long_name=long_name,
short_name=short_name,
)
save_data()
async def process_mqtt(message): async def process_mqtt(message):
@ -55,6 +102,8 @@ async def process_mqtt(message):
if msg_type == 'text': if msg_type == 'text':
await process_text(data) await process_text(data)
if msg_type == 'nodeinfo':
await process_info(data)
else: else:
logging.debug('Ignored message type %s: %s', msg_type, text) logging.debug('Ignored message type %s: %s', msg_type, text)
return return
@ -67,4 +116,5 @@ async def fetch_mqtt():
await process_mqtt(message) await process_mqtt(message)
with bot: with bot:
bot.loop.run_until_complete(fetch_mqtt()) bot.loop.create_task(fetch_mqtt())
bot.run_until_disconnected()