From 6a5e65d2f516abb2a8fff3d68f4ac2b5eaa3d009 Mon Sep 17 00:00:00 2001 From: tiennm99 Date: Wed, 3 Jul 2024 21:18:40 +0700 Subject: [PATCH] [Fix] parse source and target chat id --- .env.example | 2 +- .gitignore | 2 +- config.py | 4 ++-- main.py | 40 +++++++++++++++++++++++----------------- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/.env.example b/.env.example index aadd830..a8886bb 100644 --- a/.env.example +++ b/.env.example @@ -2,4 +2,4 @@ PHONE=+1234567890 API_ID=123456789 API_HASH=0123456789abcdef0123456789abcdef SOURCE_GROUP_ID=-123456789 -DESTINATION_GROUP_ID=-123456789 +TARGET_GROUP_ID=-123456789 diff --git a/.gitignore b/.gitignore index 67aee0b..5f60ac5 100644 --- a/.gitignore +++ b/.gitignore @@ -161,4 +161,4 @@ cython_debug/ .idea/ *.session -*.csv +*.session-journal \ No newline at end of file diff --git a/config.py b/config.py index a26e406..40b1d97 100644 --- a/config.py +++ b/config.py @@ -7,5 +7,5 @@ load_dotenv() phone = os.getenv('PHONE') api_id = os.getenv('API_ID') api_hash = os.getenv('API_HASH') -source_group_id = os.getenv('SOURCE_GROUP_ID') -destination_group_id = os.getenv('DESTINATION_GROUP_ID') +source_group_id = int(os.getenv('SOURCE_GROUP_ID')) +target_group_id = int(os.getenv('TARGET_GROUP_ID')) diff --git a/main.py b/main.py index 50954e2..0802669 100644 --- a/main.py +++ b/main.py @@ -1,26 +1,32 @@ -import getpass +import asyncio +from telethon import TelegramClient from telethon import events -from telethon.errors import SessionPasswordNeededError -from telethon.sync import TelegramClient from config import * -# client = TelegramClient(phone, api_id, api_hash) +client = TelegramClient(phone, api_id, api_hash) -# client.connect() -# if not client.is_user_authorized(): -# client.send_code_request(phone) -# try: -# client.sign_in(code=input('Enter code: ')) -# except SessionPasswordNeededError: -# client.sign_in(password=getpass.getpass()) -# client.start(phone) +@client.on(events.NewMessage(chats=[source_group_id])) +async def forward_message(event): + try: + # Forward the message to the target group + await client.forward_messages(target_group_id, event.message) + except Exception as e: + print(f"Exception on forward_message: {str(e)}") -with TelegramClient('session_name', api_id, api_hash) as client: - @client.on(events.NewMessage(chats=source_group_id)) - async def handler(event): - await client.forward_messages(destination_group_id, event.message) - client.run_until_disconnected() +async def main(): + while True: + try: + print("Starting...") + await client.start(phone) + print("Bot is running.") + await client.run_until_disconnected() + except Exception as e: + print(f"Exception on main: {str(e)}. Restarting...") + + +if __name__ == '__main__': + asyncio.run(main())