Skip to content

Commit

Permalink
Rewrite
Browse files Browse the repository at this point in the history
Added option to replace string from message.
  • Loading branch information
viperadnan-git committed Apr 10, 2021
1 parent 3ce63bc commit 89c1bc0
Show file tree
Hide file tree
Showing 8 changed files with 158 additions and 58 deletions.
2 changes: 1 addition & 1 deletion Procfile
Original file line number Diff line number Diff line change
@@ -1 +1 @@
worker: python3 main.py
worker: python3 -m bot
22 changes: 15 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Telegram Message Forwarder Bot
A telegram bot, which can forward messages from channel, group or chat to another channel, group or chat automatically.

## Deploy to Heroku
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

### Configuration
Expand All @@ -16,17 +15,26 @@ To configure this bot add the environment variables stated below. Or add them in
```
CHAT_ID_A CHAT_ID_B, CHAT_ID_C CHAT_ID_D
```
Or if you want to forward message from chat A to chat B and chat C
Or if you want to forward message from chat A to chat B, C and D. And from Chat E to Chat F
```
CHAT_ID_A CHAT_ID_B, CHAT_ID_B CHAT_ID_C
CHAT_ID_A CHAT_ID_B CHAT_ID_C CHAT_ID_D, CHAT_ID_E CHAT_ID_F
↑ ^---------------------^ ↑ ↑ to another chat
From channel To channel from another channel
```
- `REMOVE_STRING` - (Optional) Keyword to remove from message before forwarding.
- `REPLACE_STRING` - (Optional) Keyword to add in the place of `REMOVE_STRING`

### Installing Requirements
Install the required Python Modules in your machine. Not required if using [Heroku](https://heroku.com).
Install the required Python Modules in your machine.
```
pip3 install -r requirements.txt
```
### Deployment
With python3.7 or later.
```
python3 -m bot
```

## Copyright & License
- Copyright (©) 2020 by [Adnan Ahmad](https://github.com/viperadnan-git)
- Licensed under the terms of the [GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007](./LICENSE)
### Copyright & License
- Copyright © 2021 — [Adnan Ahmad](https://github.com/viperadnan-git)
- Licensed under the terms of the [GNU General Public License Version 3 ‐ 29 June 2007](./LICENSE)
76 changes: 76 additions & 0 deletions bot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import os
import sys
import logging
from os import environ
from dotenv import load_dotenv
from pyrogram import Client
from bot.helper.utils import get_formatted_chats

logging.basicConfig(format='[%(asctime)s - %(pathname)s - %(levelname)s] %(message)s',
handlers=[logging.FileHandler('log.txt'), logging.StreamHandler()],
level=logging.INFO)
logging.getLogger("pyrogram").setLevel(logging.ERROR)
LOG = logging.getLogger(__name__)

if os.path.exists('config.env'):
load_dotenv('config.env')

chats_data = {}

try:
api_id = int(environ["API_ID"])
api_hash = environ["API_HASH"]
bot_token = environ.get("BOT_TOKEN", None)
tg_session = environ.get("TELEGRAM_SESSION", None)
try:
from_chats = list(set(int(x) for x in environ.get("FROM_CHATS").split()))
to_chats = list(set(int(x) for x in environ.get("TO_CHATS").split()))
except Exception as e:
from_chats = []
to_chats = []
advance_config = environ.get("ADVANCE_CONFIG", None)
if advance_config:
from_chats = []
remove_string = environ.get("REMOVE_STRING", False)
replace_string = environ.get("REPLACE_STRING", "")
except KeyError as e:
LOG.error(e)
LOG.error("One or more variables missing. Exiting...")
sys.exit(1)
except ValueError as e:
LOG.error(e)
LOG.error("One or more variables are wrong. Exiting...")
sys.exit(1)

if tg_session:
app = Client(tg_session, api_id, api_hash)
elif bot_token:
app = Client(":memory:", api_id, api_hash, bot_token=bot_token)
else:
LOG.error("Set either TELEGRAM_SESSION or BOT_TOKEN variable.")
sys.exit(1)

if advance_config:
with app:
for chats in advance_config.split(","):
chat = chats.strip().split()
chat = get_formatted_chats(chat, app)
f = chat[0]
del chat[0]
if f in chats_data:
c = chats_data[f]
c.extend(chat)
chats_data[f] = c
else:
chats_data[f] = chat
if not f in from_chats:
from_chats.append(f)
LOG.info(from_chats)
LOG.info(chats_data)
else:
if len(to_chats) == 0 or len(from_chats) == 0:
LOG.error("Set either ADVANCE_CONFIG or FROM_CHATS and TO_CHATS")
sys.exit(1)
else:
LOG.info(from_chats)
LOG.info(to_chats)
38 changes: 38 additions & 0 deletions bot/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
from pyrogram import filters
from bot import LOG, app, advance_config, chats_data, from_chats, to_chats, remove_string, replace_string

@app.on_message(filters.chat(from_chats) & filters.incoming)
def work(client, message):
caption = None
msg = None
if remove_string:
if message.media:
caption = message.caption.html.replace(remove_string, replace_string)
elif message.text:
msg = message.text.html.replace(remove_string, replace_string)
if advance_config:
try:
for chat in chats_data[message.chat.id]:
if caption:
message.copy(chat, caption=caption)
elif msg:
app.send_message(chat, msg, parse_mode="html")
else:
message.copy(chat)
except Exception as e:
LOG.error(e)
else:
try:
for chat in to_chats:
if caption:
message.copy(chat, caption=caption)
elif msg:
app.send_message(chat, msg)
else:
message.copy(chat)
except Exception as e:
LOG.error(e)


app.run()
Empty file added bot/helper/message.py
Empty file.
27 changes: 27 additions & 0 deletions bot/helper/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import sys

def get_formatted_chats(chats, app):
formatted_chats = []
for chat in chats:
try:
if isInt(chat):
formatted_chats.append(int(chat))
elif chat.startswith("@"):
formatted_chats.append(app.get_chat(chat.replace("@", "")).id)
elif chat.startswith("https://t.me/c/") or chat.startswith("https://telegram.org/c/") or chat.startswith("https://telegram.dog/c/"):
chat_id = chat.split("/")[4]
if isInt(chat_id):
chat_id = "-100" + chat_id
chat_id = app.get_chat(int(chat_id)).id
formatted_chats.append(chat_id)
except Exception as e:
LOG.error(e)
sys.exit(1)
return formatted_chats

def isInt(value):
try:
int(value)
return True
except ValueError:
return False
49 changes: 0 additions & 49 deletions main.py

This file was deleted.

2 changes: 1 addition & 1 deletion runtime.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
python-3.7.9
python-3.7.10

0 comments on commit 89c1bc0

Please sign in to comment.