Finish prototype Meshtastic-Telegram bridge
This commit is contained in:
parent
517cca43b3
commit
eb87586b29
70
main.py
Normal file
70
main.py
Normal file
|
@ -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())
|
5
settings.py.example
Normal file
5
settings.py.example
Normal file
|
@ -0,0 +1,5 @@
|
|||
API_ID = 0
|
||||
API_HASH = ''
|
||||
API_TOKEN = ''
|
||||
|
||||
CHAT_ID = 0
|
Loading…
Reference in New Issue
Block a user