Last active
September 22, 2023 16:01
-
-
Save brasofilo/453e907fb9721607fc82fab5de844572 to your computer and use it in GitHub Desktop.
Telegram Channel Listener with Python - https://python.plainenglish.io/telegram-channel-listener-with-python-8176ebe3c89b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code from https://python.plainenglish.io/telegram-channel-listener-with-python-8176ebe3c89b | |
import configparser | |
import json | |
import re | |
from telethon.errors import SessionPasswordNeededError | |
from telethon import TelegramClient, events, sync | |
from telethon.tl.functions.messages import (GetHistoryRequest) | |
from telethon.tl.types import ( | |
PeerChannel | |
) | |
api_id = <YOUR_ID> | |
api_hash = '<YOUR_HASH>' | |
# Here you define the target channel that you want to listen to: | |
user_input_channel = 'https://t.me/<CHANNEL_NAME>' | |
subjectFilter = ['key', 'words'] | |
levelFilter = ['more', 'keywords'] | |
# Not sure if 'anon' is the correct here | |
client = TelegramClient('anon', api_id, api_hash) | |
# Listen to messages from target channel | |
@client.on(events.NewMessage(chats=user_input_channel)) | |
async def newMessageListener(event): | |
# Get message text | |
newMessage = event.message.message | |
# Apply 1st round of Regex for Subject for current messageContent — return list of keywords found (case—insensitive) | |
subjectFiltered = re.findall(r"(?=("+'|'.join(subjectFilter)+r"))", newMessage, re.IGNORECASE) | |
if len(subjectFiltered) != 0: | |
# Apply 2nd round of Regex for Level | |
levelFiltered = re.findall(r"(?=("+'|'.join(levelFilter)+r"))", newMessage, re.IGNORECASE) | |
if len(levelFiltered) != 0: | |
await client.forward_messages(entity='me', messages=event.message) | |
with client: | |
client.run_until_disconnected() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment