#!/usr/bin/env python3
# encoding: utf-8
import asyncio
import json
import sys
import re
from telethon import TelegramClient
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import GetMessagesRequest
from telethon.tl.functions.messages import GetHistoryRequest, ReadHistoryRequest
with open('config.json', 'r') as file:
config_data = json.load(file)
print(config_data)
client = TelegramClient("parser_data", config_data["api_id"], config_data["api_hash"])
async def TConnect():
await client.start()
async def ListChanels():
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id)
def save_chan_json(chan,chan_data):
f = open(chan + '.json', "w+")
json.dump(chan_data, f)
f.close()
def get_chan_json(chan):
# узнаём какое последнее сообщение прочитали на канале?
chan_data = {}
chan_data["las_id"] = 0
try:
with open(chan + '.json', 'r') as file:
chan_data = json.load(file)
print(chan_data)
return chan_data
except:
save_chan_json(chan, chan_data)
return chan_data
return chan_data;
def SendMail(chan,word,message):
msg = MIMEMultipart()
msg['Subject'] = f"Найдено слово '{word}' в новости на канале {chan} в Телеграм"
msg.add_header('Content-Type', 'text/html')
message.text=message.text.replace(word,"<strong>"+word+"</strong>")
dt_pub=message.date.strftime('%d-%m-%Y %H:%M:%S')
msg.set_payload(f"Канал: <a href='https://t.me/{chan}'>https://t.me/{chan}</a>, опубликовано {dt_pub}<hr/>"+message.text)
smtpObj = smtplib.SMTP(config_data["smtp_server"], config_data["smtp_port"])
smtpObj.starttls()
smtpObj.login(config_data["email_login"], config_data["from_password"])
smtpObj.sendmail(config_data["email_from"], config_data["notify_email"], msg.as_string().encode('utf-8'))
smtpObj.quit()
async def main():
print("-start")
await TConnect()
#await ListChanels()
for chan in config_data["chanels"]:
chan_data=get_chan_json(chan)
skeep_after = chan_data["las_id"]
if "-" in chan:
dp = await client.get_entity(int(chan))
else:
dp = await client.get_entity(chan)
poz=0
async for message in client.iter_messages(dp,limit=config_data["limit"]):
if poz==0:
chan_data["las_id"]=message.id
save_chan_json(chan, chan_data)
if skeep_after==message.id:
print("Все новости уже прочитаны...")
break
print(f"-смотрим message_id:{message.id}")
for word in config_data["alert_words"]:
if word in message.text:
print(f"--нашли слово {word}")
SendMail(chan, word, message)
print(message)
#print(message.id, message.text)
poz=poz+1
print("all done..");
if __name__ == '__main__':
for param in sys.argv:
if param == "--list_chanels":
TConnect()
ListChanels()
with client:
client.loop.run_until_complete(main())