-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
69 lines (52 loc) · 1.95 KB
/
Copy pathstart.py
File metadata and controls
69 lines (52 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import time
import asyncio
from hnotifier import Mqtt, Config
from telethon import TelegramClient, events
class Telegram:
"""Load configuration data """
_config = Config.config("hanotifier.yaml")
token = _config.data['bot_token']
api_id = _config.data['api_id']
api_hash = _config.data['api_hash']
def __init__(self, session: str):
self.notify = None
self.session = session
self.client = None
async def connect(self):
if not self.session or not self.api_id or not self.api_hash or not self.token:
raise Exception(f"[Error] Invalid telegram data")
self.client = TelegramClient(session=self.session, api_id=self.api_id, api_hash=self.api_hash, retry_delay=10)
await self.client.start(bot_token=self.token)
print(f"[Success] Connected to Telegram")
self.register_event_handlers()
self.notify = Notifier.connect()
def register_event_handlers(self):
@self.client.on(events.NewMessage())
async def handle_new_message(event):
await self.handle_event(event)
async def handle_event(self, event):
self.notify.send(message=event.message.message)
class Notifier:
topic = "Home/helltopic"
entity = "Sensore"
def __init__(self):
self.notify = Mqtt.connect(self.entity)
self.notify.subscribe(self.topic)
@classmethod
def connect(cls):
if cls.topic and cls.entity:
return cls()
def send(self, message: str):
self.notify.mosquitto.publish(self.topic, message)
print(f"[SENT:{self.topic}] \"{message}\" -> [{self.entity}]")
# time.sleep(5)
# self.notify.mosquitto.loop_stop()
async def start():
telegram = Telegram(session="hanotifier")
await telegram.connect()
async def main():
loop = asyncio.get_event_loop()
await asyncio.create_task(start())
await loop.create_future()
if __name__ == "__main__":
asyncio.run(main())