-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathTelegramForwarder.py
129 lines (101 loc) · 5.17 KB
/
TelegramForwarder.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import time
import asyncio
from telethon.sync import TelegramClient
from telethon import errors
class TelegramForwarder:
def __init__(self, api_id, api_hash, phone_number):
self.api_id = api_id
self.api_hash = api_hash
self.phone_number = phone_number
self.client = TelegramClient('session_' + phone_number, api_id, api_hash)
async def list_chats(self):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
try:
await self.client.sign_in(self.phone_number, input('Enter the code: '))
except errors.rpcerrorlist.SessionPasswordNeededError:
password = input('Two-step verification is enabled. Enter your password: ')
await self.client.sign_in(password=password)
# Get a list of all the dialogs (chats)
dialogs = await self.client.get_dialogs()
chats_file = open(f"chats_of_{self.phone_number}.txt", "w", encoding="utf-8")
# Print information about each chat
for dialog in dialogs:
print(f"Chat ID: {dialog.id}, Title: {dialog.title}")
chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title} \n")
print("List of groups printed successfully!")
async def forward_messages_to_channel(self, source_chat_id, destination_channel_id, keywords):
await self.client.connect()
# Ensure you're authorized
if not await self.client.is_user_authorized():
await self.client.send_code_request(self.phone_number)
await self.client.sign_in(self.phone_number, input('Enter the code: '))
last_message_id = (await self.client.get_messages(source_chat_id, limit=1))[0].id
while True:
print("Checking for messages and forwarding them...")
# Get new messages since the last checked message
messages = await self.client.get_messages(source_chat_id, min_id=last_message_id, limit=None)
for message in reversed(messages):
# Check if the message text includes any of the keywords
if keywords:
if message.text and any(keyword in message.text.lower() for keyword in keywords):
print(f"Message contains a keyword: {message.text}")
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
else:
# Forward the message to the destination channel
await self.client.send_message(destination_channel_id, message.text)
print("Message forwarded")
# Update the last message ID
last_message_id = max(last_message_id, message.id)
# Add a delay before checking for new messages again
await asyncio.sleep(5) # Adjust the delay time as needed
# Function to read credentials from file
def read_credentials():
try:
with open("credentials.txt", "r") as file:
lines = file.readlines()
api_id = lines[0].strip()
api_hash = lines[1].strip()
phone_number = lines[2].strip()
return api_id, api_hash, phone_number
except FileNotFoundError:
print("Credentials file not found.")
return None, None, None
# Function to write credentials to file
def write_credentials(api_id, api_hash, phone_number):
with open("credentials.txt", "w") as file:
file.write(api_id + "\n")
file.write(api_hash + "\n")
file.write(phone_number + "\n")
async def main():
# Attempt to read credentials from file
api_id, api_hash, phone_number = read_credentials()
# If credentials not found in file, prompt the user to input them
if api_id is None or api_hash is None or phone_number is None:
api_id = input("Enter your API ID: ")
api_hash = input("Enter your API Hash: ")
phone_number = input("Enter your phone number: ")
# Write credentials to file for future use
write_credentials(api_id, api_hash, phone_number)
forwarder = TelegramForwarder(api_id, api_hash, phone_number)
print("Choose an option:")
print("1. List Chats")
print("2. Forward Messages")
choice = input("Enter your choice: ")
if choice == "1":
await forwarder.list_chats()
elif choice == "2":
source_chat_id = int(input("Enter the source chat ID: "))
destination_channel_id = int(input("Enter the destination chat ID: "))
print("Enter keywords if you want to forward messages with specific keywords, or leave blank to forward every message!")
keywords = input("Put keywords (comma separated if multiple, or leave blank): ").split(",")
await forwarder.forward_messages_to_channel(source_chat_id, destination_channel_id, keywords)
else:
print("Invalid choice")
# Start the event loop and run the main function
if __name__ == "__main__":
asyncio.run(main())