From eb87586b299146a6587f87c4604a41d071b5b76d Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Mon, 19 Jun 2023 18:14:23 +0000 Subject: [PATCH] Finish prototype Meshtastic-Telegram bridge --- main.py | 70 +++++++++++++++++++++++++++++++++++++++++++++ settings.py.example | 5 ++++ 2 files changed, 75 insertions(+) create mode 100644 main.py create mode 100644 settings.py.example diff --git a/main.py b/main.py new file mode 100644 index 0000000..4988df2 --- /dev/null +++ b/main.py @@ -0,0 +1,70 @@ +import os +DEBUG = os.environ.get('DEBUG') + +import logging +logging.basicConfig( + format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s', + level=logging.DEBUG if DEBUG else logging.INFO) + +import json +from telethon import TelegramClient, events +from asyncio_mqtt import Client + +import settings + +bot = TelegramClient('data/bot', settings.API_ID, settings.API_HASH).start(bot_token=settings.API_TOKEN) + +async def process_text(data): + msg_to = data.get('to', None) + + if msg_to != -1: + logging.debug('Message not for channel: %s', str(data)) + return + + try: + msg_text = data['payload']['text'] + except KeyError: + logging.info('Invalid payload: %s', str(data)) + return + + logging.info('Channel message: %s', msg_text) + await bot.send_message(settings.CHAT_ID, msg_text) + + +async def process_mqtt(message): + try: + text = message.payload.decode() + except UnicodeDecodeError: + logging.info('Problem decoding unicode: %s', message.payload) + return + + topic = message.topic + logging.debug('MQTT topic: %s, message: %s', topic, text) + + try: + data = json.loads(text) + except json.JSONDecodeError: + logging.info('Problem decoding json: %s', text) + return + + if type(data) != dict or 'id' not in data: + logging.info('Not valid Meshtastic message: %s', text) + return + + msg_type = data.get('type', '') + + if msg_type == 'text': + await process_text(data) + else: + logging.debug('Ignored message type %s: %s', msg_type, text) + return + +async def fetch_mqtt(): + async with Client('localhost') as client: + async with client.filtered_messages('msh/+/json/#') as messages: + await client.subscribe('msh/+/json/#') + async for message in messages: + await process_mqtt(message) + +with bot: + bot.loop.run_until_complete(fetch_mqtt()) diff --git a/settings.py.example b/settings.py.example new file mode 100644 index 0000000..a1e2886 --- /dev/null +++ b/settings.py.example @@ -0,0 +1,5 @@ +API_ID = 0 +API_HASH = '' +API_TOKEN = '' + +CHAT_ID = 0