71 lines
1.9 KiB
Python
71 lines
1.9 KiB
Python
|
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())
|