├── .github └── workflows │ ├── Docker-Build-Guide.md │ ├── Docker-Code │ ├── Fly.yml │ └── docker-publish.yml ├── Commands.md ├── Dockerfile ├── Img ├── 1.png ├── 10.png ├── 11.png ├── 12.png ├── 13.png ├── 14.png ├── 15.png ├── 16.png ├── 17.png ├── 18.png ├── 19.png ├── 2.png ├── 20.png ├── 21.png ├── 22.png ├── 23.png ├── 24.png ├── 25.png ├── 26.png ├── 27.png ├── 28.png ├── 29.png ├── 3.png ├── 30.png ├── 31.png ├── 32.png ├── 33.png ├── 34.png ├── 35.png ├── 36.png ├── 37.png ├── 38.png ├── 39.png ├── 4.png ├── 40.png ├── 41.png ├── 42.png ├── 43.png ├── 44.png ├── 45.png ├── 5.png ├── 6.png ├── 7.png ├── 8.png ├── 9.png ├── Deploy-Button-Heroku.png └── deleteme.txt ├── LICENCE ├── Procfile ├── README.md ├── Termux-Guide.md ├── _config.yml ├── captain-definition ├── docker-compose.yml ├── fly.toml ├── index.html ├── requirements.txt ├── run.sh ├── sample-config.ini └── telegram_gcloner ├── config.ini ├── handlers ├── add_group.py ├── ban.py ├── cancel.py ├── choose_folder.py ├── contact.py ├── get_help.py ├── get_id.py ├── process_drive_links.py ├── process_message.py ├── sa.py ├── start.py ├── stop_task.py └── vip.py ├── telegram_gcloner.py └── utils ├── callback.py ├── config_loader.py ├── fire_save_files.py ├── google_drive.py ├── helper.py ├── process.py └── restricted.py /.github/workflows/Docker-Build-Guide.md: -------------------------------------------------------------------------------- 1 |

🐳 Docker Build Guide

2 |

As per your requirements, or to run CloneBot V2 easily on your OS and depending upon its architecture you can make your own Docker Image for CloneBot V2, the process of building docker image is automated and easy, you just need to edit Dockerfile available in root directory of main branch and trigger the Workflow from Actions Tab and it will start building your Docker Image.

3 |

🛠️ Instructions:

4 |

For quickly building the same Docker Image used by CloneBot V2:

5 |

1.Go to .github/workflows in main branch.

6 | 7 |

2.Open Docker-Code file and copy its code.

8 | 9 |

3.Go back to root directory of main branch and paste the copied code (by removing previous code) in Dockerfile.

10 |

4.Once you make new commit, then go to Actions tab and run the Publish Docker Image workflow! and it will start building your Docker Image.

11 | 12 |

5.Your Docker Image is now ready to be used, check out your Repository's Packages to know how to use it.😊

13 | 14 |

⛔NOTE: Use your own Docker Image for deploying on VPS only! Using it for deploying platforms like Heroku will simply cause Account suspension.

15 |

⚙️ Customizations

16 |

You can also customize the behaviour of Docker Image Build tool as per your needs!😉

17 |

🔫 Trigger Customization:

18 |

To set the condition "When Workflow should be triggered?", you can customize following code:

19 | https://github.com/TheCaduceus/CloneBot_V2/blob/dbbd61dc0430a5bc8eda672ef4e123a9ee5c2794/.github/workflows/docker-publish.yml#L3-L12 20 |

by default, Workflow will be triggered only if user manually do it from Actions Tab otherwise if automatic workflow trigger is enabled then it will get triggered automatically when there is new commit (including Pull Request) in main branch which can be changed.

21 |

✏️ Environment Variables:

22 |

By setting environment variables you can change the Registry and Name of your Docker Image:

23 | https://github.com/TheCaduceus/CloneBot_V2/blob/dbbd61dc0430a5bc8eda672ef4e123a9ee5c2794/.github/workflows/docker-publish.yml#L14-L18 24 |

REGISTRY: Value can be docker.io or ghcr.io. If empty then docker.io will be used.

25 |

IMAGE_NAME: Value can be anything between "" or by default it is ${{ github.repository }} which automatically set Repository name + Branch Name as IMAGE_NAME.

26 | -------------------------------------------------------------------------------- /.github/workflows/Docker-Code: -------------------------------------------------------------------------------- 1 | # As per choice 2 | FROM ubuntu:latest 3 | 4 | # Change as per VPS 5 | WORKDIR /usr/src/app 6 | RUN chmod 777 /usr/src/app 7 | 8 | # Make Non-Interactive 9 | # ENV DEBIAN_FRONTEND="noninteractive" 10 | 11 | # Or Add Time Zone 12 | # ENV TZ= # Add Zone Here 13 | # RUN ln -snf "/usr/share/zoneinfo/$TZ" /etc/localtime 14 | # RUN echo "$TZ" > /etc/timezone 15 | 16 | RUN apt-get update 17 | RUN apt-get install -y tzdata 18 | RUN apt-get -qq update 19 | 20 | # Remove if using Gclone Library 21 | RUN apt install unzip -y 22 | 23 | RUN apt-get -qq install -y git python3 python3-pip 24 | 25 | # Customize using Gclone Library without unzip 26 | RUN 27 | 28 | COPY requirements.txt . 29 | RUN pip3 install --no-cache-dir -r requirements.txt && \ 30 | apt-get -qq purge git 31 | 32 | COPY . . 33 | 34 | RUN chmod +x run.sh 35 | 36 | CMD ["bash","run.sh"] 37 | -------------------------------------------------------------------------------- /.github/workflows/Fly.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to Fly 2 | on: workflow_dispatch 3 | env: 4 | FLY_API_TOKEN: ${{secrets.FLY_API_TOKEN}} 5 | jobs: 6 | deploy: 7 | name: Deploy to Fly 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - run: | 12 | sed -i 's#URL_HERE#${{secrets.CONFIG_FILE_URL}}#' fly.toml 13 | sed -i 's#APP-NAME#${{secrets.APP_NAME}}#' fly.toml 14 | - uses: superfly/flyctl-actions/setup-flyctl@master 15 | - run: flyctl launch --generate-name --copy-config --region lax --no-deploy 16 | - run: flyctl deploy --remote-only 17 | -------------------------------------------------------------------------------- /.github/workflows/docker-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker Image 2 | 3 | # To manually run Workflow 4 | on: workflow_dispatch 5 | 6 | # To automatically run Workflow after new commit 7 | #on: 8 | #push: 9 | #branches: [ "main" ] 10 | #tags: [ 'v*.*.*' ] 11 | #pull_request: 12 | #branches: [ "main" ] 13 | 14 | env: 15 | # Use docker.io for Docker Hub if empty 16 | REGISTRY: ghcr.io 17 | # github.repository as / 18 | IMAGE_NAME: ${{ github.repository }} 19 | 20 | 21 | jobs: 22 | build: 23 | runs-on: ubuntu-latest 24 | permissions: 25 | contents: read 26 | packages: write 27 | # This is used to complete the identity challenge with sigstore/fulcio when running outside of PRs. 28 | id-token: write 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@v3 32 | # Install the cosign tool except on PR (https://github.com/sigstore/cosign-installer) 33 | - name: Install cosign 34 | if: github.event_name != 'pull_request' 35 | uses: sigstore/cosign-installer@v2.5.0 36 | with: 37 | cosign-release: 'v1.10.0' 38 | # Workaround: https://github.com/docker/build-push-action/issues/461 39 | - name: Setup Docker buildx 40 | uses: docker/setup-buildx-action@v2.0.0 41 | # Login against a Docker registry except on PR (https://github.com/docker/login-action) 42 | - name: Log into registry ${{ env.REGISTRY }} 43 | if: github.event_name != 'pull_request' 44 | uses: docker/login-action@v2.0.0 45 | with: 46 | registry: ${{ env.REGISTRY }} 47 | username: ${{ github.actor }} 48 | password: ${{ secrets.GITHUB_TOKEN }} 49 | # Extract metadata (tags, labels) for Docker (https://github.com/docker/metadata-action) 50 | - name: Extract Docker metadata 51 | id: meta 52 | uses: docker/metadata-action@v4.0.1 53 | with: 54 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 55 | # Build and push Docker image with Buildx (don't push on PR) (https://github.com/docker/build-push-action) 56 | - name: Build and push Docker image 57 | id: build-and-push 58 | uses: docker/build-push-action@v3.1.0 59 | with: 60 | context: . 61 | push: ${{ github.event_name != 'pull_request' }} 62 | tags: ${{ steps.meta.outputs.tags }} 63 | labels: ${{ steps.meta.outputs.labels }} 64 | # Sign the resulting Docker image digest except on PRs. 65 | # This will only write to the public Rekor transparency log when the Docker 66 | # repository is public to avoid leaking data. If you would like to publish 67 | # transparency data even for private images, pass --force to cosign below. (https://github.com/sigstore/cosign) 68 | - name: Sign the published Docker image 69 | if: ${{ github.event_name != 'pull_request' }} 70 | env: 71 | COSIGN_EXPERIMENTAL: "true" 72 | # This step uses the identity token to provision an ephemeral certificate against the sigstore community Fulcio instance. 73 | run: cosign sign ${{ steps.meta.outputs.tags }}@${{ steps.build-and-push.outputs.digest }} 74 | -------------------------------------------------------------------------------- /Commands.md: -------------------------------------------------------------------------------- 1 | ## Bot Commands 2 | This commands will be visible to all your Bot users as command menu, to help them discovering your Bot's functionality.
3 | ### Add following commands in BotFather: 4 | ``` 5 | start - Start the Bot 6 | sa - Upload the Serivce Account zip file to use the Bot 7 | folders - Select the Shared Drives where you wish to save your files and folders 8 | help - Get Information about the Bot 9 | ban - Ban a Telegram User ID from using the Bot 10 | unban - Reallow a Telegram User ID from using the Bot that was earlier banned 11 | vip - Add a Telegram User ID to the VIP Access List 12 | unvip - Remove a Telegram User ID to the VIP Access List 13 | id - Get your Telegram User ID 14 | contact - Get the contacts details of the owner of the Bot 15 | ``` 16 | User Commands: 17 | ``` 18 | start - Start the Bot 19 | sa - Upload the Serivce Account zip file to use the Bot 20 | folders - Select the Shared Drives where you wish to save your files and folders 21 | help - Get Information about the Bot 22 | id - Get your Telegram User ID 23 | contact - Get the contacts details of the owner of the Bot 24 | ``` 25 | Admin-only Commands: 26 | ``` 27 | ban - Ban a Telegram User ID from using the Bot 28 | unban - Reallow a Telegram User ID from using the Bot that was earlier banned 29 | vip - Add a Telegram User ID to the VIP Access List 30 | unvip - Remove a Telegram User ID to the VIP Access List 31 | ``` 32 | ⛔NOTICE: Adding this commands are optional, changing this commands from BotFather don't change it for Bot. 33 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Sync old with new 2 | FROM ghcr.io/thecaduceus/cbv2:main 3 | -------------------------------------------------------------------------------- /Img/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/1.png -------------------------------------------------------------------------------- /Img/10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/10.png -------------------------------------------------------------------------------- /Img/11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/11.png -------------------------------------------------------------------------------- /Img/12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/12.png -------------------------------------------------------------------------------- /Img/13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/13.png -------------------------------------------------------------------------------- /Img/14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/14.png -------------------------------------------------------------------------------- /Img/15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/15.png -------------------------------------------------------------------------------- /Img/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/16.png -------------------------------------------------------------------------------- /Img/17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/17.png -------------------------------------------------------------------------------- /Img/18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/18.png -------------------------------------------------------------------------------- /Img/19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/19.png -------------------------------------------------------------------------------- /Img/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/2.png -------------------------------------------------------------------------------- /Img/20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/20.png -------------------------------------------------------------------------------- /Img/21.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/21.png -------------------------------------------------------------------------------- /Img/22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/22.png -------------------------------------------------------------------------------- /Img/23.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/23.png -------------------------------------------------------------------------------- /Img/24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/24.png -------------------------------------------------------------------------------- /Img/25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/25.png -------------------------------------------------------------------------------- /Img/26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/26.png -------------------------------------------------------------------------------- /Img/27.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/27.png -------------------------------------------------------------------------------- /Img/28.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/28.png -------------------------------------------------------------------------------- /Img/29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/29.png -------------------------------------------------------------------------------- /Img/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/3.png -------------------------------------------------------------------------------- /Img/30.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/30.png -------------------------------------------------------------------------------- /Img/31.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/31.png -------------------------------------------------------------------------------- /Img/32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/32.png -------------------------------------------------------------------------------- /Img/33.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/33.png -------------------------------------------------------------------------------- /Img/34.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/34.png -------------------------------------------------------------------------------- /Img/35.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/35.png -------------------------------------------------------------------------------- /Img/36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/36.png -------------------------------------------------------------------------------- /Img/37.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/37.png -------------------------------------------------------------------------------- /Img/38.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/38.png -------------------------------------------------------------------------------- /Img/39.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/39.png -------------------------------------------------------------------------------- /Img/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/4.png -------------------------------------------------------------------------------- /Img/40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/40.png -------------------------------------------------------------------------------- /Img/41.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/41.png -------------------------------------------------------------------------------- /Img/42.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/42.png -------------------------------------------------------------------------------- /Img/43.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/43.png -------------------------------------------------------------------------------- /Img/44.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/44.png -------------------------------------------------------------------------------- /Img/45.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/45.png -------------------------------------------------------------------------------- /Img/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/5.png -------------------------------------------------------------------------------- /Img/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/6.png -------------------------------------------------------------------------------- /Img/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/7.png -------------------------------------------------------------------------------- /Img/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/8.png -------------------------------------------------------------------------------- /Img/9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/9.png -------------------------------------------------------------------------------- /Img/Deploy-Button-Heroku.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheCaduceus/CloneBot_V2/a17c9883454a9ff27543005fb543d34725d65991/Img/Deploy-Button-Heroku.png -------------------------------------------------------------------------------- /Img/deleteme.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | CloneBot V2 for cloning data in Google Drive 635 | Copyright (C) 2022 Dr.Caduceus 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: bash run.sh 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

CloneBot V2 🔥

2 | 3 |

CloneBot V2 is inspired from MsGsuite's CloneBot, which got out-dated and having too many errors in it. We both created it to keep the legacy of CloneBot alive! The bot who helped thousands for cloning their data.❤️

4 |

1. The Powerful Telegram Bot based on Gclone to clone Google Drive's Shared Drive data easily.⚡

5 |

2. CloneBot V2 usage Service Accounts to easily clone TBs of data without hitting 750GB Upload/Clone limit of Google Drive.♻️

6 |

3. It is most lightweight and performs only server-sided cloning to have very less load on system and don't use your own bandwidth.🗃️

7 |

4. Just provide the sharing link of a particular Shared Drive/folder or file and set multiple destination folders to clone data.🔗

8 | 9 |

📑 INDEX

10 |

Easily navigate through out the guide and learn about Powerful CloneBot V2 and terms related to it.

11 |

🔥 CloneBot V2

12 |

🆕 What's New!

13 |

⛔ NOTICE

14 |

⚙️ How to use?

15 |

➥🔩Commands for BotFather

16 |

🫙 Making Shared Drive

17 |

➥🌐Using Website

18 |

➥🤖Using Telegram Bot

19 |

🐍Python with PIP Installation

20 |

🕹️Deployment

21 |

➥📎Getting CONFIG_FILE_URL

22 |

-->📃Using Dr.Graph

23 |

-->🤖Using File Stream Bot

24 |

-->✏️Using GitHub Gist

25 |

➥🐳Build or Deploy using Docker

26 |

➥🕊️Deploy on Fly

27 |

➥♦️Deploy on Clever Cloud

28 |

➥🪬Deploy on Okteto

29 |

➥🖥️ Deploy on VPS or PC

30 |

➥📱Deploy on Termux

31 |

➥🎲Deploy on Scalingo

32 |

🪪 Service Accounts

33 |

➥🛠️ Create Service Accounts

34 |

➥🌐 Adding in Google Group

35 |

⛑Contact Us!

36 |

❤️Credits & Thanks

37 |

🍵Other Projects

38 | 39 |

🆕 What's New!

40 |

1.Gclone upgraded to v1.59.1 (latest)!😉

41 |

2.UI Changes!🌟

42 |

3.CloneBot V2 is now comfortable with Python 3.10.6🐍.

43 |

4.Resolved $PORT listening Errors in Okteto and other platforms.⚙️

44 |

5.Old Docker Image ghcr.io/thecaduceus/clonebot_v2:main is now no more supported and deprecated!🧹

45 |

6.Lots of other fixes, changes and improvements which can be checked in Changelog.

46 |

Full Changelog: V2.1.4...v2.2.9

47 | 48 |

⛔ NOTICE

49 |

1.You may need account for Fly.io/Clever-Cloud/Okteto/Scalingo while deploying CloneBot V2 on respected platforms.

50 |

2.Service Accounts are mandatory to use CloneBot V2, because it uses Service Accounts to prevent hitting 750GB Upload/Clone limit of Google Drive while cloning large amount of data.

51 |

3.VPS or your local machine (PC or Laptop or Mobile) should have Python 3 and Git installed in order to run CloneBot V2.

52 |

4.CloneBot V2 don't use your bandwidth or Internet connection while cloning data but it can if hosted on your local machine or VPS for calling required Telegram APIs to update the progress or to generate required response.

53 |

5.This Project comes with GNU License, please consider reading it before using this.

54 |

6.Name of zip file should be only accounts.zip and it should only contain .json files not folders!

55 |

7.Don't blame contributors of CloneBot V2 in case your account got suspended while using it by deploying on free services provided below! (We already provided you the details that you should follow to prevent it if you are new to this platforms) on Clever-Cloud add Credit card before deploying your bot on it, only report error which is releated with code of CloneBot V2! we don't accept problems regarding any platform on which you are going to deploy this.

56 |

8.Don't get confused! If you use pip to install requirements.txt then only use py or python for executing commands or in the same way if you use pip3 then only use python3.

57 |

9.Aim of CloneBot V2 is not to violate any platform's TOS and hence we removed deployment support of platforms like Heroku, don't create an issue or PR for adding support of Heroku or platforms which don't allow it or if CloneBot V2 violate their TOS.

58 |

10.PRs for just changing the status message or similar is not accepted! that does not mean that PRs including Typo Errors will be rejected.

59 | 60 |

⚙️ How to use?

61 |

CloneBot V2 is very straight forward and easy to use bot. If you deployed your CloneBot V2 then consider adding commands in it through @BotFather to make it easy for other users to know bot commands, here is the commands list to be set in @BotFather:

62 |

1.First convert accounts folder of your Service Accounts into accounts.zip then send it to bot and write /sa in caption or send /sa as reply to accounts.zip file. Don't have Service Accounts? Learn here how to create

63 |

2.Now Send /folders to your CloneBot V2 and then bot will show Shared Drives name in which you added your Service Accounts's Google Group, select Shared Drive or directory available in it as destination. Not added Service Accounts in Google Group? Learn here how to do.

64 |

3.Your CloneBot V2 is now ready to be used! just send any Google Drive sharing link and select the Destination folder you set before to clone data in it.

65 |

4.Additionally, /ban and /unban command is to unauthorize or authorize user again and /id command is to get your Telegram User ID.

66 |

⛔NOTE: Each allowed user have to upload their own accounts.zip to use CloneBot V2.

67 |
68 | 69 |
70 |

🫙Making Shared Drive

71 |

CloneBot V2 comes with the ability to clone data between My Drive to Shared Drive or Shared Drive to Shared Drive, but in both case Shared Drive is common & required! So lets see how we can create our own Shared Drive for free to use them with CloneBot V2.

72 |

First visit MsGsuite's Shared Drive Generator Website or you can also use MsGsuite Shared Drive Generator Telegram Bot to create Shared Drive.

73 |

🌐Using Website:

74 |

1.Open Website and provide details stated below:

75 |

Shared Drive Name: Enter Name which you want to give to your Shared Drive. It can be anything but avoid using Emojis to prevent UTF-8 Errors

76 |

Gmail ID: Enter your Google Account's Email ID for which you want to create Shared Drive.

77 |

Domain Selection: Using drop-down list, select a working domain through which you want to create Shared Drive, or if you are not sure then keep it as Random.

78 | 79 |

2.Once done! Solve hcaptcha to prove that you are human and then click CREATE.

80 |

3.After creating, add Google Group of your Service Accounts in that Shared Drive to use it with CloneBot V2. Don't know how to? Learn Here

81 | 82 |

4.All problems or Error codes related with MsGsuite's Website with their solutions are listed here.

83 |

🤖Using Telegram Bot:

84 |

1.Open MsGsuite's Telegram Bot on Telegram and send /start, then click CREATE TD.

85 |

2.Now provide your Gmail ID for which you want to create Shared Drive and then give name to your Shared Drive.

86 |

3.After giving required details! Bot will ask you to either select domain randomely or manually! select as per your choice. Finally! You done it.😘

87 | 88 |

⛔NOTE: Shared Drive is a temporary storage! use it carefully and keep backup of your data always with you.

89 |

🐍Python with PIP Installation

90 |

Generally, I seen people, blindly running and ignoring options provided by Setup for installing Python and PIP which is most important thing to make Service Accounts or to run CloneBot V2. People like it are just there to flood out support chat and abuse moderators too! Hence I made this Section to tackle this special disease. Lets name this disease Setup-Blindness😂

91 |

1.Run the Python Setup again and click Customize Installation:

92 | 93 |

2.Now select all options as shown in the image and click Next.

94 | 95 |

3.Again! choose following options and click Install and you done it!

96 | 97 |

4.Above steps solves below Errors:

98 |

'python3' is not recognized as an internal or external command, 99 | operable program or batch file.

100 |

'python' is not recognized as an internal or external command, 101 | operable program or batch file.

102 |

'py' is not recognized as an internal or external command, 103 | operable program or batch file.

104 |

'pip3' is not recognized as an internal or external command, 105 | operable program or batch file.

106 |

'pip' is not recognized as an internal or external command, 107 | operable program or batch file.

108 |

⛔NOTE: One dose is sufficient to cure this! Don't take it personally.😂

109 |

🕹️Deployment

110 |

Deployment of CloneBot V2 is as simple as its usage! Their are many methods listed below to deploy CloneBot easily, but before you deploy it, you need some values listed below and how to get it:

111 |

112 | path_to_gclone - Path to gclone file, by default it is gclone or change it if you using different one.

113 | telegram_token - Get your bot's Telegram API Token from BotFather.

114 | user_ids - Telegram User IDs of users who can use your CloneBot_V2. Separate them using , and first User ID is Admin.

115 | group_ids - Telegram Group IDs of Groups in which CloneBot can be used otherwise keep it -1. Separate them using ,

116 | gclone_para_override - Keep it blank if you don't know what it is. 117 |

118 |

⛔NOTE: Everything in config.ini should be Int.

119 |

📎Getting CONFIG_FILE_URL

120 |

CONFIG_FILE_URL is URL to config.ini file which contains values of variables discussed above, lets see how to get your CONFIG_FILE_URL easily:

121 |

0.First open sample-config.ini file then copy its code.

122 | 32 123 |

📃Using Dr.Graph:

124 |

1.Open Dr.Graph, enable Code as well as Raw option then paste the variables discussed above!

125 | 126 |

2.You can use Custom URL to make the final output link memorable and then press Save button as shown in the image given above.

127 |

3.It will open the new tab! just press the View Raw button and copy the URL from address bar which you will get after pressing it.

128 | 129 |

🤖Using File Stream Bot

130 |

1.Open File Stream Bot on Telegram and save the above discussed values in config.ini file and send that file to the bot and get permanent working link.

131 | 132 |

2.Your CONFIG_FILE_URL is now ready to be used.

133 |

✏️Using GitHub Gist:

134 |

1.Open GitHub Gist and create a new gist and paste the code you copied above and name it as config.ini and now fill below values as discussed above!

135 | 33 136 |

2.Then press Create Secret Gist then click Raw, it will open a New Tab in your Browser. Just copy the URL of that New Tab

137 | 34 138 | 35 139 |

3.Once you copied the URL! then remove Commit_ID from the URL:

140 |

Before:
141 | https://gist.githubusercontent.com/UserName/0ee24eXXXXXXXXXXXXXXX6b/raw/Commit_ID/config.ini
142 | After:
143 | https://gist.githubusercontent.com/UserName/0ee24eXXXXXXXXXXXXXXX6b/raw/config.ini 144 |

145 | 146 |

🐳Build or Deploy using Docker

147 |

CloneBot V2 can be deployed almost everywhere using Docker, either you can create your own Docker Image using Build Tool provided in the Workflow including Docker-Code. While CloneBot V2 also have ready to use Docker image for systems based on AMD 64.

148 |

1.To pull CloneBot V2 Docker Image:

149 |

->docker pull ghcr.io/thecaduceus/clonebot-v2:main

150 |

2.Or, to use as base Image:

151 |

->FROM ghcr.io/thecaduceus/clonebot-v2:main

152 |

3.Old Docker Image ghcr.io/thecaduceus/clonebot_v2:main is now no more supported and deprecated!

153 |

4.Want to build own docker image? alright! here is the guide.

154 |

⛔NOTE:

155 |

1.Docker Image only accepts CONFIG_FILE_URL

156 |

2.Use your own Docker Image for deploying on VPS only! Using it for deploying on platforms like Heroku, Okteto or Scalingo will simply cause Account suspension.

157 |

🕊️Deploy on Fly

158 |

Fly.io is platform and best alternative of Heroku (Salesforce) becuase here you can deploy your apps by just adding Credit Card (without being charged) or anyother payment methods, unlike Heroku, they offers you 2,340 running hours per month while Heroku only provides 550 running hours (dyno hours) to run your app! that means you don't have to worry about suddenly getting your app stopped like in the case of Heroku. Fly.io also not restarts your app each 24 hours which enables you to clone bigger data easily.

159 |

1.Create an account on Fly.io.

160 | 161 |

2.Install flyctl on your system.

162 |

MacOS / Linux:

163 |

curl -L https://fly.io/install.sh | sh

164 |

Using Brew:

165 |

brew install flyctl

166 |

Windows Powershell:

167 |

iwr https://fly.io/install.ps1 -useb | iex

168 |

Termux: (Refer #54)

169 |

pkg install flyctl

170 |

3.Download CloneBot_V2 Repository:

171 |

git clone https://github.com/TheCaduceus/CloneBot_V2

172 |

4.Now run following commands:

173 |

174 | cd CloneBot_V2 - To change directory.
175 | fly auth login - To login on Fly.io.
176 | fly launch - To configure basic things, like app name and data center as well as creating fly.toml. 177 |

178 |

5.Configure App:

179 |

1.For app name keep the field empty (Hit Enter), and for choosing data center! use arrow keys to select one. For attaching Postgres Database enter 180 | N including for Deploy Now.

181 | 182 |

2.Once you run the above command! it will automatically create fly.toml file, open the fly.toml file with any text editor and under [env] section put your CONFIG_FILE_URL which you created above!

183 | 184 |

3.Everything done! now run the final deploy command to deploy your app.

185 |

fly deploy - To deploy your app.

186 |

⛔NOTICE: You can use flyctl instead of fly.

187 |

🧿Using GitHub Actions

188 |

CloneBot V2 can also be deployed on Fly.io using GitHub Actions, this method is useful if you don't have PC or you can't download flyctl on Termux due to architecture limitations.

189 |

1.Set following secret in GitHub Secrets:

190 |

FLY_API_TOKEN: Get your Fly API Token from here.

191 |

APP_NAME: Fly App name of your choice

192 |

CONFIG_FILE_URL: CONFIG_FILE_URL created above

193 |

2.Go to Actions Tab and run Deploy to Fly workflow.

194 |

♦️Deploy on Clever Cloud

195 |

Clever Cloud is a Europe-based PaaS (Platform as a Service) company. They help developers deploy and run their apps with bulletproof infrastructure, automatic scaling as well as fair pricing. In my opinion! it is best choice to deploy CloneBot V2 on Clever Cloud because pricing is excellent & fair as well as you can run CloneBot V2 for days to clone large amount of data.

196 |

⛔NOTICE: Before deploying/running CloneBot V2 on Clever Cloud! Don't forget to add payment method like credit card in your account to verify your account otherwise deploying and using CloneBot V2 on Clever Cloud will cause suspension of your app/account.

197 |

1.First log in on Clever Cloud.

198 | 199 |

2.Now click on Create and then select an application from the list.

200 | 201 |

3.Once you reach "Application Creation" page, choose "Create an application from GitHub repository" and select the CloneBot V2 Repository. Not visible? fork this!

202 | 203 |

4.Done? now specify the application type by choosing our beloved Docker.😘

204 | 205 |

5.After that! directly click Next on "How many number of instances?" page and keep the number of instance only 1. Additionally, you can keep instance type to Nano which is most cheap because CloneBot V2 is designed to run on very low end systems.

206 | 207 |

6.Provide your instance a beautiful name, it can be "CloneBot V2" itself, and for instance location, you can choose Paris France for lower ping (tested!😉).

208 | 209 |

7.Now it will navigate to "Add-ons" page, simply click I DON'T NEED ANY ADD-ONS because... you already know it!🌟 still why? it is designed for low end systems.

210 | 211 |

8.Then enter CONFIG_FILE_URL as variable name and the CONFIG_FILE_URL which you just made here! and Clever Cloud will start deploying your instance.

212 | 213 |

9.Finally! to check if CloneBot V2 is working perfectly, you can open the domain (it will display the guide) provided by Clever Cloud for your instance which can be collected from Domain Names tab and for logs you can check Logs tab.

214 | 215 | 216 |

🪬Deploy on Okteto

217 |

Okteto is Kubernetes development platforms and used by many users and it is ideal for lightweight apps and it is perfect for CloneBot V2, Okteto is worst than Heroku, your bot will sleep after 24 hours and will not get back to online until you ping the provided ENDPOINT.

218 |

1.First Create your Okteto Account, You need one GitHub account as okteto supports only one Method to either Create or Login: Create/Login on Okteto

219 | 38 220 |

2.Now fork this repository, and go to Okteto Dashboard then press "Launch Dev Environment".

221 | 39 222 |

3.After it, select your forked repository and select branch main and add following value carefully:

223 |

224 | CONFIG_FILE_URL - Enter CONFIG_FILE_URL, which you just made here.
225 |

226 | 40 227 |

4.Once done! press "Launch" and you successfully done it! Yes 😊

228 |

5.Okteto make your deployed app to sleep if provided ENDPOINT (Allotted URL) remain untouched for 24 Hours. So lets setup a simple cron-job to keep your app active.

229 |

6.First copy your app's ENDPOINT as shown in the image and go to Cron-Job.org and sign up!

230 | 41 231 | 42 232 |

7.Done? Nice! now click "CREATE CRONJOB" button and provide your copied ENDPOINT URL that you just copied and change execution schedule to every 5 minutes.Finally! click "CREATE" and you done it! 😌 Relax and use CloneBot V2 freely.

233 | 43 234 |

⛔NOTE: Don't forget to setup Cron-Job for Okteto otherwise your deployed bot will go into sleep and you have to active it from Okteto Dashboard, while Cron-Job doing it on your behalf.

235 | 236 |

🖥️ Deploy on VPS or PC

237 |

Running CloneBot V2 on your PC or VPS is very simple and takes very less efforts! It have very less load on your System and don't use your bandwidth or Internet connection for cloning Google Drive data but only for calling Telegram APIs to update the progress or to generate required response.

238 |

1.Download Requirements:

239 |

240 | ->Python 3 or above with pip
241 | ->Git 242 |

243 |

2.Download Repository:

244 |

245 | ->git clone https://github.com/TheCaduceus/CloneBot_V2
246 | ->Or Download from Here 247 |

248 |

3.Install CloneBot_V2 Requirements:

249 |

250 | ->cd CloneBot_V2
251 | ->pip install -r requirements.txt 252 |

253 |

4.Download Gclone:

254 |

255 | ->Go to Gclone Library and download Gclone file as per your Operating System and place it in "telegram_gcloner" folder.
256 | ->Website provides direct download link, so you can also use Command-line to download Gclone.
257 | Linux:
258 | ->curl download_link_here >> telegram_gcloner/gclone
259 | Windows:
260 | ->curl download_link_here >> telegram_gcloner/gclone.exe 261 |

262 |

5.Edit Config.ini file

263 |

264 | ->Open Config.ini file in any text editor and enter the values of variables as written here
265 |
Or you can download your Config.ini file from external source using CONFIG_FILE_URL by using Command-line:
266 | ->curl CONFIG_FILE_URL >> telegram_gcloner/config.ini 267 |

268 |

6.Start CloneBot V2:

269 |

270 | ->cd CloneBot_V2
271 | ->python telegram_gcloner/telegram_gcloner.py 272 |

273 |

7.Stop CloneBot V2:

274 |

275 | ->Press CTRL + C keys 276 |

277 | 278 |

📱Deploy on Termux

279 |

Termux is a best app for running and using Command-line tools on Mobile, CloneBot can also be deploy on your Mobile using Termux itself, don't worry because CloneBot V2 is very lightweight and designed to be deployed even on low-end systems and thus it will not cause heavy load on your Mobile.

280 |

1.Download Termux app: Download Here

281 |

2.Choose specific code from here based on architecture of your phone.

282 |

3.Run the code you got from above and follow on-screen instructions.

283 |

🎲Deploy on Scalingo

284 |

CloneBot V2 is also deployable to Scalingo cloud, Just deploy Scalingo Branch.

285 |

Switch to Scalingo Branch for guide.

286 | 287 |

🪪 Service Accounts

288 |

Service Accounts are just like normal Google Account and thus have same Upload or Download limits as Google Account which is 750GB Upload and 10TB Download. They are used to act on behalf of a Google Account and hence we can use them to prevent hitting Google Drive limits by creating them in a bulk amount. After creating Service Accounts, we have to add them in Google Group so that we can directly add Google Group's Email ID in Shared Drive at place of adding each Service Accounts manually.

289 |

🛠️ Create Service Accounts

290 |

1.First go to Google Cloud Console and select "Create or select a project" then click "CREATE PROJECT" as shown in the image.

291 | 1 292 | 2 293 |

2.Now give your Project Name, for location select "No organization" and click "CREATE".

294 | 3 295 |

3.Once your project is created! then click "SELECT PROJECT". Now click on hamburger menu and hover the cursor on "APIs and services" after which a small drop-down menu list is visible, select "Enabled APIs and services"

296 | 4 297 | 5 298 |

4.After it, Click "ENABLE APIS AND SERVICES" button and search for "Google Drive API" in the Search bar as shown in the image.

299 | 6 300 | 7 301 |

5.Open "Google Drive API" and click on "ENABLE" button to enable it for your Project.

302 | 8 303 |

6.Once Enabled, Click on "OAuth consent screen" then select "External" as "User Type" and click "CREATE" button.

304 | 9 305 | 10 306 |

7.It will now open "Edit app registration" screen, provide App Name, Support Email and Developer Email ID (Same as Support Email ID) and then click "SAVE AND CONTINUE" button.

307 | 11 308 |

8.Now it will ask you to "ADD OR REMOVE SCOPES", just ignore this and directly click "SAVE AND CONTINUE" button. Then it will ask you to "ADD USERS" again ignore it and directly press "SAVE AND CONTINUE"

309 | 12 310 | 13 311 |

9.At summary page, press "BACK TO DASHBOARD" and click "PUBLISH APP".

312 | 14 313 | 15 314 |

10.After publishing, Select "Credentials" and click "CREATE CREDENTIALS", from drop down list select "OAuth Client ID".

315 | 16 316 | 17 317 |

11.Choose Application type as "Desktop app" and press "CREATE" button. Now create a Folder on your computer with name like "My Service Accounts", and then from pop-up click "DOWNLOAD JSON". Download the json file as credentials.json in the folder you just created.

318 |

⛔NOTE: Download json file as credentials.json only!

319 | 18 320 | 19 321 |

12.Once installed, now download some required python scripts from here and extract it. Then move gen_sa_accounts.py rename_script.py as well as requirements.txt files to folder in which you downloaded credentials.json.

322 | 20 323 |

13.Before we proceed further, please confirm you have installed Python (with pip) carefully. Not downloaded yet? Download Now!

324 |

14.All Ready? Type "cmd" in the address bar of folder which you created in STEP 11 and hit ENTER or as an alternative of this, you can use cd command like cd FOLDER_PATH in CMD.

325 | 23 326 |

15.Now run following commands carefully in CMD one-by-one:

327 | 328 |

329 | 1. pip install -U -r requirements.txt - To install requirements.
330 | 2. py gen_sa_accounts.py - To get login URL. 331 |

332 |

16.Running command 2 will give you a Login URL, just copy & paste it in your URL and login using your Google Account and provide all asked permission.

333 |

⛔NOTE: Login only with Google account which you used to create Project on Google Cloud Console.

334 | 21 335 | 22 336 |

17.Back to CMD screen, run following commands carefully one-by-one:

337 | 338 |

339 | 3. py gen_sa_accounts.py --list-projects - To get the ID of your created Project.
340 | 4. py gen_sa_accounts.py --enable-services PROJECT_ID - To Enable Services in given project.
341 | 5. py gen_sa_accounts.py --create-sas PROJECT_ID - To create Service Accounts.
342 | 6. py gen_sa_accounts.py --download-keys PROJECT_ID - To download Service Accounts file.
343 | 7. py rename_script.py - To rename Service Accounts file in 1-100 sequence. 344 |

345 |

⛔NOTE: Replace PROJECT_ID with Project ID which you will get from command 3 and if commands not working then replace py with python or python3.

346 |

18.Till now, We have created 100 Service Accounts but we have to do some more work before we take them in our use. Open folder which you created in STEP 11 and you will see accounts folder in it which have your 100 Service Accounts file (json files), now type "Powershell" in address bar of accounts folder or as an alternative you can use cd commands like cd FOLDER_PATH in Powershell.

347 | 24 348 |

19.Done? Now run following command:

349 |

MacOS / Linux:

350 |

351 | grep -oPh '"client_email": "\K[^"]+' *.json > emails.txt 352 |

353 |

Windows:

354 |

355 | $emails = Get-ChildItem .\**.json |Get-Content -Raw |ConvertFrom-Json |Select -ExpandProperty client_email >>emails.txt 356 |

357 |

20.Above command collects the EMAIL-ID of all your Service Accounts available in accounts folder into emails.txt file. Move emails.txt file from accounts folder to prevent confusion or any other problem.

358 |

🌐 Adding in Google Group

359 |

21.Last work! we have to add them in a Google Group and have to add that Google Group in a Shared Drive to give read + write permission to all Service Accounts at once. Go to Google Groups and press "Create group" button to create a group.

360 | 25 361 |

22.In pop-up, fill up details of your Google Group like Name and Email ID as shown in the image then press "Next". After it, let privacy settings as it is and again click "Next"

362 | 26 363 | 27 364 |

23.Once done, it will ask you to "Add Members" in your Group as shown in the image,just ignore it and directly press "Create Group". Now open your Google Group and select "Members" from sidebar and click "Add Members"

365 | 28 366 | 29 367 |

24.In the pop-up shown, enable "Directly add members" and open emails.txt file which you got from STEP 19 then copy & paste 10 Email IDs in the field named "Group Managers". In this way! add all 100 Email IDs in your Google Group but only 10 Email IDs at once.

368 | 30 369 |

25.After adding all Email IDs of your Service Accounts, now copy the Email ID of your Google Group which looks like XXXXX@googlegroups.com and add it in your Shared Drives as "Manager".

370 | 31 371 |

26.Finally! We have created 100 Service Accounts and also added them in Google Group. Each Service Account have 750 GB Upload/Clone limit and 10 TB Download limit that means now we can upload/clone 75 TB and can download 100 TB a day.

372 |

⛑Contact Us!

373 |

Join my Update Channel on Telegram: Join Now!

374 |

Special Torrent Group on Telegram: Dr.Torrent

375 |

Directly Contact the Developer using Telegram @HelpAutomatted_Bot

376 |

❤️Credits & Thanks

377 |

🔥CloneBot V2:

378 |

Dr.Caduceus: For making this Project and Guide.

379 |

Levi: For Gclone and upgrading it.

380 |

⚡CloneBot:

381 |

382 | wrenfairbank: For the original python script.
383 | smartass08: To adapt the scrip to heroku.
384 | anymeofu: For making the Direct Heroku deployable Version.
385 | Zero-The-Kamisama: To making MsGsuite discover this amazing bot and the detailed instructions.
386 | zorgof: For the termux script.
387 | Aishik Tokdar: For Adding Guide to Deploy on Railway.app , Qovery , Clever Cloud , Scalingo and some other Code Improvements.Also Added Heroku Workflow Deployment Method.
388 | Katarina: For adding the ability to be deployed to Clever Cloud and Scalingo.
389 | Miss Emily: For adding Support of Okteto Cloud Deployment as well as improving little layout. 390 |

391 | 392 | ## 🍵Other Projects 393 | - **Dr.Graph: Online Anonymous Text / Pasting platform without limits.** 394 | - **Dr.FileStreamBot: Get Download / Stream links for Telegram files and use as host.** 395 | 396 | -------------------------------------------------------------------------------- /Termux-Guide.md: -------------------------------------------------------------------------------- 1 | ## ARM v6: 2 | ``` 3 | termux-setup-storage && pkg update && pkg install git && pkg install python && pkg install wget && pkg upgrade && pip install --upgrade pip && mkdir /sdcard/MyTermuxCloneBot_V2/ -p && mkdir /sdcard/MyTermuxCloneBot_V2/gclone/ -p && cd /sdcard/MyTermuxCloneBot_V2/ && git clone https://github.com/TheCaduceus/CloneBot_V2 && cd CloneBot_V2 && pip install -r requirements.txt && cd /sdcard/MyTermuxCloneBot_V2/gclone/ && wget -O gclone.gz https://github.com/donwa/gclone/releases/download/v1.51.0-mod1.3.1/gclone_1.51.0-mod1.3.1_Linux_armv6.gz && gzip -d -f gclone.gz && git clone https://github.com/roshanconnor123/gclone_android && mv gclone /data/data/com.termux/files/usr/bin/ && chmod 777 /data/data/com.termux/files/usr/bin/gclone && mv gclone_android/gc.py /sdcard/MyTermuxCloneBot_V2/gclone/ && gclone version && cd /sdcard/MyTermuxCloneBot_V2/ && echo "" && echo "now you will see text at top like rclone v1.51.0-mod1.3.1 - os/arch: linux/arm64 - go version: go1.13.8. if you see this, than go ahead!" && echo "" && echo "if you dont see this, gclone install is failed. take screenshot and send t.me/msgsuitechat." && echo "" && echo "now edit your config.ini file. you can find it from /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/config.ini." && echo "" && echo "when your edit finish, then come termux, type following 2 commands to start your bot:" && echo "" && echo "cd /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/" && echo "" && echo "python telegram_gcloner.py" && echo "" && echo "if you want to stop bot, then do ctrl+c double time. if you exited from terminal and have a new terminal," && echo "" && echo "then type pkill -9 -f telegram_gcloner.py" && echo "" && echo "you can check what is running with: ps -ef. dont try to kill other things. they are not related with bot." && echo "" && echo "install completed. written by @TheCaduceus for CloneBot_V2" 4 | ``` 5 | ## ARM 64: 6 | ``` 7 | termux-setup-storage && pkg update && pkg install git && pkg install python && pkg install wget && pkg upgrade && pip install --upgrade pip && mkdir /sdcard/MyTermuxCloneBot_V2/ -p && mkdir /sdcard/MyTermuxCloneBot_V2/gclone/ -p && cd /sdcard/MyTermuxCloneBot_V2/ && git clone https://github.com/TheCaduceus/CloneBot_V2 && cd CloneBot_V2 && pip install -r requirements.txt && cd /sdcard/MyTermuxCloneBot_V2/gclone/ && wget -O gclone.gz https://github.com/donwa/gclone/releases/download/v1.51.0-mod1.3.1/gclone_1.51.0-mod1.3.1_Linux_arm64.gz && gzip -d -f gclone.gz && git clone https://github.com/roshanconnor123/gclone_android && mv gclone /data/data/com.termux/files/usr/bin/ && chmod 777 /data/data/com.termux/files/usr/bin/gclone && mv gclone_android/gc.py /sdcard/MyTermuxCloneBot_V2/gclone/ && gclone version && cd /sdcard/MyTermuxCloneBot_V2/ && echo "" && echo "now you will see text at top like rclone v1.51.0-mod1.3.1 - os/arch: linux/arm64 - go version: go1.13.8. if you see this, than go ahead!" && echo "" && echo "if you dont see this, gclone install is failed. take screenshot and send t.me/msgsuitechat." && echo "" && echo "now edit your config.ini file. you can find it from /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/config.ini." && echo "" && echo "when your edit finish, then come termux, type following 2 commands to start your bot:" && echo "" && echo "cd /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/" && echo "" && echo "python telegram_gcloner.py" && echo "" && echo "if you want to stop bot, then do ctrl+c double time. if you exited from terminal and have a new terminal," && echo "" && echo "then type pkill -9 -f telegram_gcloner.py" && echo "" && echo "you can check what is running with: ps -ef. dont try to kill other things. they are not related with bot." && echo "" && echo "install completed. written by @TheCaduceus for CloneBot_V2" 8 | ``` 9 | ## x08_64: 10 | ``` 11 | termux-setup-storage && pkg update && pkg install git && pkg install python && pkg install wget && pkg upgrade && pip install --upgrade pip && mkdir /sdcard/MyTermuxCloneBot_V2/ -p && mkdir /sdcard/MyTermuxCloneBot_V2/gclone/ -p && cd /sdcard/MyTermuxCloneBot_V2/ && git clone https://github.com/TheCaduceus/CloneBot_V2 && cd CloneBot_V2 && pip install -r requirements.txt && cd /sdcard/MyTermuxCloneBot_V2/gclone/ && wget -O gclone.gz https://github.com/donwa/gclone/releases/download/v1.51.0-mod1.3.1/gclone_1.51.0-mod1.3.1_Linux_x86_64.gz && gzip -d -f gclone.gz && git clone https://github.com/roshanconnor123/gclone_android && mv gclone /data/data/com.termux/files/usr/bin/ && chmod 777 /data/data/com.termux/files/usr/bin/gclone && mv gclone_android/gc.py /sdcard/MyTermuxCloneBot_V2/gclone/ && gclone version && cd /sdcard/MyTermuxCloneBot_V2/ && echo "" && echo "now you will see text at top like rclone v1.51.0-mod1.3.1 - os/arch: linux/arm64 - go version: go1.13.8. if you see this, than go ahead!" && echo "" && echo "if you dont see this, gclone install is failed. take screenshot and send t.me/msgsuitechat." && echo "" && echo "now edit your config.ini file. you can find it from /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/config.ini." && echo "" && echo "when your edit finish, then come termux, type following 2 commands to start your bot:" && echo "" && echo "cd /sdcard/MyTermuxCloneBot_V2/CloneBot_V2/telegram_gcloner/" && echo "" && echo "python telegram_gcloner.py" && echo "" && echo "if you want to stop bot, then do ctrl+c double time. if you exited from terminal and have a new terminal," && echo "" && echo "then type pkill -9 -f telegram_gcloner.py" && echo "" && echo "you can check what is running with: ps -ef. dont try to kill other things. they are not related with bot." && echo "" && echo "install completed. written by @zorgof for @msgsuitechat" 12 | ``` 13 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | # Site config 2 | theme: jekyll-theme-cayman 3 | -------------------------------------------------------------------------------- /captain-definition: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 2, 3 | "dockerfilePath": "./Dockerfile" 4 | } 5 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | clonebot: 5 | image: ghcr.io/thecaduceus/cbv2:main 6 | container_name: clonebot 7 | environment: 8 | - CONFIG_FILE_URL=${CONFIG_FILE_URL} 9 | ports: 10 | - 8080:8080 11 | restart: unless-stopped 12 | -------------------------------------------------------------------------------- /fly.toml: -------------------------------------------------------------------------------- 1 | # Set app name below, replace APP-NAME 2 | app = "APP-NAME" 3 | kill_signal = "SIGINT" 4 | kill_timeout = 5 5 | processes = [] 6 | 7 | [env] 8 | CONFIG_FILE_URL = "URL_HERE" 9 | 10 | # No need to touch below 11 | 12 | [experimental] 13 | allowed_public_ports = [] 14 | auto_rollback = true 15 | cmd = [] 16 | entrypoint = [] 17 | exec = [] 18 | 19 | [[services]] 20 | http_checks = [] 21 | internal_port = 8080 22 | processes = ["app"] 23 | protocol = "tcp" 24 | script_checks = [] 25 | [services.concurrency] 26 | hard_limit = 25 27 | soft_limit = 20 28 | type = "connections" 29 | 30 | [[services.ports]] 31 | force_https = true 32 | handlers = ["http"] 33 | port = 80 34 | 35 | [[services.ports]] 36 | handlers = ["tls", "http"] 37 | port = 443 38 | 39 | [[services.tcp_checks]] 40 | grace_period = "1s" 41 | interval = "15s" 42 | restart_limit = 0 43 | timeout = "2s" 44 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | google-api-python-client 2 | python-telegram-bot 3 | requests 4 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | rm telegram_gcloner/config.ini 2 | curl $CONFIG_FILE_URL >> telegram_gcloner/config.ini 3 | npm install http-server -g 4 | http-server -p 8080 & 5 | python3 telegram_gcloner/telegram_gcloner.py 6 | -------------------------------------------------------------------------------- /sample-config.ini: -------------------------------------------------------------------------------- 1 | [General] 2 | path_to_gclone = gclone 3 | 4 | telegram_token = 5 | user_ids = 6 | group_ids = -1 7 | 8 | gclone_para_override = 9 | -------------------------------------------------------------------------------- /telegram_gcloner/config.ini: -------------------------------------------------------------------------------- 1 | [General] 2 | path_to_gclone = gclone 3 | 4 | telegram_token = 5 | user_ids = -1 6 | group_ids = -1 7 | 8 | gclone_para_override = 9 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/add_group.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import html 4 | import logging 5 | 6 | from telegram import ParseMode 7 | from telegram.ext import Dispatcher, MessageHandler, Filters 8 | from telegram.utils.helpers import mention_html 9 | 10 | from utils.config_loader import config 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def init(dispatcher: Dispatcher): 16 | """Provide handlers initialization.""" 17 | dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, add_group)) 18 | 19 | 20 | def add_group(update, context): 21 | message = 'joined: {} {}'.format(mention_html(update.message.new_chat_members[0].id, 22 | html.escape(update.message.new_chat_members[0].full_name)), 23 | update.message.new_chat_members[0].id) 24 | logger.info(message) 25 | context.bot.send_message(chat_id=config.USER_IDS[0], text=message, parse_mode=ParseMode.HTML) 26 | if ( 27 | update.message.chat_id not in config.GROUP_IDS 28 | and update.message.new_chat_members[0].id == context.bot.id 29 | ): 30 | mention_html_from_user = mention_html(update.message.from_user.id, 31 | html.escape(update.message.from_user.full_name)) 32 | context.bot.send_message( 33 | chat_id=update.message.chat_id, 34 | text=f'『{mention_html_from_user}』Thank you for adding CloneBot V2. {config.AD_STRING.format(context.bot.username)}', 35 | parse_mode=ParseMode.HTML, 36 | ) 37 | 38 | context.bot.send_message(chat_id=update.message.chat_id, text='I am not allowed to be here 😔. \n So I am leaving this group. \n Ask my owner to allow me in this group.') 39 | message = f'🔙 Left Unauthorized Group : \n │ Name : {update.message.chat.title} ({update.message.chat_id}). \n │ Bot Added by{mention_html_from_user} {update.message.from_user.id}. \n │ Message : {update.message.text}' 40 | 41 | context.bot.leave_chat(update.message.chat_id) 42 | logger.warning(message) 43 | context.bot.send_message(chat_id=config.USER_IDS[0], text=message, parse_mode=ParseMode.HTML) 44 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/ban.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import copy 4 | import logging 5 | 6 | from telegram import Update 7 | from telegram.ext import Dispatcher, CommandHandler, CallbackContext, Filters 8 | 9 | from utils.config_loader import config 10 | from utils.fire_save_files import thread_pool 11 | from utils.restricted import restricted_admin 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | def init(dispatcher: Dispatcher): 17 | """Provide handlers initialization.""" 18 | dispatcher.add_handler(CommandHandler('ban', ban, filters=Filters.chat(config.USER_IDS[0]), pass_args=True)) 19 | dispatcher.add_handler(CommandHandler('unban', unban, filters=Filters.chat(config.USER_IDS[0]), pass_args=True)) 20 | 21 | 22 | @restricted_admin 23 | def ban(update: Update, context: CallbackContext): 24 | if not context.args: 25 | if ban_list := context.bot_data.get('ban', None): 26 | update.message.reply_text('\n'.join(map(str, ban_list))) 27 | return 28 | if not context.args[0].isdigit: 29 | update.message.reply_text('/ban user_id') 30 | return 31 | user_id = int(context.args[0]) 32 | if not context.bot_data.get('ban', None): 33 | context.bot_data['ban'] = [user_id] 34 | elif user_id not in context.bot_data['ban']: 35 | new_ban = copy.deepcopy(context.bot_data['ban']) 36 | new_ban.append(user_id) 37 | context.bot_data['ban'] = new_ban 38 | else: 39 | update.message.reply_text('✔️ User Already banned.') 40 | return 41 | context.dispatcher.update_persistence() 42 | if tasks := thread_pool.get(user_id, None): 43 | for t in tasks: 44 | t.kill() 45 | logger.debug(f'Task {t.ident} was stopped due to user {user_id} is banned.') 46 | break 47 | update.message.reply_text('✅ User successfully banned!') 48 | logger.info(f'{user_id} is banned.') 49 | return 50 | 51 | 52 | @restricted_admin 53 | def unban(update: Update, context: CallbackContext): 54 | if not context.args or not context.args[0].isdigit: 55 | update.message.reply_text('/unban user_id') 56 | return 57 | user_id = int(context.args[0]) 58 | if user_id in context.bot_data.get('ban', []): 59 | new_ban = copy.deepcopy(context.bot_data['ban']) 60 | new_ban.remove(user_id) 61 | context.bot_data['ban'] = new_ban 62 | context.dispatcher.update_persistence() 63 | update.message.reply_text('✅ User successfully removed from banned users list') 64 | logger.info(f'{user_id} is unbanned.') 65 | else: 66 | update.message.reply_text('✖️ User is not banned before.') 67 | 68 | return 69 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/cancel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import Dispatcher, CallbackQueryHandler 6 | 7 | from utils.helper import alert_users 8 | from utils.restricted import restricted 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | def init(dispatcher: Dispatcher): 14 | """Provide handlers initialization.""" 15 | dispatcher.add_handler(CallbackQueryHandler(cancel, pattern=r'^cancel$')) 16 | 17 | 18 | @restricted 19 | def cancel(update, context): 20 | query = update.callback_query 21 | if query.message.chat_id < 0 and \ 22 | (not query.message.reply_to_message or 23 | query.from_user.id != query.message.reply_to_message.from_user.id): 24 | alert_users(context, update.effective_user, 'invalid caller', query.data) 25 | query.answer(text='Yo-he!', show_alert=True) 26 | return 27 | # query.message.edit_reply_markup(reply_markup=None) 28 | query.message.delete() 29 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/choose_folder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import copy 4 | import html 5 | import logging 6 | import re 7 | 8 | from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ParseMode 9 | from telegram.ext import Dispatcher, CommandHandler, CallbackQueryHandler 10 | 11 | from utils.config_loader import config 12 | from utils.google_drive import GoogleDrive 13 | from utils.helper import alert_users, get_inline_keyboard_pagination_data, simplified_path 14 | from utils.restricted import restricted 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | default_max_folders = 4 19 | default_max_folders_vip = 10 20 | 21 | udkey_folders = 'folder_ids' 22 | udkey_folders_cache = 'folder_ids_cache' 23 | udkey_fav_folders_replace = 'favourite_folder_ids_replace' 24 | 25 | 26 | def init(dispatcher: Dispatcher): 27 | """Provide handlers initialization.""" 28 | dispatcher.add_handler( 29 | CallbackQueryHandler(choose_folder, 30 | pattern=r'^(?:un)?choose_folder(?:_replace)?(?:_page#\d+)?(?:\,[\dA-Za-z\-_]+)?$')) 31 | dispatcher.add_handler(CallbackQueryHandler(chosen_folder, 32 | pattern=r'^chosen_folder\,[\dA-Za-z\-_]+$')) 33 | dispatcher.add_handler(CommandHandler('folders', set_folders)) 34 | dispatcher.add_handler(CallbackQueryHandler(set_folders, 35 | pattern=r'^(?:un)?set_folders(:?_page#\d+)?(?:\,[\dA-Za-z\-_]+)?$')) 36 | 37 | 38 | @restricted 39 | def chosen_folder(update, context): 40 | query = update.callback_query 41 | if query.message.chat_id < 0 and \ 42 | (not query.message.reply_to_message or 43 | query.from_user.id != query.message.reply_to_message.from_user.id): 44 | alert_users(context, update.effective_user, 'invalid caller', query.data) 45 | query.answer(text='Yo-he!', show_alert=True) 46 | return 47 | if update.effective_user.id in config.USER_IDS\ 48 | or (context.bot_data.get('vip', None) and update.effective_user.id in context.bot_data['vip']): 49 | max_folders = default_max_folders_vip 50 | else: 51 | max_folders = default_max_folders 52 | 53 | callback_query_prefix = 'chosen_folder' 54 | 55 | try: 56 | gd = GoogleDrive(update.effective_user.id) 57 | except Exception as e: 58 | context.bot.send_message( 59 | chat_id=update.effective_user.id, 60 | text=f'🔸 Please make sure the SA archive has been uploaded followed by /sa and the Destination Favourite Folder has been configured. 🔸\n{html.escape(str(e))}', 61 | parse_mode=ParseMode.HTML, 62 | ) 63 | 64 | return 65 | 66 | query = update.callback_query 67 | match = re.search( 68 | f'^{callback_query_prefix},(?P[\dA-Za-z\-_]+)$', query.data 69 | ) 70 | 71 | if not match: 72 | alert_users(context, update.effective_user, 'invalid query', query.data) 73 | query.answer(text='Yo-he!', show_alert=True) 74 | return 75 | folder_id = match['folder_id'] 76 | 77 | drive_ids_replace = context.user_data.get(udkey_fav_folders_replace, None) 78 | favourite_drive_ids = context.user_data.get(udkey_folders, {}) 79 | new_fav_folders = copy.deepcopy(favourite_drive_ids) 80 | new_fav_folders.pop(drive_ids_replace, None) 81 | new_fav_folders_len = len(new_fav_folders) 82 | if new_fav_folders_len < max_folders: 83 | current_path_list = gd.get_file_path_from_id(folder_id) 84 | if not current_path_list: 85 | alert_users(context, update.effective_user, 'invalid folder id', query.data) 86 | query.answer(text='Yo-he!', show_alert=True) 87 | return 88 | current_path_list.reverse() 89 | new_fav_folders[folder_id] = { 90 | 'name': current_path_list[-1]['name'], 91 | 'path': '/' + '/'.join(item['name'] for item in current_path_list), 92 | } 93 | context.user_data[udkey_folders] = new_fav_folders 94 | context.user_data[udkey_fav_folders_replace] = None 95 | context.dispatcher.update_persistence() 96 | set_folders(update, context) 97 | else: 98 | query.answer(text=f'Maximum {max_folders}', show_alert=True) 99 | return 100 | 101 | 102 | @restricted 103 | def choose_folder(update, context): 104 | current_folder_id = '' 105 | folders = None 106 | 107 | try: 108 | gd = GoogleDrive(update.effective_user.id) 109 | except Exception as e: 110 | context.bot.send_message(chat_id=update.effective_user.id, 111 | text='🔸 Please make sure the SA archive has been uploaded followed by /sa and the Destination Favourite Folder has been configured. 🔸\n' 112 | '{}'.format(html.escape(str(e))), 113 | parse_mode=ParseMode.HTML) 114 | return 115 | 116 | if context.args: 117 | current_folder_id = context.args[0] 118 | try: 119 | gd.get_file_name(current_folder_id) 120 | folders = gd.list_folders(current_folder_id) 121 | except Exception as e: 122 | folders = gd.get_drives() 123 | current_folder_id = '' 124 | context.bot.send_message(chat_id=update.effective_user.id, 125 | text='Error:\n{}'.format(html.escape(str(e))), 126 | parse_mode=ParseMode.HTML) 127 | 128 | callback_query_prefix = 'choose_folder' 129 | query = update.callback_query 130 | page = None 131 | message_id = -1 132 | if not query: 133 | rsp = update.message.reply_text('⚙️ Getting Directory ⚙️') 134 | rsp.done.wait(timeout=60) 135 | message_id = rsp.result().message_id 136 | if not folders: 137 | folders = gd.get_drives() 138 | context.user_data[udkey_folders_cache] = copy.deepcopy(folders) 139 | 140 | if query: 141 | logger.debug('{}: {}'.format(update.effective_user.id, query.data)) 142 | if query.message.chat_id < 0 and \ 143 | (not query.message.reply_to_message or 144 | query.from_user.id != query.message.reply_to_message.from_user.id): 145 | alert_users(context, update.effective_user, 'invalid caller', query.data) 146 | query.answer(text='Yo-he!', show_alert=True) 147 | return 148 | message_id = query.message.message_id 149 | match = re.search(r'^(?Pun)?{}(?P_replace)?(?:_page#(?P\d+))?' 150 | r'(?:,(?P[\dA-Za-z\-_]+))?$'.format(callback_query_prefix), 151 | query.data) 152 | if match: 153 | match_folder_id = match.group('folder_id') 154 | if match_folder_id: 155 | current_folder_id = match_folder_id 156 | try: 157 | gd.get_file_name(current_folder_id) 158 | folders = gd.list_folders(match_folder_id) 159 | except Exception as e: 160 | folders = gd.get_drives() 161 | current_folder_id = '' 162 | context.bot.send_message(chat_id=update.effective_user.id, 163 | text='⁉️ Error:\n{}'.format(html.escape(str(e))), 164 | parse_mode=ParseMode.HTML) 165 | context.user_data[udkey_folders_cache] = copy.deepcopy(folders) 166 | if not folders: 167 | folders = {'#': '(No subfolders)'} 168 | match_folder_id_replace = match.group('replace') 169 | if match_folder_id_replace: 170 | context.user_data[udkey_fav_folders_replace] = match_folder_id 171 | if match.group('page'): 172 | page = int(match.group('page')) 173 | if not folders and match.group('page'): 174 | folders = context.user_data.get(udkey_folders_cache, None) 175 | if not folders: 176 | folders = gd.get_drives() 177 | context.user_data[udkey_folders_cache] = copy.deepcopy(folders) 178 | if not folders: 179 | folders = {'#': 'I could not find any Shared Drives associated with your Service Accounts. \n If you don`t have no shared drives, go to @MsGsuite to get one for yourself.'} 180 | else: 181 | alert_users(context, update.effective_user, 'invalid query data', query.data) 182 | query.answer(text='Yo-he!', show_alert=True) 183 | return 184 | 185 | if not page: 186 | page = 1 187 | 188 | folders_len = len(folders) 189 | page_data = [] 190 | for item in folders: 191 | page_data.append({'text': folders[item], 'data': item}) 192 | 193 | page_data_chosen = list(context.user_data.get(udkey_folders, {})) 194 | inline_keyboard_drive_ids = get_inline_keyboard_pagination_data( 195 | callback_query_prefix, 196 | page_data, 197 | page_data_chosen=page_data_chosen, 198 | page=page, 199 | max_per_page=10, 200 | ) 201 | 202 | if current_folder_id: 203 | current_path = '' 204 | current_path_list = gd.get_file_path_from_id(current_folder_id) 205 | if current_path_list: 206 | current_folder_name = current_path_list[0]['name'] 207 | for item in current_path_list: 208 | current_path = '/{}{}'.format(item['name'], current_path) 209 | if len(current_path_list) > 1: 210 | inline_keyboard_drive_ids.insert( 211 | 0, [InlineKeyboardButton('📁 ' + current_path, 212 | callback_data='{},{}'.format( 213 | callback_query_prefix, current_path_list[1]['folder_id']))]) 214 | else: 215 | inline_keyboard_drive_ids.insert( 216 | 0, [InlineKeyboardButton('📁' + current_path, 217 | callback_data=callback_query_prefix)]) 218 | inline_keyboard_drive_ids.append( 219 | [InlineKeyboardButton('✔️ Select this folder({})'.format(current_folder_name), 220 | callback_data='chosen_folder,{}'.format(current_folder_id))]) 221 | inline_keyboard_drive_ids.append([InlineKeyboardButton('🔙 Go back', 222 | callback_data='choose_folder' if current_folder_id else '#'), 223 | InlineKeyboardButton('Cancel', callback_data='cancel')]) 224 | context.bot.edit_message_text(chat_id=update.effective_chat.id, 225 | message_id=message_id, 226 | text='🔶 Select the directory you wish to add to Favourite Folders and also want to use for cloning 🔶 \n 🔶🔶 There are {} subdirectories found 🔶🔶'.format( 227 | folders_len), 228 | reply_markup=InlineKeyboardMarkup(inline_keyboard_drive_ids)) 229 | 230 | 231 | @restricted 232 | def set_folders(update, context): 233 | if update.effective_user.id in config.USER_IDS\ 234 | or (context.bot_data.get('vip', None) and update.effective_user.id in context.bot_data['vip']): 235 | max_folders = default_max_folders_vip 236 | else: 237 | max_folders = default_max_folders 238 | 239 | callback_query_prefix = 'choose_folder' 240 | query = update.callback_query 241 | page = 1 242 | if not query: 243 | rsp = update.message.reply_text('⚙️ Getting Favourite Shared Drives ⚙️') 244 | rsp.done.wait(timeout=60) 245 | message_id = rsp.result().message_id 246 | else: 247 | if query.message.chat_id < 0 and \ 248 | (not query.message.reply_to_message or 249 | query.from_user.id != query.message.reply_to_message.from_user.id): 250 | alert_users(context, update.effective_user, 'invalid caller', query.data) 251 | query.answer(text='Yo-he!', show_alert=True) 252 | return 253 | message_id = query.message.message_id 254 | folder_ids = context.user_data.get(udkey_folders, None) 255 | 256 | if folder_ids: 257 | folder_ids_len = len(folder_ids) 258 | page_data = [] 259 | for item in folder_ids: 260 | page_data.append({'text': simplified_path(folder_ids[item]['path']), 'data': '{}'.format(item)}) 261 | inline_keyboard_drive_ids = get_inline_keyboard_pagination_data( 262 | callback_query_prefix + '_replace', 263 | page_data, 264 | page=page, 265 | max_per_page=10, 266 | ) 267 | else: 268 | inline_keyboard_drive_ids = [] 269 | folder_ids_len = 0 270 | if folder_ids_len < max_folders: 271 | inline_keyboard_drive_ids.insert(0, [InlineKeyboardButton('➕ Add Favorite Folder', callback_data=callback_query_prefix)]) 272 | inline_keyboard_drive_ids.append([InlineKeyboardButton('✔️ Done', callback_data='cancel')]) 273 | 274 | context.bot.edit_message_text(chat_id=update.effective_chat.id, 275 | message_id=message_id, 276 | text='📁 Total No of Destination Folders {}/{} 📁:'.format( 277 | folder_ids_len, 278 | max_folders, 279 | ), 280 | reply_markup=InlineKeyboardMarkup(inline_keyboard_drive_ids)) 281 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/contact.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import html 4 | import logging 5 | 6 | from telegram import ParseMode 7 | from telegram.ext import Dispatcher, CommandHandler 8 | from telegram.utils.helpers import mention_html 9 | 10 | from utils.callback import callback_delete_message 11 | from utils.config_loader import config 12 | from utils.restricted import restricted_private 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | def init(dispatcher: Dispatcher): 18 | """Provide handlers initialization.""" 19 | dispatcher.add_handler(CommandHandler('contact', contact, pass_args=True)) 20 | 21 | 22 | @restricted_private 23 | def contact(update, context): 24 | if text := update.message.text.strip('/contact'): 25 | context.bot.send_message( 26 | chat_id=config.USER_IDS[0], 27 | text=f'📬 Received message from {mention_html(update.effective_user.id, html.escape(update.effective_user.name))} ({update.effective_user.id}):', 28 | parse_mode=ParseMode.HTML, 29 | ) 30 | 31 | context.bot.forward_message(chat_id=config.USER_IDS[0], 32 | from_chat_id=update.message.chat_id, 33 | message_id=update.message.message_id) 34 | logger.info( 35 | f'{update.effective_user.name} ({update.effective_user.id}) left a message: {text}' 36 | ) 37 | 38 | rsp = update.message.reply_text('👍 Roger that Master 👍') 39 | else: 40 | rsp = update.message.reply_text('You\'re so shy, don\'t you want to say anything?\n' + 41 | config.AD_STRING.format(context.bot.username), 42 | ParseMode.HTML) 43 | rsp.done.wait(timeout=60) 44 | message_id = rsp.result().message_id 45 | if update.message.chat_id < 0: 46 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 47 | context=(update.message.chat_id, message_id)) 48 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 49 | context=(update.message.chat_id, update.message.message_id)) 50 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/get_help.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import Dispatcher, CommandHandler 6 | 7 | from utils.config_loader import config 8 | from utils.callback import callback_delete_message 9 | from utils.restricted import restricted 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def init(dispatcher: Dispatcher): 15 | """Provide handlers initialization.""" 16 | dispatcher.add_handler(CommandHandler('help', get_help)) 17 | 18 | 19 | @restricted 20 | def get_help(update, context): 21 | message = 'Send a Google Drive link, or forward a message with a Google Drive link to manually transfer.\n' \ 22 | 'Configuration with /sa and /folders is required.\n\n' \ 23 | '📚 Commands:\n' \ 24 | ' │ /start - Start the Bot' \ 25 | ' │ /folders - Set favorite folders\n' \ 26 | ' │ /sa - Private chat only, upload a ZIP containing SA accounts with this command as the subject.\n' \ 27 | ' │ /ban - Ban a Telegram User ID from using the Bot' \ 28 | ' │ /unban - Reallow a Telegram User ID from using the Bot that was earlier banned' \ 29 | ' │ /id - Get your Telegram User ID' \ 30 | ' │ /contact - Get the contacts details of the owner of the Bot' \ 31 | ' │ /help - Output this message\n' 32 | 33 | rsp = update.message.reply_text(message) 34 | rsp.done.wait(timeout=60) 35 | message_id = rsp.result().message_id 36 | if update.message.chat_id < 0: 37 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 38 | context=(update.message.chat_id, message_id)) 39 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 40 | context=(update.message.chat_id, update.message.message_id)) -------------------------------------------------------------------------------- /telegram_gcloner/handlers/get_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import Dispatcher, CommandHandler 6 | 7 | from utils.callback import callback_delete_message 8 | from utils.config_loader import config 9 | from utils.restricted import restricted 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def init(dispatcher: Dispatcher): 15 | """Provide handlers initialization.""" 16 | dispatcher.add_handler(CommandHandler('id', get_id)) 17 | 18 | 19 | @restricted 20 | def get_id(update, context): 21 | logger.info('Telegram User {0} has requested its ID.'.format(update.effective_user.id)) 22 | rsp = update.message.reply_text(update.effective_user.id) 23 | rsp.done.wait(timeout=60) 24 | message_id = rsp.result().message_id 25 | 26 | if update.message.chat_id < 0: 27 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 28 | context=(update.message.chat_id, message_id)) 29 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 30 | context=(update.message.chat_id, update.message.message_id)) 31 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/process_drive_links.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import html 4 | import logging 5 | import re 6 | 7 | from telegram import ParseMode, InlineKeyboardButton, InlineKeyboardMarkup 8 | from telegram.ext import Dispatcher, CallbackQueryHandler 9 | 10 | from utils.fire_save_files import MySaveFileThread, thread_pool 11 | from utils.google_drive import GoogleDrive 12 | from utils.helper import parse_folder_id_from_url, alert_users, get_inline_keyboard_pagination_data, simplified_path 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | udkey_folders = 'folder_ids' 17 | 18 | 19 | def init(dispatcher: Dispatcher): 20 | """Provide handlers initialization.""" 21 | dispatcher.add_handler(CallbackQueryHandler(save_to_folder_page, 22 | pattern=r'^save_to_folder_page#\d+$')) 23 | dispatcher.add_handler(CallbackQueryHandler(save_to_folder, 24 | pattern=r'^save_to_folder(:?_page#\d+)?\,\s*[\dA-Za-z\-_]+$')) 25 | 26 | 27 | def parse_entity_for_drive_id(message): 28 | if message.photo: 29 | entities = message.parse_caption_entities() 30 | else: 31 | entities = message.parse_entities() 32 | 33 | folder_ids = {} 34 | k = 0 35 | 36 | for entity in entities: 37 | if entity.type == 'text_link': 38 | url = entity.url 39 | name = entities[entity] 40 | elif entity.type == 'url': 41 | url = entities[entity] 42 | name = 'file{:03d}'.format(k) 43 | else: 44 | continue 45 | 46 | logger.debug('Found {0}: {1}.'.format(name, url)) 47 | folder_id = parse_folder_id_from_url(url) 48 | if not folder_id: 49 | continue 50 | folder_ids[folder_id] = name 51 | 52 | logger.debug('Found {0} with folder_id {1}.'.format(name, folder_id)) 53 | 54 | if not folder_ids: 55 | logger.debug('Cannot find any legit folder id.') 56 | return None 57 | return folder_ids 58 | 59 | 60 | def process_drive_links(update, context): 61 | if not update.message: 62 | return 63 | 64 | folder_ids = parse_entity_for_drive_id(update.message) 65 | 66 | if not folder_ids: 67 | return 68 | message = '📑 The Following Files were Detected : 📑\n' 69 | 70 | try: 71 | gd = GoogleDrive(update.effective_user.id) 72 | except Exception as e: 73 | update.message.reply_text( 74 | f'🔸 Please make sure the SA archive has been uploaded and the collection folder has been configured. 🔸\n{e}' 75 | ) 76 | 77 | return 78 | 79 | for item in folder_ids: 80 | try: 81 | folder_name = gd.get_file_name(item) 82 | except Exception as e: 83 | update.message.reply_text( 84 | f'🔸 Please make sure that the SA archive has been uplaoded and yuor SA have rights to read files from the Source Link. 🔸\n{e}' 85 | ) 86 | 87 | return 88 | message += f' {html.escape(folder_name)}\n' 89 | 90 | message += '\n📂 Please select the Target Destination 📂' 91 | if fav_folder_ids := context.user_data.get(udkey_folders, None): 92 | page_data = [ 93 | { 94 | 'text': simplified_path(fav_folder_ids[item]['path']), 95 | 'data': f'{item}', 96 | } 97 | for item in fav_folder_ids 98 | ] 99 | 100 | callback_query_prefix = 'save_to_folder' 101 | page = 1 102 | inline_keyboard_drive_ids = get_inline_keyboard_pagination_data( 103 | callback_query_prefix, 104 | page_data, 105 | page=page, 106 | max_per_page=10, 107 | ) 108 | else: 109 | inline_keyboard_drive_ids = [[InlineKeyboardButton(text='⚠️ Use /folders to add a destination to Favourite Folders List ⚠️', callback_data='#')]] 110 | inline_keyboard = inline_keyboard_drive_ids 111 | update.message.reply_text(message, parse_mode=ParseMode.HTML, 112 | disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup(inline_keyboard)) 113 | 114 | 115 | def save_to_folder_page(update, context): 116 | query = update.callback_query 117 | if query.message.chat_id < 0 and \ 118 | (not query.message.reply_to_message or 119 | query.from_user.id != query.message.reply_to_message.from_user.id): 120 | alert_users(context, update.effective_user, 'invalid caller', query.data) 121 | query.answer(text='Yo-he!', show_alert=True) 122 | return 123 | match = re.search(r'^save_to_folder_page#(\d+)$', query.data) 124 | if not match: 125 | alert_users(context, update.effective_user, 'invalid query data', query.data) 126 | query.answer(text='Yo-he!', show_alert=True) 127 | return 128 | page = int(match[1]) 129 | if fav_folder_ids := context.user_data.get(udkey_folders, None): 130 | page_data = [ 131 | { 132 | 'text': simplified_path(fav_folder_ids[item]['path']), 133 | 'data': f'{item}', 134 | } 135 | for item in fav_folder_ids 136 | ] 137 | 138 | callback_query_prefix = 'save_to_folder' 139 | 140 | inline_keyboard_drive_ids = get_inline_keyboard_pagination_data( 141 | callback_query_prefix, 142 | page_data, 143 | page=page, 144 | max_per_page=10, 145 | ) 146 | else: 147 | inline_keyboard_drive_ids = [[InlineKeyboardButton(text='🔹 If you don\'t have any shared drives, you must get one here : @MsGsuite before you can use this.', callback_data='#')]] 148 | inline_keyboard = inline_keyboard_drive_ids 149 | query.message.edit_reply_markup(reply_markup=InlineKeyboardMarkup(inline_keyboard)) 150 | 151 | 152 | def save_to_folder(update, context): 153 | query = update.callback_query 154 | if query.message.chat_id < 0 and \ 155 | (not query.message.reply_to_message or 156 | query.from_user.id != query.message.reply_to_message.from_user.id): 157 | alert_users(context, update.effective_user, 'invalid caller', query.data) 158 | query.answer(text='Yo-he!', show_alert=True) 159 | return 160 | match = re.search(r'^save_to_folder(?:_page#[\d]+)?,\s*([\dA-Za-z\-_]+)$', query.data) 161 | fav_folders = context.user_data.get(udkey_folders, {}) 162 | if not match or match[1] not in fav_folders: 163 | alert_users(context, update.effective_user, 'invalid query', query.data) 164 | query.answer(text='Yo-he!', show_alert=True) 165 | return 166 | message = query.message 167 | text = message.caption or message.text 168 | folder_ids = parse_entity_for_drive_id(message) 169 | 170 | if not folder_ids: 171 | return 172 | dest_folder = fav_folders[match[1]] 173 | dest_folder['folder_id'] = match[1] 174 | if not thread_pool.get(update.effective_user.id, None): 175 | thread_pool[update.effective_user.id] = [] 176 | t = MySaveFileThread(args=(update, context, folder_ids, text, dest_folder)) 177 | thread_pool[update.effective_user.id].append(t) 178 | t.start() 179 | logger.debug(f'User {query.from_user.id} has added task {t.ident}.') 180 | query.message.edit_reply_markup(reply_markup=InlineKeyboardMarkup( 181 | [[InlineKeyboardButton(text='Executed', callback_data='#')]])) 182 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/process_message.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import Dispatcher, MessageHandler, Filters, CallbackQueryHandler 6 | 7 | from handlers.process_drive_links import process_drive_links 8 | from utils.config_loader import config 9 | from utils.helper import parse_folder_id_from_url, alert_users 10 | from utils.process import leave_chat_from_message 11 | from utils.restricted import restricted_admin, restricted 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | def init(dispatcher: Dispatcher): 17 | """Provide handlers initialization.""" 18 | dispatcher.add_handler( 19 | MessageHandler(Filters.chat_type.groups & Filters.chat(config.GROUP_IDS) & 20 | (Filters.text | Filters.caption) & 21 | ~Filters.update.edited_message, 22 | process_message)) 23 | dispatcher.add_handler( 24 | MessageHandler(Filters.chat(config.USER_IDS[0]) & 25 | (Filters.text | Filters.caption) & 26 | ~Filters.update.edited_message, 27 | process_message_from_authorised_user)) 28 | dispatcher.add_handler( 29 | MessageHandler((~Filters.chat_type.groups) & 30 | (Filters.text | Filters.caption) & 31 | ~Filters.update.edited_message, 32 | process_message)) 33 | 34 | dispatcher.add_handler(CallbackQueryHandler(ignore_callback, pattern=r'^#$')) 35 | dispatcher.add_handler(CallbackQueryHandler(get_warning)) 36 | 37 | 38 | def ignore_callback(update, context): 39 | query = update.callback_query 40 | query.answer(text='') 41 | 42 | 43 | def get_warning(update, context): 44 | query = update.callback_query 45 | alert_users(context, update.effective_user, 'unknown query data', query.data) 46 | query.answer(text='Yo-he!', show_alert=True) 47 | 48 | 49 | def leave_from_chat(update, context): 50 | if update.channel_post: 51 | if update.channel_post.chat_id < 0 and update.channel_post.chat_id not in config.GROUP_IDS: 52 | leave_chat_from_message(update.channel_post, context) 53 | return 54 | elif update.message.chat_id < 0 and update.message.chat_id not in config.GROUP_IDS: 55 | leave_chat_from_message(update.message, context) 56 | return 57 | 58 | 59 | @restricted_admin 60 | def process_message_from_authorised_user(update, context): 61 | logger.debug(update.message) 62 | if update.message.caption: 63 | text_urled = update.message.caption_html_urled 64 | else: 65 | text_urled = update.message.text_html_urled 66 | if parse_folder_id_from_url(text_urled): 67 | process_drive_links(update, context) 68 | return 69 | 70 | 71 | @restricted 72 | def process_message(update, context): 73 | if not update.message: 74 | return 75 | if update.message.chat_id != config.USER_IDS[0]: 76 | logger.debug(update.message) 77 | if update.message.caption: 78 | text_urled = update.message.caption_html_urled 79 | else: 80 | text_urled = update.message.text_html_urled 81 | if parse_folder_id_from_url(text_urled): 82 | process_drive_links(update, context) 83 | return 84 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/sa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import configparser 4 | import datetime 5 | import logging 6 | import os 7 | import shutil 8 | import time 9 | from pathlib import Path 10 | from zipfile import ZipFile 11 | 12 | from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters 13 | 14 | from utils.config_loader import config 15 | from utils.restricted import restricted_private 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def init(dispatcher: Dispatcher): 21 | """Provide handlers initialization.""" 22 | dispatcher.add_handler(CommandHandler('sa', get_sa, filters=~Filters.update.edited_message)) 23 | dispatcher.add_handler(MessageHandler(Filters.chat_type.private & Filters.document, get_sa)) 24 | 25 | 26 | @restricted_private 27 | def get_sa(update, context): 28 | instruction_text = 'Please private message a ZIP archive 🗂 containing SA files and write /sa in the subject.\n' \ 29 | '📱 If you are using your phone, upload the ZIP archive first, then reply with /sa' 30 | if update.message and update.message.caption and update.message.caption.startswith('/sa'): 31 | document = update.message.document 32 | elif update.message and update.message.reply_to_message: 33 | document = update.message.reply_to_message.document 34 | else: 35 | update.message.reply_text(instruction_text) 36 | return 37 | 38 | if not document: 39 | update.message.reply_text(instruction_text) 40 | return 41 | gclone_path = os.path.join(config.BASE_PATH, 42 | 'gclone_config', 43 | str(update.effective_user.id)) 44 | current_time = datetime.datetime.now() 45 | file_name = document.file_name 46 | 47 | if not file_name.endswith('zip'): 48 | update.message.reply_text('Only Zip Files are accepted.') 49 | return 50 | 51 | file_pah = os.path.join( 52 | gclone_path, 53 | f'{current_time.strftime("%Y-%m-%d")}_{current_time.strftime("%H-%M-%S")}_{file_name}', 54 | ) 55 | 56 | if not os.path.isdir(gclone_path): 57 | Path(gclone_path).mkdir(parents=True, exist_ok=True) 58 | file = document.get_file(timeout=20) 59 | file.download(custom_path=file_pah) 60 | 61 | zip_path = os.path.join(gclone_path, 'current') 62 | 63 | # remove old files 64 | if os.path.isdir(zip_path): 65 | shutil.rmtree(zip_path) 66 | while os.path.exists(zip_path): 67 | time.sleep(1) 68 | Path(zip_path).mkdir(parents=True, exist_ok=True) 69 | 70 | # unzip files 71 | with ZipFile(file_pah, 'r') as zip_file: 72 | for member in zip_file.namelist(): 73 | filename = os.path.basename(member) 74 | # skip directories 75 | if not filename: 76 | continue 77 | 78 | source = zip_file.open(member) 79 | target = open(os.path.join(zip_path, filename), "wb") 80 | with source, target: 81 | shutil.copyfileobj(source, target) 82 | 83 | # remove non json 84 | puppet_file = None 85 | json_count = 1 86 | for f in os.listdir(zip_path): 87 | current_file = os.path.join(zip_path, f) 88 | if not f.endswith('.json'): 89 | os.remove(current_file) 90 | elif not puppet_file: 91 | puppet_file = os.path.join(zip_path, 'google_drive_puppet.json') 92 | shutil.copy(current_file, puppet_file) 93 | else: 94 | json_count += 1 95 | if not puppet_file: 96 | update.message.reply_text(instruction_text) 97 | return 98 | 99 | # generate config file 100 | config_file = configparser.ConfigParser() 101 | config_file.add_section('gc') 102 | config_file.set('gc', 'type', 'drive') 103 | config_file.set('gc', 'scope', 'drive') 104 | config_file.set('gc', 'service_account_file', puppet_file) 105 | config_file.set('gc', 'service_account_file_path', zip_path + os.path.sep) 106 | config_file.set('gc', 'root_folder_id', 'root') 107 | 108 | with open(os.path.join(zip_path, 'rclone.conf'), 'w') as file_to_write: 109 | config_file.write(file_to_write) 110 | 111 | update.message.reply_text( 112 | f'✔️ A total of {json_count} SA files were received and configured to use in CloneBot V2. \n │ Now bookmark your favorite folders with /folders' 113 | ) 114 | 115 | logger.info( 116 | f'{json_count} Service Accounts have been saved for the User {update.effective_user.id}.' 117 | ) 118 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/start.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import Dispatcher, CommandHandler 6 | 7 | from utils.callback import callback_delete_message 8 | from utils.config_loader import config 9 | from utils.restricted import restricted 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | def init(dispatcher: Dispatcher): 15 | """Provide handlers initialization.""" 16 | dispatcher.add_handler(CommandHandler('start', start)) 17 | 18 | 19 | @restricted 20 | def start(update, context): 21 | rsp = update.message.reply_text('🔺 First, send me a ZIP archive containing the SA files and add /sa to the subject. 🔺\n' 22 | '📂 After that, use /folders to set and mark/favourite your destination folders. 📂\n' 23 | '🔗 You are now ready to go! Just forward or send a Google Drive link to clone the File/Folder 🔗 \n.') 24 | rsp.done.wait(timeout=60) 25 | message_id = rsp.result().message_id 26 | if update.message.chat_id < 0: 27 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 28 | context=(update.message.chat_id, message_id)) 29 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 30 | context=(update.message.chat_id, update.message.message_id)) 31 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/stop_task.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | import re 5 | 6 | from telegram.ext import Dispatcher, CallbackQueryHandler 7 | 8 | from utils.fire_save_files import thread_pool 9 | from utils.helper import alert_users 10 | from utils.restricted import restricted 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | regex_stop_task = r'^stop_task,(\d+)' 15 | 16 | 17 | def init(dispatcher: Dispatcher): 18 | """Provide handlers initialization.""" 19 | dispatcher.add_handler(CallbackQueryHandler(stop_task, pattern=regex_stop_task)) 20 | 21 | 22 | @restricted 23 | def stop_task(update, context): 24 | query = update.callback_query 25 | if query.message.chat_id < 0 and \ 26 | (not query.message.reply_to_message or 27 | query.from_user.id != query.message.reply_to_message.from_user.id): 28 | alert_users(context, update.effective_user, 'invalid caller', query.data) 29 | query.answer(text='Yo-he!', show_alert=True) 30 | return 31 | if query.data: 32 | if match := re.search(regex_stop_task, query.data): 33 | thread_id = int(match[1]) 34 | if tasks := thread_pool.get(update.effective_user.id, None): 35 | for t in tasks: 36 | if t.ident == thread_id and t.owner == query.from_user.id: 37 | t.kill() 38 | logger.info(f'User {query.from_user.id} has stopped Cloning Task {thread_id}') 39 | return 40 | alert_users(context, update.effective_user, 'invalid query data', query.data) 41 | query.answer(text='Yo-he!', show_alert=True) 42 | return 43 | -------------------------------------------------------------------------------- /telegram_gcloner/handlers/vip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import copy 4 | import logging 5 | 6 | from telegram import Update 7 | from telegram.ext import Dispatcher, CommandHandler, CallbackContext, Filters 8 | 9 | from utils.config_loader import config 10 | from utils.restricted import restricted_admin 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def init(dispatcher: Dispatcher): 16 | """Provide handlers initialization.""" 17 | dispatcher.add_handler(CommandHandler('vip', vip, filters=Filters.chat(config.USER_IDS[0]), pass_args=True)) 18 | dispatcher.add_handler(CommandHandler('unvip', unvip, filters=Filters.chat(config.USER_IDS[0]), pass_args=True)) 19 | 20 | 21 | @restricted_admin 22 | def vip(update: Update, context: CallbackContext): 23 | if not context.args: 24 | if vip_list := context.bot_data.get('vip', None): 25 | update.message.reply_text('\n'.join(map(str, vip_list))) 26 | return 27 | if not context.args[0].isdigit: 28 | update.message.reply_text('/vip user_id') 29 | return 30 | user_id = int(context.args[0]) 31 | if not context.bot_data.get('vip', None): 32 | context.bot_data['vip'] = [user_id] 33 | elif user_id not in context.bot_data['vip']: 34 | new_vip = copy.deepcopy(context.bot_data['vip']) 35 | new_vip.append(user_id) 36 | context.bot_data['vip'] = new_vip 37 | else: 38 | update.message.reply_text('User already Exists in VIP Users List.') 39 | return 40 | context.dispatcher.update_persistence() 41 | update.message.reply_text('User added successfully to VIP Users List.') 42 | logger.info(f'{user_id} is added successfully to VIP Users List.') 43 | return 44 | 45 | 46 | @restricted_admin 47 | def unvip(update: Update, context: CallbackContext): 48 | if not context.args or not context.args[0].isdigit: 49 | update.message.reply_text('/unvip user_id') 50 | return 51 | user_id = int(context.args[0]) 52 | if user_id in context.bot_data.get('vip', []): 53 | new_vip = copy.deepcopy(context.bot_data['vip']) 54 | new_vip.remove(user_id) 55 | context.bot_data['vip'] = new_vip 56 | context.dispatcher.update_persistence() 57 | update.message.reply_text('Removed from VIP.') 58 | logger.info(f'{user_id} is successfully removed from VIP Users List.') 59 | else: 60 | update.message.reply_text('Could not find User in VIP Users List.') 61 | 62 | return 63 | -------------------------------------------------------------------------------- /telegram_gcloner/telegram_gcloner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import functools 4 | import logging 5 | import html 6 | import os.path 7 | import re 8 | import sys 9 | 10 | import traceback 11 | from importlib import import_module 12 | from logging import handlers 13 | from pathlib import Path 14 | 15 | from telegram import ParseMode 16 | from telegram.ext import Updater, Dispatcher 17 | 18 | import telegram.bot 19 | from telegram.ext import messagequeue as mq 20 | from telegram.ext.picklepersistence import PicklePersistence 21 | 22 | from telegram.utils.helpers import mention_html 23 | from telegram.utils.request import Request as TGRequest 24 | 25 | 26 | from utils.config_loader import config 27 | 28 | 29 | logger = logging.getLogger(__name__) 30 | 31 | 32 | class MQBot(telegram.bot.Bot): 33 | """A subclass of Bot which delegates send method handling to MQ""" 34 | 35 | def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): 36 | super(MQBot, self).__init__(*args, **kwargs) 37 | # below 2 attributes should be provided for decorator usage 38 | self._is_messages_queued_default = is_queued_def 39 | self._msg_queue = mqueue or mq.MessageQueue( 40 | all_burst_limit=29, 41 | all_time_limit_ms=1017, 42 | group_burst_limit=19, 43 | group_time_limit_ms=60000, 44 | ) 45 | 46 | def __del__(self): 47 | try: 48 | self._msg_queue.stop() 49 | except: 50 | pass 51 | 52 | def auto_group(method): 53 | @functools.wraps(method) 54 | def wrapped(self, *args, **kwargs): 55 | chat_id = 0 56 | if "chat_id" in kwargs: 57 | chat_id = kwargs["chat_id"] 58 | elif len(args) > 0: 59 | chat_id = args[0] 60 | is_group = True if type(chat_id) is str else (chat_id < 0) 61 | return method(self, *args, **kwargs, isgroup=is_group) 62 | 63 | @mq.queuedmessage 64 | def send_message(self, *args, **kwargs): 65 | """Wrapped method would accept new `queued` and `isgroup` 66 | OPTIONAL arguments""" 67 | return super(MQBot, self).send_message(*args, **kwargs) 68 | 69 | @mq.queuedmessage 70 | def send_photo(self, *args, **kwargs): 71 | """Wrapped method would accept new `queued` and `isgroup` 72 | OPTIONAL arguments""" 73 | return super(MQBot, self).send_photo(*args, **kwargs) 74 | # 75 | # @mq.queuedmessage 76 | # def edit_message_text(self, *args, **kwargs): 77 | # '''Wrapped method would accept new `queued` and `isgroup` 78 | # OPTIONAL arguments''' 79 | # return super(MQBot, self).edit_message_text(*args, **kwargs) 80 | 81 | @mq.queuedmessage 82 | def forward_message(self, *args, **kwargs): 83 | """Wrapped method would accept new `queued` and `isgroup` 84 | OPTIONAL arguments""" 85 | return super(MQBot, self).forward_message(*args, **kwargs) 86 | # 87 | # @mq.queuedmessage 88 | # def answer_callback_query(self, *args, **kwargs): 89 | # '''Wrapped method would accept new `queued` and `isgroup` 90 | # OPTIONAL arguments''' 91 | # return super(MQBot, self).answer_callback_query(*args, **kwargs) 92 | 93 | @mq.queuedmessage 94 | def leave_chat(self, *args, **kwargs): 95 | """Wrapped method would accept new `queued` and `isgroup` 96 | OPTIONAL arguments""" 97 | return super(MQBot, self).leave_chat(*args, **kwargs) 98 | 99 | 100 | def main(): 101 | log_file = init_logger() 102 | config.load_config() 103 | config.LOG_FILE = log_file 104 | 105 | telegram_pickle = PicklePersistence( 106 | filename=f'pickle_{config.USER_IDS[0]}', 107 | store_bot_data=True, 108 | store_user_data=True, 109 | store_chat_data=False, 110 | ) 111 | 112 | q = mq.MessageQueue() 113 | request = TGRequest(con_pool_size=8) 114 | my_bot = MQBot(config.TELEGRAM_TOKEN, request=request, mqueue=q) 115 | updater = Updater(bot=my_bot, use_context=True, persistence=telegram_pickle) 116 | 117 | updater.dispatcher.add_error_handler(error) 118 | 119 | load_handlers(updater.dispatcher) 120 | 121 | updater.start_polling() 122 | updater.bot.send_message(chat_id=config.USER_IDS[0], text='Welcome to CloneBot V2⚡.\n Let\'s clone some data to your Team Drives !') 123 | updater.idle() 124 | 125 | 126 | def init_logger(): 127 | root_logger = logging.getLogger() 128 | root_logger.setLevel(logging.DEBUG) 129 | console_logger = logging.StreamHandler() 130 | console_logger.setLevel(logging.INFO) 131 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 132 | console_logger.setFormatter(formatter) 133 | root_logger.addHandler(console_logger) 134 | 135 | this_file_name = os.path.basename(os.path.splitext(os.path.basename(__file__))[0]) 136 | 137 | Path('./logs/').mkdir(parents=True, exist_ok=True) 138 | logfile = f'./logs/{this_file_name}' 139 | 140 | file_logger = handlers.TimedRotatingFileHandler(logfile, encoding='utf-8', when='midnight') 141 | file_logger.suffix = "%Y-%m-%d.log" 142 | file_logger.extMatch = re.compile(r'^\d{4}-\d{2}-\d{2}\.log$') 143 | file_logger.setLevel(logging.DEBUG) 144 | file_logger.setFormatter(formatter) 145 | root_logger.addHandler(file_logger) 146 | 147 | logging.getLogger('googleapiclient').setLevel(logging.CRITICAL) 148 | logging.getLogger('googleapiclient.discover').setLevel(logging.CRITICAL) 149 | logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.CRITICAL) 150 | logging.getLogger('google.auth.transport.requests').setLevel(logging.INFO) 151 | 152 | logging.getLogger('telegram.bot').setLevel(logging.INFO) 153 | logging.getLogger('telegram.ext.dispatcher').setLevel(logging.INFO) 154 | logging.getLogger('telegram.ext.updater').setLevel(logging.INFO) 155 | logging.getLogger('telegram.vendor.ptb_urllib3.urllib3.connectionpool').setLevel(logging.INFO) 156 | logging.getLogger('JobQueue').setLevel(logging.INFO) 157 | 158 | return logfile 159 | 160 | 161 | def load_handlers(dispatcher: Dispatcher): 162 | """Load handlers from files in a 'bot' directory.""" 163 | base_path = os.path.join(os.path.dirname(__file__), 'handlers') 164 | files = os.listdir(base_path) 165 | 166 | for file_name in files: 167 | if file_name.endswith('.py'): 168 | handler_module, _ = os.path.splitext(file_name) 169 | if handler_module == 'process_message': 170 | continue 171 | 172 | module = import_module(f'.{handler_module}', 'handlers') 173 | module.init(dispatcher) 174 | logger.info(f'loaded handler module: {handler_module}') 175 | module = import_module('.process_message', 'handlers') 176 | module.init(dispatcher) 177 | logger.info('loaded handler module: process_message') 178 | 179 | 180 | def error(update, context): 181 | devs = [config.USER_IDS[0]] 182 | # """Log Errors caused by Updates.""" 183 | # text = 'Update "{}" caused error: "{}"'.format(update, context.error) 184 | # logger.warning(text) 185 | 186 | # This traceback is created with accessing the traceback object from the sys.exc_info, which is returned as the 187 | # third value of the returned tuple. Then we use the traceback.format_tb to get the traceback as a string, which 188 | # for a weird reason separates the line breaks in a list, but keeps the linebreaks itself. So just joining an 189 | # empty string works fine. 190 | trace = "".join(traceback.format_tb(sys.exc_info()[2])) 191 | # lets try to get as much information from the telegram update as possible 192 | payload = "" 193 | # normally, we always have an user. If not, its either a channel or a poll update. 194 | if update.effective_user: 195 | payload += f' with the user ' \ 196 | f'{mention_html(update.effective_user.id, html.escape(update.effective_user.first_name))} ' 197 | # there are more situations when you don't get a chat 198 | if update.effective_chat: 199 | if update.effective_chat.title: 200 | payload += f' within the chat {html.escape(update.effective_chat.title)}' 201 | if update.effective_chat.username: 202 | payload += f' (@{update.effective_chat.username}, {update.effective_chat.id})' 203 | # but only one where you have an empty payload by now: A poll (buuuh) 204 | if update.poll: 205 | payload += f' with the poll id {update.poll.id}.' 206 | 207 | context_error = str(context.error) 208 | # lets put this in a "well" formatted text 209 | text = f"Hey.\n The error {html.escape(context_error)} happened{str(payload)}. The full traceback:\n\n{html.escape(trace)}" 210 | 211 | 212 | # ignore message is not modified error from telegram 213 | if 'Message is not modified' in context_error: 214 | return 215 | 216 | # and send it to the dev(s) 217 | for dev_id in devs: 218 | context.bot.send_message(dev_id, text, parse_mode=ParseMode.HTML) 219 | # we raise the error again, so the logger module catches it. If you don't use the logger module, use it. 220 | raise 221 | 222 | 223 | if __name__ == '__main__': 224 | main() 225 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/callback.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | 5 | from telegram.ext import CallbackContext 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | def callback_delete_message(context: CallbackContext): 11 | (chat_id, message_id) = context.job.context 12 | try: 13 | context.bot.delete_message(chat_id=chat_id, message_id=message_id) 14 | except Exception as e: 15 | logger.warning(f'Could not delete message {message_id}: {e}') 16 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/config_loader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import configparser 5 | import logging 6 | import os 7 | import shutil 8 | import sys 9 | 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class _Config: 15 | def __init__(self): 16 | self._ad_string = '' 17 | self._log_file = '' 18 | self._telegram_token = None 19 | self._path_to_gclone = None 20 | self._user_ids = '' 21 | self._group_ids = '' 22 | self._gclone_para_override = '' 23 | self._base_path = os.path.dirname(os.path.dirname(__file__)) 24 | self.TIMER_TO_DELETE_MESSAGE = 20 25 | self.AD_STRING = ' Goodbye, Please talk to the Bot privately.' 26 | 27 | def load_config(self): 28 | logger.debug('Loading config') 29 | 30 | try: 31 | config_file = configparser.ConfigParser(allow_no_value=True) 32 | config_file.read(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config.ini'), encoding='utf-8') 33 | except IOError as err: 34 | logger.warning("Can't open the config file: ", err) 35 | input('Press enter to exit.') 36 | sys.exit(1) 37 | 38 | if not config_file.has_section('General'): 39 | logger.warning("Can't find General section in the Config File.") 40 | input('Press enter to exit.') 41 | sys.exit(1) 42 | 43 | config_general = config_file['General'] 44 | 45 | config_general_keywords_str = [ 46 | 'telegram_token', 47 | 'user_ids', 48 | 'group_ids', 49 | ] 50 | 51 | self.get_config_from_section('str', config_general_keywords_str, config_general) 52 | self.get_config_from_section('str', ['path_to_gclone', 'gclone_para_override'], config_general, optional=True) 53 | 54 | self._user_ids = [int(item) for item in self._user_ids.split(',')] 55 | self._group_ids = [int(item) for item in self._group_ids.split(',')] 56 | 57 | if not os.path.isfile(self._path_to_gclone): 58 | self._path_to_gclone = shutil.which('gclone') 59 | if not self._path_to_gclone: 60 | logger.warning('Gclone Executable was not found in the Drectory.') 61 | input("Press Enter to continue...") 62 | sys.exit(0) 63 | logger.info(f'Found gclone: {self._path_to_gclone}') 64 | 65 | if not self._telegram_token: 66 | logger.warning('Telegram Bot Token not found.') 67 | input("Press Enter to continue...") 68 | sys.exit(0) 69 | logger.info(f'Found Bot Token: {self._telegram_token}') 70 | 71 | if self._gclone_para_override: 72 | self._gclone_para_override = self._gclone_para_override.split() 73 | 74 | def get_config_from_section(self, var_type, keywords, section, optional=False): 75 | for item in keywords: 76 | if var_type == 'int': 77 | value = section.getint(item, 0) 78 | elif var_type == 'str': 79 | value = section.get(item, '') 80 | elif var_type == 'bool': 81 | value = section.getboolean(item, False) 82 | else: 83 | raise TypeError 84 | if not optional and not value and value is not False: 85 | logger.warning(f'{item} is not provided.') 86 | input("Press Enter to continue...") 87 | sys.exit(1) 88 | logger.info(f'Found {item}: {value}') 89 | setattr(self, f'_{item}', value) 90 | 91 | @property 92 | def PATH_TO_GCLONE(self): 93 | return self._path_to_gclone 94 | 95 | @property 96 | def TELEGRAM_TOKEN(self): 97 | return self._telegram_token 98 | 99 | @property 100 | def USER_IDS(self): 101 | return self._user_ids 102 | 103 | @property 104 | def GROUP_IDS(self): 105 | return self._group_ids 106 | 107 | @property 108 | def GCLONE_PARA_OVERRIDE(self): 109 | return self._gclone_para_override 110 | 111 | @property 112 | def BASE_PATH(self): 113 | return self._base_path 114 | 115 | @property 116 | def LOG_FILE(self): 117 | return self._log_file 118 | 119 | @LOG_FILE.setter 120 | def LOG_FILE(self, val): 121 | self._log_file = val 122 | 123 | 124 | config = _Config() -------------------------------------------------------------------------------- /telegram_gcloner/utils/fire_save_files.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import datetime 4 | import html 5 | import logging 6 | import os 7 | import re 8 | import subprocess 9 | import threading 10 | 11 | from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton 12 | 13 | from utils.config_loader import config 14 | from utils.google_drive import GoogleDrive 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | thread_pool = {} 20 | 21 | 22 | class MySaveFileThread(threading.Thread): 23 | def __init__(self, args=(), kwargs=None): 24 | threading.Thread.__init__(self, args=(), kwargs=None) 25 | self.daemon = True 26 | self.args = args 27 | self.critical_fault = False 28 | self.owner = -1 29 | 30 | def run(self): 31 | update, context, folder_ids, text, dest_folder = self.args 32 | self.owner = update.effective_user.id 33 | thread_id = self.ident 34 | is_multiple_ids = len(folder_ids) > 1 35 | is_fclone = 'fclone' in os.path.basename(config.PATH_TO_GCLONE) 36 | chat_id = update.effective_chat.id 37 | user_id = update.effective_user.id 38 | gd = GoogleDrive(user_id) 39 | message = '╭──────⌈ 📥 Copying In Progress ⌋──────╮\n│\n├ 📂 Target Directory:{}\n'.format(dest_folder['path']) 40 | inline_keyboard = InlineKeyboardMarkup( 41 | [[InlineKeyboardButton(text=f'🚫 Stop', callback_data=f'stop_task,{thread_id}')]]) 42 | 43 | reply_message_id = update.callback_query.message.reply_to_message.message_id \ 44 | if update.callback_query.message.reply_to_message else None 45 | rsp = context.bot.send_message(chat_id=chat_id, text=message, 46 | parse_mode=ParseMode.HTML, 47 | disable_web_page_preview=True, 48 | reply_to_message_id=reply_message_id, 49 | reply_markup=inline_keyboard) 50 | rsp.done.wait(timeout=60) 51 | message_id = rsp.result().message_id 52 | 53 | for folder_id in folder_ids: 54 | destination_path = folder_ids[folder_id] 55 | 56 | command_line = [ 57 | config.PATH_TO_GCLONE, 58 | 'copy', 59 | '--drive-server-side-across-configs', 60 | '-P', 61 | '--stats', 62 | '1s', 63 | '--ignore-existing' 64 | ] 65 | if config.GCLONE_PARA_OVERRIDE: 66 | command_line.extend(config.GCLONE_PARA_OVERRIDE) 67 | elif is_fclone is True: 68 | command_line += [ 69 | '--checkers=256', 70 | '--transfers=256', 71 | '--drive-pacer-min-sleep=1ms', 72 | '--drive-pacer-burst=5000', 73 | '--check-first' 74 | ] 75 | else: 76 | command_line += [ 77 | '--transfers', 78 | '8', 79 | '--tpslimit', 80 | '6', 81 | ] 82 | gclone_config = os.path.join(config.BASE_PATH, 83 | 'gclone_config', 84 | str(update.effective_user.id), 85 | 'current', 86 | 'rclone.conf') 87 | command_line += ['--config', gclone_config] 88 | command_line += [ 89 | '{}:{{{}}}'.format('gc', folder_id), 90 | ('{}:{{{}}}/{}'.format('gc', dest_folder['folder_id'], destination_path)) 91 | ] 92 | 93 | logger.debug('command line: ' + str(command_line)) 94 | 95 | process = subprocess.Popen(command_line, 96 | bufsize=1, 97 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 98 | encoding='utf-8', 99 | errors='ignore', 100 | universal_newlines=True) 101 | progress_checked_files = 0 102 | progress_total_check_files = 0 103 | progress_transferred_file = 0 104 | progress_total_files = 0 105 | progress_file_percentage = 0 106 | progress_file_percentage_10 = 0 107 | progress_transferred_size = '0' 108 | progress_total_size = '0 Bytes' 109 | progress_speed = '-' 110 | progress_speed_file = '-' 111 | progress_eta = '-' 112 | progress_size_percentage_10 = 0 113 | regex_checked_files = r'Checks:\s+(\d+)\s+/\s+(\d+)' 114 | regex_total_files = r'Transferred:\s+(\d+) / (\d+), (\d+)%(?:,\s*([\d.]+\sFiles/s))?' 115 | regex_total_size = r'Transferred:[\s]+([\d.]+\s*[kMGTP]?) / ([\d.]+[\s]?[kMGTP]?Bytes),' \ 116 | r'\s*(?:\-|(\d+)\%),\s*([\d.]+\s*[kMGTP]?Bytes/s),\s*ETA\s*([\-0-9hmsdwy]+)' 117 | message_progress_last = '' 118 | message_progress = '' 119 | progress_update_time = datetime.datetime.now() - datetime.timedelta(minutes=5) 120 | while True: 121 | try: 122 | line = process.stdout.readline() 123 | except Exception as e: 124 | logger.debug(str(e)) 125 | if process.poll() is not None: 126 | break 127 | else: 128 | continue 129 | if not line and process.poll() is not None: 130 | break 131 | output = line.rstrip() 132 | if output: 133 | # logger.debug(output) 134 | match_total_files = re.search(regex_total_files, output) 135 | if match_total_files: 136 | progress_transferred_file = int(match_total_files.group(1)) 137 | progress_total_files = int(match_total_files.group(2)) 138 | progress_file_percentage = int(match_total_files.group(3)) 139 | progress_file_percentage_10 = progress_file_percentage // 10 140 | if match_total_files.group(4): 141 | progress_speed_file = match_total_files.group(4) 142 | match_total_size = re.search(regex_total_size, output) 143 | if match_total_size: 144 | progress_transferred_size = match_total_size.group(1) 145 | progress_total_size = match_total_size.group(2) 146 | progress_size_percentage = int(match_total_size.group(3)) if match_total_size.group( 147 | 3) else 0 148 | progress_size_percentage_10 = progress_size_percentage // 10 149 | progress_speed = match_total_size.group(4) 150 | progress_eta = match_total_size.group(5) 151 | match_checked_files = re.search(regex_checked_files, output) 152 | if match_checked_files: 153 | progress_checked_files = int(match_checked_files.group(1)) 154 | progress_total_check_files = int(match_checked_files.group(2)) 155 | progress_max_percentage_10 = max(progress_size_percentage_10, progress_file_percentage_10) 156 | message_progress = '├──────⌈ Progress Details⌋──────' \ 157 | '├ 🗂 Source : {}\n│\n' \ 158 | '├ ✔️ Checks: {} / {}\n' \ 159 | '├ 📥 Transfers: {} / {}\n' \ 160 | '├ 📦 Size:{} / {}\n{}' \ 161 | '├ ⚡️Speed:{} \n├⏳ ETA: {}\n' \ 162 | '├ ⛩ Progress:[{}] {: >2}%\n│\n' \ 163 | '├──────⌈ CloneBot V2🔥 ⌋──────' \ 164 | .format( 165 | folder_id, 166 | html.escape(destination_path), 167 | progress_checked_files, 168 | progress_total_check_files, 169 | progress_transferred_file, 170 | progress_total_files, 171 | progress_transferred_size, 172 | progress_total_size, 173 | f'Speed:{progress_speed_file}\n' if is_fclone is True else '', 174 | progress_speed, 175 | progress_eta, 176 | '●' * progress_file_percentage_10 + '○' * ( 177 | progress_max_percentage_10 - progress_file_percentage_10) + ' ' * ( 178 | 10 - progress_max_percentage_10), 179 | progress_file_percentage) 180 | 181 | match = re.search(r'Failed to Copy: Failed to Make Directory in the Destination', output) 182 | if match: 183 | message_progress = '{}\n│Destination Write Permission Error.\n Please ensure that you have rights to upload files to the Destination.'.format(message_progress) 184 | temp_message = '{}{}'.format(message, message_progress) 185 | # logger.info('Write permission error, please confirm permission'.format()) 186 | try: 187 | context.bot.edit_message_text(chat_id=chat_id, message_id=message_id, 188 | text=temp_message, parse_mode=ParseMode.HTML, 189 | disable_web_page_preview=True, 190 | reply_markup=inline_keyboard) 191 | except Exception as e: 192 | logger.debug('Error {} occurs when editing message {} for user {} in chat {}: \n│{}'.format( 193 | e, message_id, user_id, chat_id, temp_message)) 194 | process.terminate() 195 | self.critical_fault = True 196 | break 197 | 198 | match = re.search(r"Couldn't List Directory", output) 199 | if match: 200 | message_progress = '{}\n│Source Read permission Error. \n Please ensure that you have rights to read files from the Source Link'.format(message_progress) 201 | temp_message = '{}{}'.format(message, message_progress) 202 | # logger.info('Read permission error, please confirm the permission:') 203 | try: 204 | context.bot.edit_message_text(chat_id=chat_id, message_id=message_id, 205 | text=temp_message, parse_mode=ParseMode.HTML, 206 | disable_web_page_preview=True, 207 | reply_markup=inline_keyboard) 208 | except Exception as e: 209 | logger.debug('Error {} occurs when editing message {} for user {} in chat {}: \n│{}'.format( 210 | e, message_id, user_id, chat_id, temp_message)) 211 | process.terminate() 212 | self.critical_fault = True 213 | break 214 | 215 | if message_progress != message_progress_last: 216 | if datetime.datetime.now() - progress_update_time > datetime.timedelta(seconds=5): 217 | temp_message = '{}{}'.format(message, message_progress) 218 | try: 219 | context.bot.edit_message_text(chat_id=chat_id, message_id=message_id, 220 | text=temp_message, parse_mode=ParseMode.HTML, 221 | disable_web_page_preview=True, 222 | reply_markup=inline_keyboard) 223 | except Exception as e: 224 | logger.debug( 225 | 'Error {} occurs when editing message {} for user {} in chat {}: \n│{}'.format( 226 | e, message_id, user_id, chat_id, temp_message)) 227 | message_progress_last = message_progress 228 | progress_update_time = datetime.datetime.now() 229 | 230 | if self.critical_fault: 231 | message_progress = '{}\n│\n│ You have terminated the Cloning Process'.format(message_progress) 232 | process.terminate() 233 | break 234 | 235 | rc = process.poll() 236 | message_progress_heading, message_progress_content = message_progress.split('\n│', 1) 237 | link_text = 'Unable to fetch Google Drive Link.' 238 | try: 239 | link = gd.get_folder_link(dest_folder['folder_id'], destination_path) 240 | if link: 241 | link_text = '\n│ \n│ 👉 Google Drive Link 👈'.format(link) 242 | except Exception as e: 243 | logger.info(str(e)) 244 | 245 | if self.critical_fault is True: 246 | message = '{}{} ❌\n│{}\n│{}\n│'.format(message, message_progress_heading, message_progress_content, 247 | link_text) 248 | elif progress_file_percentage == 0 and progress_checked_files > 0: 249 | message = '{}{} ✅\n│ File Already Exists in the Destination!\n│ {}\n│'.format(message, message_progress_heading, link_text) 250 | else: 251 | message = '{}{}{}\n│{}\n│{}\n│\n│'.format(message, 252 | message_progress_heading, 253 | '✅' if rc == 0 else '❌', 254 | message_progress_content, 255 | link_text) 256 | 257 | try: 258 | context.bot.edit_message_text(chat_id=chat_id, message_id=message_id, text=message, 259 | parse_mode=ParseMode.HTML, disable_web_page_preview=True, 260 | reply_markup=inline_keyboard) 261 | except Exception as e: 262 | logger.debug('Error {} occurs when editing message {} for user {} in chat {}: \n│{}'.format( 263 | e, message_id, user_id, chat_id, message)) 264 | 265 | if self.critical_fault is True: 266 | break 267 | 268 | message += '\n╰──────⌈ ✅ Cloning Process Finished ! ✅ ⌋──────╯' 269 | try: 270 | context.bot.edit_message_text(chat_id=chat_id, message_id=message_id, text=message, 271 | parse_mode=ParseMode.HTML, disable_web_page_preview=True) 272 | except Exception as e: 273 | logger.debug('Error {} occurs when editing message {} for user {} in chat {}: \n│{}'.format( 274 | e, message_id, user_id, chat_id, message)) 275 | update.callback_query.message.edit_reply_markup(reply_markup=InlineKeyboardMarkup( 276 | [[InlineKeyboardButton(text='Done', callback_data='cancel')]])) 277 | 278 | logger.debug('User {} has finished task {}: \n│{}'.format(user_id, thread_id, message)) 279 | tasks = thread_pool.get(user_id, None) 280 | if tasks: 281 | for t in tasks: 282 | if t.ident == thread_id: 283 | tasks.remove(t) 284 | return 285 | 286 | def kill(self): 287 | self.critical_fault = True 288 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/google_drive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import copy 4 | import logging 5 | import os 6 | 7 | from googleapiclient import errors 8 | from googleapiclient.discovery import build 9 | from google.auth.transport.requests import Request 10 | from google.oauth2 import service_account 11 | 12 | from utils.config_loader import config 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | class GoogleDrive: 18 | def __init__(self, user_id): 19 | service_account_file = os.path.join(config.BASE_PATH, 20 | 'gclone_config', 21 | str(user_id), 22 | 'current', 23 | 'google_drive_puppet.json') 24 | 25 | creds = None 26 | scopes = ['https://www.googleapis.com/auth/drive'] 27 | 28 | if os.path.exists(service_account_file): 29 | creds = service_account.Credentials.from_service_account_file( 30 | service_account_file, scopes=scopes) 31 | if not creds.valid: 32 | creds.refresh(Request()) 33 | 34 | # If there are no (valid) credentials available, throw error. 35 | if not creds or not creds.valid: 36 | raise FileNotFoundError 37 | 38 | self.service = build('drive', 'v3', credentials=creds) 39 | 40 | def get_drives(self): 41 | result = [] 42 | page_token = None 43 | while True: 44 | try: 45 | param = { 46 | 'pageSize': 100, 47 | } 48 | if page_token: 49 | param['pageToken'] = page_token 50 | drives = self.service.drives().list(**param).execute() 51 | 52 | result.extend(drives['drives']) 53 | logger.debug(f"Received {len(drives['drives'])} drives") 54 | page_token = drives.get('nextPageToken') 55 | if not page_token: 56 | break 57 | except errors.HttpError as error: 58 | logger.warning(f'An error occurred: {error}') 59 | break 60 | return {item['id']: item['name'] for item in result} 61 | 62 | def get_file_name(self, file_id): 63 | param = { 64 | 'fileId': file_id, 65 | 'supportsAllDrives': True, 66 | 'fields': 'name, driveId', 67 | } 68 | file_info = self.service.files().get(**param).execute() 69 | file_name = file_info['name'] 70 | if file_info.get('driveId', None) == file_id: 71 | file_name = self.get_drive_name(file_id) 72 | return file_name 73 | 74 | def get_file_path_from_id(self, file_id, parents=[]): 75 | result = copy.deepcopy(parents) 76 | param = { 77 | 'fileId': file_id, 78 | 'supportsAllDrives': True, 79 | 'fields': 'name, mimeType, parents, driveId', 80 | } 81 | file_info = self.service.files().get(**param).execute() 82 | if file_info.get('driveId', None) == file_id: 83 | drive_name = self.get_drive_name(file_id) 84 | parent_entry = {'name': drive_name, 'folder_id': file_id} 85 | else: 86 | parent_entry = {'name': file_info['name'], 'folder_id': file_id} 87 | parent = file_info.get('parents', None) 88 | result.append(parent_entry) 89 | if parent: 90 | return self.get_file_path_from_id(parent[0], result) 91 | logger.debug(str(result)) 92 | return result 93 | 94 | def get_drive_name(self, drive_id): 95 | param = { 96 | 'driveId': drive_id, 97 | } 98 | drive_info = self.service.drives().get(**param).execute() 99 | return drive_info['name'] 100 | 101 | def list_folders(self, folder_id): 102 | result = [] 103 | 104 | page_token = None 105 | while True: 106 | try: 107 | param = { 108 | 'q': f"'{folder_id}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false", 109 | 'includeItemsFromAllDrives': True, 110 | 'supportsAllDrives': True, 111 | 'fields': 'nextPageToken, files(id, name)', 112 | 'pageSize': 1000, 113 | } 114 | 115 | if page_token: 116 | param['pageToken'] = page_token 117 | all_files = self.service.files().list(**param).execute() 118 | 119 | result.extend(all_files['files']) 120 | logger.debug(f"Received {len(all_files['files'])} files") 121 | page_token = all_files.get('nextPageToken') 122 | 123 | if not page_token: 124 | break 125 | except errors.HttpError as error: 126 | logger.info(f'An error occurred: {error}') 127 | break 128 | result_sorted = sorted(result, key=lambda k: k['name']) 129 | return {item['id']: item['name'] for item in result_sorted} 130 | 131 | def get_folder_link(self, folder_id, folder_path): 132 | folder_path_list = list(filter(None, folder_path.split('/'))) 133 | if result := self.get_folder_id_by_name(folder_id, folder_path_list[0]): 134 | if len(folder_path_list) > 1: 135 | for item in result: 136 | next_result = self.get_folder_link(item['id'], '/'.join(folder_path_list[1:])) 137 | if isinstance(next_result, str): 138 | return next_result 139 | return None 140 | else: 141 | link = f"https://drive.google.com/open?id={result[0]['id']}" 142 | logger.info(f'found link: {link}') 143 | return link 144 | return None 145 | 146 | def get_folder_id_by_name(self, folder_id, folder_name): 147 | page_token = None 148 | result = [] 149 | while True: 150 | try: 151 | param = { 152 | 'q': f"name = '{folder_name}' and mimeType = 'application/vnd.google-apps.folder' and '{folder_id}' in parents and trashed = false", 153 | 'includeItemsFromAllDrives': True, 154 | 'supportsAllDrives': True, 155 | 'fields': 'nextPageToken, files(id, name)', 156 | 'pageSize': 1000, 157 | } 158 | 159 | if page_token: 160 | param['pageToken'] = page_token 161 | # logger.debug(str(param)) 162 | all_files = self.service.files().list(**param).execute() 163 | 164 | result.extend(all_files['files']) 165 | # logger.debug(str(allFiles)) 166 | # logger.info('Received {} files'.format(len(allFiles['files']))) 167 | page_token = all_files.get('nextPageToken') 168 | 169 | if not page_token: 170 | break 171 | except errors.HttpError as error: 172 | logger.info(f'An error occurred: {error}') 173 | break 174 | return result 175 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import html 4 | import logging 5 | import math 6 | import re 7 | 8 | from telegram import ParseMode, InlineKeyboardButton 9 | from telegram.utils.helpers import mention_html 10 | 11 | from utils.config_loader import config 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | def parse_folder_id_from_url(url): 17 | folder_id = None 18 | 19 | pattern = r'https://drive\.google\.com/(?:' \ 20 | r'drive/(?:u/[\d]+/)?(?:mobile/)?folders/([\w.\-_]+)(?:\?[\=\w]+)?|' \ 21 | r'folderview\?id=([\w.\-_]+)(?:\&[=\w]+)?|' \ 22 | r'open\?id=([\w.\-_]+)(?:\&[=\w]+)?|' \ 23 | r'(?:a/[\w.\-_]+/)?file/d/([\w.\-_]+)|' \ 24 | r'(?:a/[\w.\-_]+/)?uc\?id\=([\w.\-_]+)&?' \ 25 | r')' 26 | 27 | if x := re.search(pattern, url): 28 | folder_id = ''.join(filter(None, x.groups())) 29 | 30 | if folder_id: 31 | logger.debug(f'folder_id: {folder_id}') 32 | return folder_id 33 | 34 | 35 | def alert_users(context, user_info, warning_message, text): 36 | mention_html_user = mention_html(user_info.id, html.escape(user_info.full_name)) 37 | message = f'🤔 Detected Suspicious Behaviour from User {mention_html_user} {user_info.id}: {warning_message} {text}.' 38 | 39 | logger.info(message) 40 | context.bot.send_message(chat_id=config.USER_IDS[0], text=message, parse_mode=ParseMode.HTML) 41 | 42 | 43 | def get_inline_keyboard_pagination_data(callback_query_prefix, page_data, page_data_chosen=None, page=1, 44 | max_per_page=10): 45 | callback_query_prefix_data = f'{callback_query_prefix}_page#{page}' 46 | page_data_len = len(page_data) 47 | total_page = math.ceil(page_data_len / max_per_page) 48 | inline_keyboard = [] 49 | for i in range(max((min(page, total_page) - 1) * max_per_page, 0), 50 | min(max(page, 1) * max_per_page, page_data_len)): 51 | if isinstance(page_data[i], list): 52 | inline_keyboard_row = [] 53 | for j in range(len(page_data[i])): 54 | is_chosen = any(k == page_data[i][j]['data'] for k in page_data_chosen or []) 55 | text = f"{'✅ ' if is_chosen else ''}{page_data[i][j]['text']}" 56 | if page_data[i][j]['data'] != '#': 57 | data = f"{f'un{callback_query_prefix_data}' if is_chosen else callback_query_prefix_data},{page_data[i][j]['data']}" 58 | 59 | else: 60 | data = '#' 61 | inline_keyboard_row.append(InlineKeyboardButton(text, callback_data=data)) 62 | inline_keyboard.append(inline_keyboard_row) 63 | else: 64 | is_chosen = any(k == page_data[i]['data'] for k in page_data_chosen or []) 65 | text = f"{'✅ ' if is_chosen else ''}{page_data[i]['text']}" 66 | if page_data[i]['data'] != '#': 67 | data = f"{f'un{callback_query_prefix_data}' if is_chosen else callback_query_prefix_data},{page_data[i]['data']}" 68 | 69 | else: 70 | data = '#' 71 | inline_keyboard.append( 72 | [InlineKeyboardButton(text, callback_data=data)]) 73 | if total_page > 1: 74 | inline_keyboard.extend(get_inline_keyboard_pagination_paginator(callback_query_prefix, 75 | total_page, 76 | page=page, 77 | )) 78 | return inline_keyboard 79 | 80 | 81 | def get_inline_keyboard_pagination_paginator(callback_query_prefix, total_page, page=1, total_pages_shown=5): 82 | start_page = min(max(page - total_pages_shown // 2, 1), max(total_page - total_pages_shown + 1, 1)) 83 | inline_keyboard_pagination_page = [ 84 | InlineKeyboardButton( 85 | f'{i}' if i != page else f'*{i}', 86 | callback_data=f'{callback_query_prefix}_page#{i}' 87 | if i != page 88 | else '#', 89 | ) 90 | for i in range( 91 | start_page, min(start_page + total_pages_shown, total_page + 1) 92 | ) 93 | ] 94 | 95 | inline_keyboard_pagination = [inline_keyboard_pagination_page] 96 | if total_page > total_pages_shown: 97 | previous_1 = max(page - 1, 1) 98 | previous_2 = max(page - total_pages_shown, 1) 99 | next_1 = min(page + 1, total_page) 100 | next_2 = min(page + total_pages_shown, total_page) 101 | 102 | inline_keyboard_pagination_nav = [ 103 | InlineKeyboardButton( 104 | '|<', 105 | callback_data=f'{callback_query_prefix}_page#1' 106 | if page != 1 107 | else '#', 108 | ), 109 | InlineKeyboardButton( 110 | '<<', 111 | callback_data=f'{callback_query_prefix}_page#{previous_2}' 112 | if page != previous_2 113 | else '#', 114 | ), 115 | InlineKeyboardButton( 116 | '<', 117 | callback_data=f'{callback_query_prefix}_page#{previous_1}' 118 | if page != previous_1 119 | else '#', 120 | ), 121 | InlineKeyboardButton(f'{page}/{total_page}', callback_data='#'), 122 | InlineKeyboardButton( 123 | '>', 124 | callback_data=f'{callback_query_prefix}_page#{next_1}' 125 | if page != next_1 126 | else '#', 127 | ), 128 | InlineKeyboardButton( 129 | '>>', 130 | callback_data=f'{callback_query_prefix}_page#{next_2}' 131 | if page != next_2 132 | else '#', 133 | ), 134 | InlineKeyboardButton( 135 | '>|', 136 | callback_data=f'{callback_query_prefix}_page#{total_page}' 137 | if page != total_page 138 | else '#', 139 | ), 140 | ] 141 | 142 | inline_keyboard_pagination.append(inline_keyboard_pagination_nav) 143 | return inline_keyboard_pagination 144 | 145 | 146 | def simplified_path(folder_path): 147 | max_length = 30 148 | 149 | prefix, delimiter, postfix = folder_path.rpartition('/') 150 | spare_length = max(max_length - len(postfix), 0) 151 | 152 | # logger.debug(prefix) 153 | return f"{f'{prefix[:spare_length]}..' if len(prefix) > spare_length else prefix}/{postfix}" 154 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import html 4 | import logging 5 | 6 | 7 | from telegram import ParseMode 8 | from telegram.utils.helpers import mention_html 9 | 10 | from utils.config_loader import config 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def leave_chat_from_message(message, context): 16 | context.bot.send_message( 17 | chat_id=message.chat_id, 18 | text=f'Hey, Thank you for adding CloneBot V2 to this group. {config.AS_STRING.format(context.bot.username)}', 19 | parse_mode=ParseMode.HTML, 20 | ) 21 | 22 | context.bot.send_message(chat_id=message.chat_id, text='\n\nUnfortunately I am not authorized in this Group/Chat 😔 \n So I am leavng this Group \nIf you want me in this Group/Chat, ask my owner to authorize me here 😉.') 23 | if message.from_user: 24 | mention_html_from_user = mention_html(message.from_user.id, 25 | message.from_user.full_name.full_name) 26 | text = f'🔙 Left Unauthorized Group : \n │ Name : {html.escape(message.chat.title)} ({message.chat_id}). \n │ Added by : {mention_html_from_user} {message.from_user.id}. \n │ Message : {message.text}' 27 | 28 | else: 29 | text = f'🔙 Left Unauthorized Group : \n │ Name : {html.escape(message.chat.title)} ({message.chat_id}). \n │ Message : {message.text}' 30 | 31 | context.bot.leave_chat(message.chat_id) 32 | logger.warning(text) 33 | context.bot.send_message(chat_id=config.USER_IDS[0], text=text, parse_mode=ParseMode.HTML) 34 | -------------------------------------------------------------------------------- /telegram_gcloner/utils/restricted.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import logging 4 | from functools import wraps 5 | 6 | from utils.callback import callback_delete_message 7 | from utils.config_loader import config 8 | 9 | logger = logging.getLogger(__name__) 10 | 11 | 12 | def restricted(func): 13 | @wraps(func) 14 | def wrapped(update, context, *args, **kwargs): 15 | if not update.effective_user: 16 | return 17 | user_id = update.effective_user.id 18 | ban_list = context.bot_data.get('ban', []) 19 | # access control. comment out one or the other as you wish. otherwise you can use any of the following examples. 20 | # if user_id in ban_list: 21 | if user_id in ban_list or user_id not in config.USER_IDS: 22 | logger.info('UnAuthorized Access denied for {} {}.' 23 | .format(update.effective_user.full_name, user_id)) 24 | return 25 | return func(update, context, *args, **kwargs) 26 | return wrapped 27 | 28 | 29 | def restricted_private(func): 30 | @wraps(func) 31 | def wrapped(update, context, *args, **kwargs): 32 | if not update.effective_user: 33 | return 34 | user_id = update.effective_user.id 35 | chat_id = update.effective_chat.id 36 | ban_list = context.bot_data.get('ban', []) 37 | if user_id in ban_list or chat_id < 0: 38 | logger.info('Unauthorized access denied for private messages {} {}.' 39 | .format(update.effective_user.full_name, user_id)) 40 | if chat_id < 0: 41 | rsp = update.message.reply_text('Private chat only!') 42 | rsp.done.wait(timeout=60) 43 | message_id = rsp.result().message_id 44 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 45 | context=(update.message.chat_id, message_id)) 46 | context.job_queue.run_once(callback_delete_message, config.TIMER_TO_DELETE_MESSAGE, 47 | context=(update.message.chat_id, update.message.message_id)) 48 | return 49 | return func(update, context, *args, **kwargs) 50 | return wrapped 51 | 52 | 53 | def restricted_private_and_group(func): 54 | @wraps(func) 55 | def wrapped(update, context, *args, **kwargs): 56 | if not update.effective_user: 57 | return 58 | user_id = update.effective_user.id 59 | chat_id = update.effective_chat.id 60 | ban_list = context.bot_data.get('ban', []) 61 | if user_id in ban_list or (chat_id < 0 or chat_id not in config.GROUP_IDS): 62 | logger.info('Unauthorized access denied for private and group messages{} {}.' 63 | .format(update.effective_user.full_name, user_id)) 64 | return 65 | return func(update, context, *args, **kwargs) 66 | return wrapped 67 | 68 | 69 | def restricted_group_only(func): 70 | @wraps(func) 71 | def wrapped(update, context, *args, **kwargs): 72 | if not update.effective_user: 73 | return 74 | user_id = update.effective_user.id 75 | chat_id = update.effective_chat.id 76 | ban_list = context.bot_data.get('ban', []) 77 | if user_id not in config.USER_IDS and (user_id in ban_list or chat_id > 0 or chat_id not in config.GROUP_IDS): 78 | logger.info('Unauthorized access denied for group only messages {} {}.' 79 | .format(update.effective_user.full_name, user_id)) 80 | return 81 | return func(update, context, *args, **kwargs) 82 | return wrapped 83 | 84 | 85 | def restricted_group_and_its_members_in_private(func): 86 | @wraps(func) 87 | def wrapped(update, context, *args, **kwargs): 88 | if not update.effective_user: 89 | return 90 | user_id = update.effective_user.id 91 | chat_id = update.effective_chat.id 92 | ban_list = context.bot_data.get('ban', []) 93 | allow = False 94 | if user_id in config.USER_IDS: 95 | allow = True 96 | elif user_id not in ban_list: 97 | if chat_id < 0: 98 | if chat_id in config.GROUP_IDS: 99 | allow = True 100 | else: 101 | for group_id in config.GROUP_IDS: 102 | info = context.bot.get_chat_member(chat_id=group_id, user_id=update.effective_user.id) 103 | if info.status in ['creator', 'administrator', 'member']: 104 | allow = True 105 | break 106 | if allow is False: 107 | logger.info('Unauthorized access denied for group and its members messages{} {}.' 108 | .format(update.effective_user.full_name, user_id)) 109 | return 110 | return func(update, context, *args, **kwargs) 111 | return wrapped 112 | 113 | 114 | def restricted_user_ids(func): 115 | @wraps(func) 116 | def wrapped(update, context, *args, **kwargs): 117 | if not update.effective_user: 118 | return 119 | user_id = update.effective_user.id 120 | if user_id not in config.USER_IDS: 121 | logger.info('Unauthorized access denied for {} {}.' 122 | .format(update.effective_user.full_name, user_id)) 123 | return 124 | return func(update, context, *args, **kwargs) 125 | return wrapped 126 | 127 | 128 | def restricted_admin(func): 129 | @wraps(func) 130 | def wrapped(update, context, *args, **kwargs): 131 | if not update.effective_user: 132 | return 133 | user_id = update.effective_user.id 134 | chat_id = update.effective_chat.id 135 | if user_id != config.USER_IDS[0]: 136 | logger.info("Unauthorized admin access denied for {} {}.".format(update.effective_user.full_name, user_id)) 137 | return 138 | if chat_id < 0: 139 | return 140 | return func(update, context, *args, **kwargs) 141 | return wrapped 142 | --------------------------------------------------------------------------------