Create a Free Telegram Auto-Forward Application for Raspberry Pi

by HarryB1991 in Circuits > Raspberry Pi

1924 Views, 1 Favorites, 0 Comments

Create a Free Telegram Auto-Forward Application for Raspberry Pi

Telegram-Bots-CL-Blog-Title-01.png

I was looking online for a solution to auto-forward messages from multiple groups in Telegram Messenger to other groups and came across Telefeed, which is great, but if you want to forward from more than 5 groups the only option you have is to pay for their basic plan which is $7 a month. This inspired me to do some digging around to try and create an app myself to do it for free... or without the monthly subscription. I already had a few Raspberry Pi's laying around and the electricity cost to run this is negligible. I am a coding amateur and had to crawl through the internet and fail multiple times before I was successful, so I thought I'd make an instructable for people in the same boat.

Supplies

Raspberry Pi 3/4

Official Raspberry Pi power supply

8GB MicroSD card

USB MicroSD Card Reader

PC for setting up (this guide will be explaining the process using Windows)

Write Raspberry Pi OS to Your MicroSD Card

pi-imager2.gif

Plug in your USB MicroSD card reader with your MicroSD card inserted into your PC. Download Raspberry Pi Imager from here.

Once installed, choose your OS, in this case we're going to choose Raspberry Pi OS (32-bit). Now select choose storage and MAKE SURE TO PICK THE CORRECT DRIVE YOU WANT TO WRITE TO. You also need to go to the settings cog, enable SSH and create your username and password (see GIF). Once that's complete, it's time to unplug your MicroSD card and insert it into the Pi. Your Pi then needs to be plugged into your router with an ethernet cable and plugged into a power outlet. It might take a minute or 2 for the first boot before you can connect to it via PuTTY.

Connect Via SSH Using PuTTY

putty2.gif

First things first, you'll need to do a little bit of digging to find out your Pi's IP address. You can do this by logging into your router. You'll need to use a browser and navigate to your routers IP address, then log in. Typically the default login details are on a sticker on the router.

Once you know your Pi's IP address, download PuTTY from here. It's a free SSH client what you'll use to send commands to your Pi. Once you have it installed, open it up and type in your Pi's IP address, click Open, then login with your username and password that you created in step 1.

Creating Your Telegram Application

esrjrknt4m771.png

You'll need to head over to Telegram's site to create your application. Head here and follow the steps under Obtaining api_id. You'll need to save your api_id and api_hash ready for use in your Python code in later steps. Open Notepad and copy them into there and save them onto your Desktop for easy access.

Installing Pre-requisites on the Pi Ready for Your Code

Featured-Image-For-How-To-Check-Free-Disk-Space-On-Raspberry-Pi-5-Easy-Ways.png

Right... Now we're ready to send some commands over to your Pi. You'll need to make sure you have Python3 and Telethon libraries installed. You can do this with the following:

python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon

Ignore any warnings. I also found to be able to run this automatically after boot (explained in later steps), you need to do the following too:

sudo pip3 install telethon

For these steps and for my code, I used this from Stack Overflow as a base for me to build from. Credits to Ali Padida for that!

Get All of Your Chat ID's Ready

tg_feedbot.jpg

This seems cheeky... Considering the whole idea of the bot is to save paying subscription fees for more than 5 redirects with TeleFeed... Ha. Although, the best way I've found to get all of your chat ID's is to use TeleFeeds bot to gather them for you.

First of all, I created 2 test groups so I could check auto-forwarding works in later steps. It's a good idea to do that before getting all of your chat ID's.

Open Telegram and search for:

@tg_feedbot

Once you've opened the chat, start the bot and type /connect 'yourphonenumber' , make sure to use the correct country code here. E.g.

/connect 447912321321

In this case, I used 44 as my country code (UK). Now Telegram should send you a 5-digit code to connect TeleFeed bot to your Telegram account. You need to reply with 'aa' before the code for it to be connected to your account. E.g.

aa12345

Now that it's connected, you can type /chats 'yourphonenumber' to get a full list of all your chat ID's. E.g.

/chats 447912321321

This should give you a full list of all your chat, group and channel ID's. It's worth opening the TeleFeed chat up on Telegram Desktop for easy copy-pasting ready for the next step...

The Code

2853787.png

Now down to the nitty gritty. Here's a code 'template' to work with:

from telethon import TelegramClient, events
import asyncio
import logging
logging.basicConfig(level=logging.WARNING)

api_id = 12345678 # replace numbers with your api_id
api_hash = '1234567891011121314151617181920' # replace numbers with your api_hash

client = TelegramClient("yourbotname", api_id, api_hash) # replace yourbotname
client.start()

from_chat1 = 0123456789 # replace with your chat ID
to_chat1 = 0123456789 # replace with your chat ID
from_chat2 = 0123456789 # replace with your chat ID
to_chat2 = 0123456789 # replace with your chat ID
from_chat3 = 0123456789 # replace with your chat ID
to_chat3 = 0123456789 # replace with your chat ID
from_chat4 = 0123456789 # replace with your chat ID
to_chat4 = 0123456789 # replace with your chat ID
from_chat5 = 0123456789 # replace with your chat ID
to_chat5 = 0123456789 # replace with your chat ID
from_chat6 = 0123456789 # replace with your chat ID
to_chat6 = 0123456789 # replace with your chat ID
from_chat7 = 0123456789 # replace with your chat ID
to_chat7 = 0123456789 # replace with your chat ID

async def get_chat_id(title):
  async for dialog in client.iter_dialogs():
    if dialog.title == title:
      return dialog.id

@client.on(events.NewMessage)
async def my_event_handler(event):
  chat = await event.get_chat()
  if chat.id == from_chat1:
    await client.forward_messages(to_chat1, event.message)
  if chat.id == from_chat2:
    await client.forward_messages(to_chat2, event.message)
  if chat.id == from_chat3:
    await client.forward_messages(to_chat3, event.message)
  if chat.id == from_chat4:
    await client.forward_messages(to_chat4, event.message)
  if chat.id == from_chat5:
    await client.forward_messages(to_chat5, event.message)
  if chat.id == from_chat6:
    await client.forward_messages(to_chat6, event.message)
  if chat.id == from_chat7:
    await client.forward_messages(to_chat7, event.message)
asyncio.get_event_loop().run_forever()

Copy the above code into Notepad and edit in there. You can copy-paste from there once you're finished.

You need to replace the numbers in line 6 & 7 with your api_id and api_hash that you obtained in step 3. You may want to replace yourbotname on line 9 with your own (if you do, you will need to change it also in later steps). This template has 7 chats to forward from and to... Delete or add lines to suit your needs. Remember the 2 test groups I suggested? It's worth adding them in here as a from and to so you can check later on if things are up and running.

Once you're finished, open up your PuTTY session and send the following command:

nano

This will open up a text editor. Copy your code from notepad and to paste it in the PuTTY window, all you need to do is right-click on it to paste. Press Ctrl + X to exit. It will ask you if you'd like to save; press Y. Then it will ask for the filename you'd like to save the text as, type yourbotname.py and hit Enter.

To make this file executable, you'll need to change permissions of the file. You can do this using chmod:

sudo chmod a+x yourbotname.py

Running Your Python Code

Python_logo_and_wordmark.svg.png

To run your code, in PuTTY, run:

python yourbotname.py

It will then ask:

Please enter your phone (or bot token):

Make sure to include your country code when you type it in. In my case, it's +44

Please enter your phone (or bot token): +447912321321

Telegram will now send you a 5-digit code to connect your new bot to your Telegram account. Type it in when it asks:

Please enter the code you received: 12345

This can take a few minutes to get going; but all being well, your bot should connect to your account and auto-forwarding should work! Try it out with the 2 test groups I suggested earlier.

Setting Up As a Service to Run at Startup

allsystemsgo.png

Now that your Python script is up and working, we need to set it up as a service with systemd.

In the last step, after entering your phone number and verification code, you will have a new file called yourbotname.session in your Pi's user directory where your Python script is stored i.e. /home/yourusername/ (where 'yourusername' will be the username you created in step 1). When you run your python script as a service, it will run as root user/sudo; because of this, you will need to point to the absolute path of this session file in your python script for it to work on startup.

To change this, in PuTTY, run:

nano yourbotname.py

On line 9 you should see:

client = TelegramClient("yourbotname", api_id, api_hash)

Change this to:

client = TelegramClient("/home/yourusername/yourbotname", api_id, api_hash)

Replacing yourusername and yourbotname to suit your earlier changes. Press Ctrl + X to exit. Press Y to save changes and Enter to overwrite with the same filename.

Now to set up a new service with systemd. To do this we will create a new text file with nano ready to run it as a service:

sudo nano /etc/systemd/system/yourbotname.service

In nano, copy-paste the following:

[Unit]
Description=fwd
After=network.target

[Service]
Type=oneshot
ExecStartPre=/bin/sleep 30
ExecStart=/usr/bin/python3 /home/yourusername/yourbotname.py

[Install]
WantedBy=multi-user.target

Make sure you change yourusername and yourbotname to suit your earlier changes. Press Ctrl + X. Press Y to save and Enter to confirm yourbotname.service filename.

Now to finish off, run:

sudo systemctl daemon-reload
sudo systemctl enable yourbotname

This has enabled your yourbotname.service to run at startup. Restart your Pi to check all is working:

sudo reboot

You might have to give it a few minutes so the Pi has time to boot up and run your service and Python script. You can check the status of your service to see if there are any errors with the following:

sudo systemctl status yourbotname

You can also check if your Python script is running with:

ps -aef | grep python

You should be ready to rock & roll! :)

Conclusion

F2F08C76-6CFA-4A79-AE82-A7A598D39D21.png

Now I'll wait for some Linux God or Python pro to tell me how inefficient my workflow is! Lol. I'm by no means an expert, but if it works, it works! I'm all ears to hear how I can improve on this.

On another note, TeleFeed is still a great option for people wanting more advanced features, like filters, blacklists, whitelists etc. I won't take anything away from them for that. I just wanted a no-frills forwarding method without limits on the amount of groups I can have.