Git Product home page Git Product logo

python-aria-mirror-bot's Introduction

What is this repo about?

This is a telegram bot writen in python for mirroring files on the internet to our beloved Google Drive.

Inspiration

This project is heavily inspired from @out386 's telegram bot which is written in JS.

Features supported:

  • Mirroring direct download links to google drive
  • Download progress
  • Upload progress
  • Download/upload speeds and ETAs
  • Docker support
  • Uploading To Team Drives.
  • Index Link support
  • Service account support
  • Mirror all youtube-dl supported links
  • Mirror telegram files
  • Stable Mega.nz support
  • Unzip downloads
  • Persistent authorised chat storage

How to deploy?

Deploying is pretty much straight forward and is divided into several steps as follows:

Installing requirements

  • Clone this repo:
git clone https://github.com/lzzy12/python-aria-mirror-bot mirror-bot/
cd mirror-bot
  • Install requirements For Debian based distros
sudo apt install python3

Install Docker by following the official docker docs

  • For Arch and it's derivatives:
sudo pacman -S docker python
  • Install dependencies for running setup scripts:
pip3 install -r requirements-cli.txt

Setting up config file

NOTE: Starting from 953113269e4424ecb956d0b9b093b846301efffb we are moving away from storing authroized chat ids in txt files. We will be using a light weight redis db. So, going forword, a redis db is a must.

cp config_sample.env config.env
  • Remove the first line saying:
_____REMOVE_THIS_LINE_____=True

Fill up rest of the fields. Meaning of each fields are discussed below:

  • BOT_TOKEN : The telegram bot token that you get from @BotFather
  • GDRIVE_FOLDER_ID : This is the folder ID of the Google Drive Folder to which you want to upload all the mirrors.
  • DOWNLOAD_DIR : The path to the local folder where the downloads should be downloaded to
  • DOWNLOAD_STATUS_UPDATE_INTERVAL : A short interval of time in seconds after which the Mirror progress message is updated. (I recommend to keep it 5 seconds at least)
  • OWNER_ID : The Telegram user ID (not username) of the owner of the bot
  • AUTO_DELETE_MESSAGE_DURATION : Interval of time (in seconds), after which the bot deletes it's message (and command message) which is expected to be viewed instantly. Note: Set to -1 to never automatically delete messages
  • IS_TEAM_DRIVE : (Optional field) Set to "True" if GDRIVE_FOLDER_ID is from a Team Drive else False or Leave it empty.
  • USE_SERVICE_ACCOUNTS: (Optional field) (Leave empty if unsure) Whether to use service accounts or not. For this to work see "Using service accounts" section below.
  • INDEX_URL : (Optional field) Refer to https://github.com/maple3142/GDIndex/ The URL should not have any trailing '/'
  • TELEGRAM_API : This is to authenticate to your telegram account for downloading Telegram files. You can get this from https://my.telegram.org DO NOT put this in quotes.
  • TELEGRAM_HASH : This is to authenticate to your telegram account for downloading Telegram files. You can get this from https://my.telegram.org
  • USER_SESSION_STRING : Session string generated by running:
  • MEGA_KEY: Mega.nz api key to mirror mega.nz links. Get it from Mega SDK Page
  • MEGA_USERNAME: Your mega email id (You can leave it empty, it will start megasdkrest server in anonymous mode)
  • MEGA_PASSWORD: Your password for your mega.nz account. (NOTE: You must deactivate 2FA to use the account with the bot otherwise bot will not be able to sign in)
  • REDIS_HOST: Redis DB Host URL. Redis DB is used to store the authorised chats informations (you can get it at https://redis.com -> Login -> Select Free subscription -> Create Database -> Enter a name -> Select a location(if you want) -> keep everything else default. You will get a public endpoint(refered to as REDIS_HOST in this repo), port (most probably 6397) and a password)
  • REDIS_PORT: Redis DB Port number.
  • REDIS_PASSWORD: Password of your redis DB
python3 generate_string_session.py

Note: You can limit maximum concurrent downloads by changing the value of MAX_CONCURRENT_DOWNLOADS in aria.sh. By default, it's set to 2

Getting Google OAuth API credential file

  • Visit the Google Cloud Console
  • Go to the OAuth Consent tab, fill it, and save.
  • Go to the Credentials tab and click Create Credentials -> OAuth Client ID
  • Choose Other and Create.
  • Use the download button to download your credentials.
  • Move that file to the root of mirror-bot, and rename it to credentials.json
  • Visit Google API page
  • Search for Drive and enable it if it is disabled
  • Finally, run the script to generate token file (token.pickle) for Google Drive:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
python3 generate_drive_token.py

Deploying

  • Start docker daemon (skip if already running):
sudo dockerd
  • Build Docker image:
sudo docker build . -t mirror-bot
  • Run the image:
sudo docker run mirror-bot

Using service accounts for uploading to avoid user rate limit

For Service Account to work, you must set USE_SERVICE_ACCOUNTS="True" in config file or environment variables Many thanks to AutoRClone for the scripts NOTE: Using service accounts is only recommended while uploading to a team drive.

Generating service accounts

Step 1. Generate service accounts What is service account

Let us create only the service accounts that we need. Warning: abuse of this feature is not the aim of this project and we do NOT recommend that you make a lot of projects, just one project and 100 sa allow you plenty of use, its also possible that over abuse might get your projects banned by google.

Note: 1 service account can copy around 750gb a day, 1 project can make 100 service accounts so that's 75tb a day, for most users this should easily suffice. 

python3 gen_sa_accounts.py --quick-setup 1 --new-only

A folder named accounts will be created which will contain keys for the service accounts

NOTE: If you have created SAs in past from this script, you can also just re download the keys by running:

python3 gen_sa_accounts.py --download-keys project_id

Add all the service accounts to the Team Drive

  • Run:
python3 add_to_team_drive.py -d SharedTeamDriveSrcID

Youtube-dl authentication using .netrc file

For using your premium accounts in youtube-dl, edit the netrc file (in the root directory of this repository) according to following format:

machine host login username password my_youtube_password

where host is the name of extractor (eg. youtube, twitch). Multiple accounts of different hosts can be added each separated by a new line

python-aria-mirror-bot's People

Contributors

a092devs avatar adyatan avatar akianonymus avatar archie9211 avatar gautamajay52 avatar jaskaransm avatar lzzy12 avatar magneto261290 avatar mohitmallick17 avatar sainak avatar sawankumar avatar smartass08 avatar vegitouchiha avatar viper-adnan avatar yash-garg avatar yshalsager avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-aria-mirror-bot's Issues

Deploy succeeded but sending files to mirror causes the following

`Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/urllib3/connection.py", line 156, in _new_conn
conn = connection.create_connection(
File "/usr/local/lib/python3.8/site-packages/urllib3/util/connection.py", line 84, in create_connection
raise err
File "/usr/local/lib/python3.8/site-packages/urllib3/util/connection.py", line 74, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 665, in urlopen
httplib_response = self._make_request(
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 387, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/local/lib/python3.8/http/client.py", line 1230, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1276, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1225, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/usr/local/lib/python3.8/http/client.py", line 1004, in _send_output
self.send(msg)
File "/usr/local/lib/python3.8/http/client.py", line 944, in send
self.connect()
File "/usr/local/lib/python3.8/site-packages/urllib3/connection.py", line 184, in connect
conn = self._new_conn()
File "/usr/local/lib/python3.8/site-packages/urllib3/connection.py", line 168, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f2b9ec73df0>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 719, in urlopen
retries = retries.increment(
File "/usr/local/lib/python3.8/site-packages/urllib3/util/retry.py", line 436, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=6800): Max retries exceeded with url: /jsonrpc (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2b9ec73df0>: Failed to establish a new connection: [Errno 111] Connection refused'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/usr/src/app/bot/helper/mirror_utils/download_tools.py", line 21, in add_download
download = aria2.add_uris([link], {'dir': DOWNLOAD_DIR + str(self.__listener.uid)})
File "/usr/local/lib/python3.8/site-packages/aria2p/api.py", line 154, in add_uris
gid = self.client.add_uri(uris, client_options, position)
File "/usr/local/lib/python3.8/site-packages/aria2p/client.py", line 441, in add_uri
return self.call(self.ADD_URI, params=[uris, options, position])
File "/usr/local/lib/python3.8/site-packages/aria2p/client.py", line 224, in call
return self.res_or_raise(self.post(self.get_payload(method, params, msg_id=msg_id)))
File "/usr/local/lib/python3.8/site-packages/aria2p/client.py", line 321, in post
return requests.post(self.server, data=payload).json()
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=6800): Max retries exceeded with url: /jsonrpc (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2b9ec73df0>: Failed to establish a new connection: [Errno 111] Connection refused'))`

[Issue] Problem with torrent-file mirroring.

After you guys added YT-DL, mirroring with torrent files has not been possible.
It uploads back the same torrent file.😨
Check logs below.

2020-03-28T16:50:39.136684+00:00 app[worker.1]: 2020-03-28 16:50:39,135 - bot - INFO -
2020-03-28T16:50:39.961262+00:00 app[worker.1]: [generic] file_111: Requesting header
2020-03-28T16:50:40.367172+00:00 app[worker.1]: WARNING: Falling back on generic information extractor.
2020-03-28T16:50:40.368240+00:00 app[worker.1]: [generic] file_111: Downloading webpage
2020-03-28T16:50:40.692400+00:00 app[worker.1]: WARNING: URL could be a direct video link, returning it as such.
2020-03-28T16:50:40.713767+00:00 app[worker.1]: 2020-03-28 16:50:40,713 - bot - INFO - Downloading with YT-DL: https://api.telegram.org/file/botxxxxxxxxxxxxxxxxxxxxxx/documents/file_111.torrent
2020-03-28T16:50:40.730619+00:00 app[worker.1]: [generic] file_111: Requesting header
2020-03-28T16:50:40.979488+00:00 app[worker.1]: WARNING: Falling back on generic information extractor.
2020-03-28T16:50:40.979807+00:00 app[worker.1]: [generic] file_111: Downloading webpage
2020-03-28T16:50:41.303052+00:00 app[worker.1]: WARNING: URL could be a direct video link, returning it as such.
2020-03-28T16:50:41.716273+00:00 app[worker.1]: [download] Destination: /app/temp/1256/file_111.torrent
2020-03-28T16:50:41.954258+00:00 app[worker.1]:
2020-03-28T16:50:41.954260+00:00 app[worker.1]: 2020-03-28 16:50:41,953 - bot - INFO - Download completed: file_111.torrent
2020-03-28T16:50:41.954260+00:00 app[worker.1]: 2020-03-28 16:50:41,954 - bot - INFO - Upload Name : file_111.torrent

why deleted heroku.yml ?

we cant push to heroku without heroku.yml ? i know its simple steps.but it will be hard for noobs.

[Feature Request] Option to upload files to Google Drive using rclone

Could there be a feature added such that one can choose maybe in the config file if they want to upload files via rclone or not. This is because sometimes uploads get stuck via normal upload most especially with very large files and there's no way of resuming the upload via a command so one has to restart the bot losing previously downloaded files.
But rclone uploads rarely fails as it keeps on retrying to upload after 1 fail.

I thought this might be a solution to failed uploads especially for large files.

Add a deploy to heroku button

I am on android and for some fucking reason getting this error code :
Traceback (most recent call last):
File "generate_drive_token.py", line 16, in
flow = InstalledAppFlow.from_client_secrets_file(
File "/data/data/com.termux/files/usr/lib/python3.8/site-packages/google_auth_oauthlib/flow.py", line 180, in from_client_secrets_file
with open(client_secrets_file, 'r') as json_file:
FileNotFoundError: [Errno 2] No such file or directory: 'credentials.json'
$

so my suggestion is to add deploy to heroku button please do it! and then this bot will be much easier to make/deploy

[Issue] Uploading problem

https://ghostbin.co/paste/378r8

Im on dev branch

And rest bot or crash, or stuck on 0% of uploading and other upload can stuck like in maybe 40% and dont go more, eta stopped updating, but downloading is fine, only bot stop all uploads, no gdrive limit etc

Yotube and other direct downloads [Feature Request]

Followed all the steps, but its stuck on:
Downloading
[ ] 0.00% of 0.00 B at 0.00 B/s, ETA: -

PS- DOWNLOAD_DIR = "/home/username/mirror-bot/downloads" What directory I have to choose? I have setup a Team drive
Thanks in advance!

rqst

please give list of blocked tracker if possible sir?

No module named aria2p

When I run python3 -m bot I get this error.

Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/usr/lib/python3.6/runpy.py", line 142, in _get_module_details
return _get_module_details(pkg_main_name, error)
File "/usr/lib/python3.6/runpy.py", line 109, in _get_module_details
import(pkg_name)
File "/home/ubuntu/mirror-bot/bot/init.py", line 3, in
import aria2p
ModuleNotFoundError: No module named 'aria2p'

Error 400 when the file is uploading

The bot is giving this error when uploading a file.
HttpError 400 when requesting https://www.googleapis.com/upload/drive/v3/files?alt=json&uploadType=resumable returned "Bad Request"

Although the file is getting uploaded!

Onedrive support

Google drive works great but it would be great if it's possible to upload on onedrive too.

This is not sending the files to Google Drive

I managed to host the bot on Heroku and it manages to download the files, it can also create the folders of each mirror but does not send the file to GDrive, just gets stopped at 0%...

JSONDecodeError

When I ran python3 generate_drive_token.py

I got these in return -

Traceback (most recent call last):
File "generate_drive_token.py", line 17, in
'credentials.json', __OAUTH_SCOPE)
File "/usr/local/lib/python3.6/dist-packages/google_auth_oauthlib/flow.py", line 197, in from_client_secrets_file
client_config = json.load(json_file)
File "/usr/lib/python3.6/json/init.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 7 column 1 (char 6)

[Issue] Upload never starts.

Deployed the bot on my Ubuntu system as per the notes.

Now when I send any file to bot it downloads the file but it does not upload anything.

Is this stagning-3.0 stable enough?

Hello, i have question, as i know development branch is "development" and unstable, but what about 3.0 branch? Is it also, development? Or its "stable enough"?

Error Httperror404

`
bot - INFO - Adding link: filelink

bot - INFO - Download completed: README.md

bot - INFO - Upload Name : README.md

bot.helper.ext_utils.bot_utils - INFO - Google Drive token already valid!

bot.helper.ext_utils.bot_utils - INFO - Uploading File: README.md

bot.helper.ext_utils.bot_utils - INFO - status: None

bot.helper.ext_utils.bot_utils - ERROR - <HttpError 404 when requesting https://www.googleapis.com/upload/drive/v3/files?alt=json&uploadType=resumable returned "File not found: 0ALrxNBX8bGUk9PVA.">
bot - ERROR - HttpError 404 when requesting https://www.googleapis.com/upload/drive/v3/files?alt=json&uploadType=resumable returned "File not found: 0ALrxBX8bGUk9PVA."
bot - INFO - Cleaning download: /bot/downloads/102
`

error

~/mirror-bot$ python3 generate_drive_token.py
Traceback (most recent call last):
File "generate_drive_token.py", line 3, in
from google_auth_oauthlib.flow import InstalledAppFlow
ModuleNotFoundError: No module named 'google_auth_oauthlib'

[Feature Request] Specify directory for the bot to upload files in the same

Can we have the bot upload the files to a specific directory, which we specify at the time of mirroring.

Like I have a parent directory ex: Mirrored Stuff and in that, I'd like to classify my mirrored stuff like Anime, Tv-Shows, Movies, etc in their respective directories.

So when mirroring/cloning (if it's possible) can we specify something like:

/mirror (magnet/link) dir=(dir name or id)

It'd be really great and would save a lot of time.

Stuck on MetaData

Hey brother. First of all thanks for your hard work. The issue I am facing is the bot gets stuck on Metadata even when torrent that has seeds (Joker BluRay for now). I tried other few torrents too... Same issue. But its working for DDLs. What can I do to fix this? Also I couldn't cancel torrents using /cancelmirror as only the /mirror command is working for me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.