Shivam commited on
Commit ·
2e79dc0
1
Parent(s): a7e554d
Initial commit for Hugging Face Space
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .envDeleted-12
- .gitattributes+3
- CODE_OF_CONDUCT.mdAdded+128
- CONTRIBUTING.mdAdded+23
- Dockerfile+57-16
- FileStream/__init__.pyDeleted-5
- FileStream/__main__.pyDeleted-77
- FileStream/bot/__init__.pyDeleted-25
- FileStream/bot/clients.pyDeleted-59
- FileStream/bot/plugins/admin.pyDeleted-160
- FileStream/bot/plugins/callback.pyDeleted-198
- FileStream/bot/plugins/start.pyDeleted-149
- FileStream/bot/plugins/stream.pyDeleted-96
- FileStream/config.pyDeleted-41
- FileStream/server/__init__.pyDeleted-7
- FileStream/server/exceptions.pyDeleted-5
- FileStream/server/stream_routes.pyDeleted-136
- FileStream/template/dl.htmlDeleted-44
- FileStream/template/play.htmlDeleted-171
- FileStream/utils/__init__.pyDeleted-3
- FileStream/utils/bot_utils.pyDeleted-216
- FileStream/utils/broadcast_helper.pyDeleted-19
- FileStream/utils/custom_dl.pyDeleted-214
- FileStream/utils/database.pyDeleted-134
- FileStream/utils/file_properties.pyDeleted-144
- FileStream/utils/human_readable.pyDeleted-10
- FileStream/utils/render_template.pyDeleted-30
- FileStream/utils/time_format.pyDeleted-22
- FileStream/utils/translation.pyDeleted-72
- FileStreamBotDeleted-1
- FilerAdded+1
- LICENSEAdded+661
- ProcfileDeleted-1
- addons.txtAdded+19
- app.jsonDeleted-117
- assistant/__init__.pyAdded+34
- assistant/callbackstuffs.pyAdded+1325
- assistant/games.pyAdded+317
- assistant/initial.pyAdded+84
- assistant/inlinestuff.pyAdded+623
- assistant/localization.pyAdded+47
- assistant/manager/__init__.pyAdded+11
- assistant/manager/_help.pyAdded+134
- assistant/manager/_on_adds.pyAdded+23
- assistant/manager/admins.pyAdded+50
- assistant/manager/afk.pyAdded+110
- assistant/manager/misc.pyAdded+64
- assistant/manager/stickermanager.pyAdded+180
- assistant/pmbot.pyAdded+150
- assistant/start.pyAdded+240
123456789101112API_ID = 28238386API_HASH = b466f3f2023129c2737f6af0f5a59efaBOT_TOKEN = 7872827994:AAE21CqczkEldf1IzCHn45tentXskDiS4EsULOG_CHANNEL = -1002340006444FLOG_CHANNEL = -1002340006444DATABASE_URL = mongodb+srv://harshkr0095:Harsh8083@cluster0.bnqjd.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0FQDN = 192.168.27.1HAS_SSL = False#MULTI_TOKEN1 = 12345678:bot_token_multi_client_1#MULTI_TOKEN2 = 12345678:bot_token_multi_client_2OWNER_ID = 987456321PORT = 808032 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.otf filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in ourcommunity a harassment-free experience for everyone, regardless of age, bodysize, visible or invisible disability, ethnicity, sex characteristics, genderidentity and expression, level of experience, education, socio-economic status,nationality, personal appearance, race, religion, or sexual identityand orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for ourcommunity include:
* Demonstrating empathy and kindness toward other people* Being respectful of differing opinions, viewpoints, and experiences* Giving and gracefully accepting constructive feedback* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind* Trolling, insulting or derogatory comments, and personal or political attacks* Public or private harassment* Publishing others' private information, such as a physical or email address, without their explicit permission* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards ofacceptable behavior and will take appropriate and fair corrective action inresponse to any behavior that they deem inappropriate, threatening, offensive,or harmful.
Community leaders have the right and responsibility to remove, edit, or rejectcomments, commits, code, wiki edits, issues, and other contributions that arenot aligned to this Code of Conduct, and will communicate reasons for moderationdecisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies whenan individual is officially representing the community in public spaces.Examples of representing our community include using an official e-mail address,posting via an official social media account, or acting as an appointedrepresentative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may bereported to the community leaders responsible for enforcement atteamultroid@ultroid.tech.All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of thereporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determiningthe consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemedunprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providingclarity around the nature of the violation and an explanation of why thebehavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or seriesof actions.
**Consequence**: A warning with consequences for continued behavior. Nointeraction with the people involved, including unsolicited interaction withthose enforcing the Code of Conduct, for a specified period of time. Thisincludes avoiding interactions in community spaces as well as external channelslike social media. Violating these terms may lead to a temporary orpermanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, includingsustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or publiccommunication with the community for a specified period of time. No public orprivate interaction with the people involved, including unsolicited interactionwith those enforcing the Code of Conduct, is allowed during this period.Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of communitystandards, including sustained inappropriate behavior, harassment of anindividual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction withinthe community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],version 2.0, available athttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conductenforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ athttps://www.contributor-covenant.org/faq. Translations are available athttps://www.contributor-covenant.org/translations.1234567891011121314151617181920212223# Welcome To Contributing GuideAny contribution done to this repository will be appreciated! 🎉
### About Ultroid- **Ultroid** is Telegram Userbot, which allow you to perform many task easily. - It's base core is a pip package named [`pyUltroid`](https://GitHub.com/TeamUltroid/pyUltroid).- This repository, contains Ultroid's official plugin files.- moreover, Ultroid User also have an option to get more plugins available at [`UltroidAddons`](https://github.com/TeamUltroid/UltroidAddons)
### Issues- Search for existing Similar issues.- You can open a issue first before contributing, If it contain some major changes like `bug fixes` or `feature addition`.- If you are busy or getting trouble while making changes, you can just open the issue (explaining it).
### Contributing- You can [fork](https://github.com/TeamUltroid/Ultroid/fork) this repository.- You can commits your changes now.- You can [Git-Squash](https://docs.github.com/en/get-started/using-git/about-git-rebase) your commits, if they are more. [Optional]- At last, You are ready to [`make a Pull Request`](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).- Make sure that, your `Pull Request` contain an explaining title and issue number if it closes any open issue.
### Thanks- Congrats! 💫 you have successfully made your Contribution to Ultroid.12345678910111213141516171819202122# Use a minimal base imageFROM ghcr.io/wolfi-dev/alpine-base# Set environment variablesENV OLLAMA_VERSION=1.0.0# Install necessary packagesRUN apk add --no-cache \curl \ca-certificates# Download and install OllamaRUN curl -L https://ollama.com/download/$OLLAMA_VERSION/ollama-linux-amd64.tar.gz | tar -xz -C /usr/local/bin# Create a directory for Ollama dataRUN mkdir -p /root/.ollama# Expose the default Ollama portEXPOSE 11434# Set the entry pointENTRYPOINT ["ollama", "serve"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263FROM python:3.9.5-buster# Fix apt sources for old Buster releaseRUN sed -i 's|deb.debian.org|archive.debian.org|g' /etc/apt/sources.list && \sed -i 's|security.debian.org|archive.debian.org|g' /etc/apt/sources.list && \sed -i '/stretch-updates/d' /etc/apt/sources.list && \echo 'Acquire::Check-Valid-Until "false";' > /etc/apt/apt.conf.d/99no-check-valid-until# Set timezoneENV TZ=Asia/KolkataRUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone# Install dependenciesRUN apt-get update && \apt-get install -y --no-install-recommends \neofetch \git \curl \wget \mediainfo \ffmpeg && \apt-get autoremove --purge -y && \rm -rf /var/lib/apt/lists/*# Set working directoryWORKDIR /Ult# Copy the application codeCOPY . .RUN pip3 install --no-cache-dir -r reqs.txtRUN pip3 install -U pipRUN pip3 install -U redisRUN pip3 install --no-cache-dir -r addons.txtRUN pip3 install --no-cache-dir -r requirements.txtRUN pip3 install --no-cache-dir -r res*/st*/op*# Set appropriate permissionsRUN chown -R 1000:0 /Ult \&& chown -R 1000:0 . \&& chmod 777 . \&& chmod 777 /usr \&& chown -R 1000:0 /usr \&& chmod -R 755 /Ult \&& chmod +x /Ult/start.sh# Install FFmpegRUN wget https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz && \wget https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz.md5 && \md5sum -c ffmpeg-git-amd64-static.tar.xz.md5 && \tar xvf ffmpeg-git-amd64-static.tar.xz && \mv ffmpeg-git*/ffmpeg ffmpeg-git*/ffprobe /usr/local/bin/# Expose portEXPOSE 7860# Start the applicationCMD ["bash", "-c", "python3 server.py & python3 -m pyUltroid"]
12345import time
__version__ = "1.1.0"StartTime = time.time()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import sysimport asyncioimport loggingimport tracebackimport logging.handlers as handlersfrom FileStream.config import Telegram, Serverfrom aiohttp import webfrom pyrogram import idle
from FileStream.bot import FileStreamfrom FileStream.server import web_serverfrom FileStream.bot.clients import initialize_clients
logging.basicConfig( level=logging.INFO, datefmt="%d/%m/%Y %H:%M:%S", format='[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', handlers=[logging.StreamHandler(stream=sys.stdout), handlers.RotatingFileHandler("streambot.log", mode="a", maxBytes=104857600, backupCount=2, encoding="utf-8")],)
logging.getLogger("aiohttp").setLevel(logging.ERROR)logging.getLogger("pyrogram").setLevel(logging.ERROR)logging.getLogger("aiohttp.web").setLevel(logging.ERROR)
server = web.AppRunner(web_server())
loop = asyncio.get_event_loop()
async def start_services(): print() if Telegram.SECONDARY: print("------------------ Starting as Secondary Server ------------------") else: print("------------------- Starting as Primary Server -------------------") print() print("-------------------- Initializing Telegram Bot --------------------")
await FileStream.start() bot_info = await FileStream.get_me() FileStream.id = bot_info.id FileStream.username = bot_info.username FileStream.fname=bot_info.first_name print("------------------------------ DONE ------------------------------") print() print("---------------------- Initializing Clients ----------------------") await initialize_clients() print("------------------------------ DONE ------------------------------") print() print("--------------------- Initializing Web Server ---------------------") await server.setup() await web.TCPSite(server, Server.BIND_ADDRESS, Server.PORT).start() print("------------------------------ DONE ------------------------------") print() print("------------------------- Service Started -------------------------") print(" bot =>> {}".format(bot_info.first_name)) if bot_info.dc_id: print(" DC ID =>> {}".format(str(bot_info.dc_id))) print(" URL =>> {}".format(Server.URL)) print("------------------------------------------------------------------") await idle()
async def cleanup(): await server.cleanup() await FileStream.stop()
if __name__ == "__main__": try: loop.run_until_complete(start_services()) except KeyboardInterrupt: pass except Exception as err: logging.error(traceback.format_exc()) finally: loop.run_until_complete(cleanup()) loop.stop() print("------------------------ Stopped Services ------------------------")12345678910111213141516171819202122232425from ..config import Telegramfrom pyrogram import Client
if Telegram.SECONDARY: plugins=None no_updates=Trueelse: plugins={"root": "FileStream/bot/plugins"} no_updates=None
FileStream = Client( name="FileStream", api_id=Telegram.API_ID, api_hash=Telegram.API_HASH, workdir="FileStream", plugins=plugins, bot_token=Telegram.BOT_TOKEN, sleep_threshold=Telegram.SLEEP_THRESHOLD, workers=Telegram.WORKERS, no_updates=no_updates)
multi_clients = {}work_loads = {}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import asyncioimport loggingfrom os import environfrom ..config import Telegramfrom pyrogram import Clientfrom . import multi_clients, work_loads, FileStream
async def initialize_clients(): all_tokens = dict( (c + 1, t) for c, (_, t) in enumerate( filter( lambda n: n[0].startswith("MULTI_TOKEN"), sorted(environ.items()) ) ) ) if not all_tokens: multi_clients[0] = FileStream work_loads[0] = 0 print("No additional clients found, using default client") return async def start_client(client_id, token): try: if len(token) >= 100: session_string=token bot_token=None print(f'Starting Client - {client_id} Using Session String') else: session_string=None bot_token=token print(f'Starting Client - {client_id} Using Bot Token') if client_id == len(all_tokens): await asyncio.sleep(2) print("This will take some time, please wait...") client = await Client( name=str(client_id), api_id=Telegram.API_ID, api_hash=Telegram.API_HASH, bot_token=bot_token, sleep_threshold=Telegram.SLEEP_THRESHOLD, no_updates=True, session_string=session_string, in_memory=True, ).start() client.id = (await client.get_me()).id work_loads[client_id] = 0 return client_id, client except Exception: logging.error(f"Failed starting Client - {client_id} Error:", exc_info=True) clients = await asyncio.gather(*[start_client(i, token) for i, token in all_tokens.items()]) multi_clients.update(dict(clients)) if len(multi_clients) != 1: Telegram.MULTI_CLIENT = True print("Multi-Client Mode Enabled") else: print("No additional clients were initialized, using default client")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import osimport timeimport stringimport randomimport asyncioimport aiofilesimport datetime
from FileStream.utils.broadcast_helper import send_msgfrom FileStream.utils.database import Databasefrom FileStream.bot import FileStreamfrom FileStream.server.exceptions import FIleNotFoundfrom FileStream.config import Telegram, Serverfrom pyrogram import filters, Clientfrom pyrogram.types import Messagefrom pyrogram.enums.parse_mode import ParseMode
db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)broadcast_ids = {}
@FileStream.on_message(filters.command("status") & filters.private & filters.user(Telegram.OWNER_ID))async def sts(c: Client, m: Message): await m.reply_text(text=f"""**Total Users in DB:** `{await db.total_users_count()}`**Banned Users in DB:** `{await db.total_banned_users_count()}`**Total Links Generated: ** `{await db.total_files()}`""" , parse_mode=ParseMode.MARKDOWN, quote=True)
@FileStream.on_message(filters.command("ban") & filters.private & filters.user(Telegram.OWNER_ID))async def sts(b, m: Message): id = m.text.split("/ban ")[-1] if not await db.is_user_banned(int(id)): try: await db.ban_user(int(id)) await db.delete_user(int(id)) await m.reply_text(text=f"`{id}`** is Banned** ", parse_mode=ParseMode.MARKDOWN, quote=True) if not str(id).startswith('-100'): await b.send_message( chat_id=id, text="**Your Banned to Use The Bot**", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True ) except Exception as e: await m.reply_text(text=f"**something went wrong: {e}** ", parse_mode=ParseMode.MARKDOWN, quote=True) else: await m.reply_text(text=f"`{id}`** is Already Banned** ", parse_mode=ParseMode.MARKDOWN, quote=True)
@FileStream.on_message(filters.command("unban") & filters.private & filters.user(Telegram.OWNER_ID))async def sts(b, m: Message): id = m.text.split("/unban ")[-1] if await db.is_user_banned(int(id)): try: await db.unban_user(int(id)) await m.reply_text(text=f"`{id}`** is Unbanned** ", parse_mode=ParseMode.MARKDOWN, quote=True) if not str(id).startswith('-100'): await b.send_message( chat_id=id, text="**Your Unbanned now Use can use The Bot**", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True ) except Exception as e: await m.reply_text(text=f"** something went wrong: {e}**", parse_mode=ParseMode.MARKDOWN, quote=True) else: await m.reply_text(text=f"`{id}`** is not Banned** ", parse_mode=ParseMode.MARKDOWN, quote=True)
@FileStream.on_message(filters.command("broadcast") & filters.private & filters.user(Telegram.OWNER_ID) & filters.reply)async def broadcast_(c, m): all_users = await db.get_all_users() broadcast_msg = m.reply_to_message while True: broadcast_id = ''.join([random.choice(string.ascii_letters) for i in range(3)]) if not broadcast_ids.get(broadcast_id): break out = await m.reply_text( text=f"Broadcast initiated! You will be notified with log file when all the users are notified." ) start_time = time.time() total_users = await db.total_users_count() done = 0 failed = 0 success = 0 broadcast_ids[broadcast_id] = dict( total=total_users, current=done, failed=failed, success=success ) async with aiofiles.open('broadcast.txt', 'w') as broadcast_log_file: async for user in all_users: sts, msg = await send_msg( user_id=int(user['id']), message=broadcast_msg ) if msg is not None: await broadcast_log_file.write(msg) if sts == 200: success += 1 else: failed += 1 if sts == 400: await db.delete_user(user['id']) done += 1 if broadcast_ids.get(broadcast_id) is None: break else: broadcast_ids[broadcast_id].update( dict( current=done, failed=failed, success=success ) ) try: await out.edit_text(f"Broadcast Status\n\ncurrent: {done}\nfailed:{failed}\nsuccess: {success}") except: pass if broadcast_ids.get(broadcast_id): broadcast_ids.pop(broadcast_id) completed_in = datetime.timedelta(seconds=int(time.time() - start_time)) await asyncio.sleep(3) await out.delete() if failed == 0: await m.reply_text( text=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", quote=True ) else: await m.reply_document( document='broadcast.txt', caption=f"broadcast completed in `{completed_in}`\n\nTotal users {total_users}.\nTotal done {done}, {success} success and {failed} failed.", quote=True ) os.remove('broadcast.txt')
@FileStream.on_message(filters.command("del") & filters.private & filters.user(Telegram.OWNER_ID))async def sts(c: Client, m: Message): file_id = m.text.split(" ")[-1] try: file_info = await db.get_file(file_id) except FIleNotFound: await m.reply_text( text=f"**ꜰɪʟᴇ ᴀʟʀᴇᴀᴅʏ ᴅᴇʟᴇᴛᴇᴅ**", quote=True ) return await db.delete_one_file(file_info['_id']) await db.count_links(file_info['user_id'], "-") await m.reply_text( text=f"**Fɪʟᴇ Dᴇʟᴇᴛᴇᴅ Sᴜᴄᴄᴇssғᴜʟʟʏ !** ", quote=True )
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198import datetimeimport mathfrom FileStream import __version__from FileStream.bot import FileStreamfrom FileStream.config import Telegram, Serverfrom FileStream.utils.translation import LANG, BUTTONfrom FileStream.utils.bot_utils import gen_linkfrom FileStream.utils.database import Databasefrom FileStream.utils.human_readable import humanbytesfrom FileStream.server.exceptions import FIleNotFoundfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQueryfrom pyrogram.file_id import FileId, FileType, PHOTO_TYPESfrom pyrogram.enums.parse_mode import ParseModedb = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
#---------------------[ START CMD ]---------------------#@FileStream.on_callback_query()async def cb_data(bot, update: CallbackQuery): usr_cmd = update.data.split("_") if usr_cmd[0] == "home": await update.message.edit_text( text=LANG.START_TEXT.format(update.from_user.mention, FileStream.username), disable_web_page_preview=True, reply_markup=BUTTON.START_BUTTONS ) elif usr_cmd[0] == "help": await update.message.edit_text( text=LANG.HELP_TEXT.format(Telegram.OWNER_ID), disable_web_page_preview=True, reply_markup=BUTTON.HELP_BUTTONS ) elif usr_cmd[0] == "about": await update.message.edit_text( text=LANG.ABOUT_TEXT.format(FileStream.fname, __version__), disable_web_page_preview=True, reply_markup=BUTTON.ABOUT_BUTTONS )
#---------------------[ MY FILES CMD ]---------------------#
elif usr_cmd[0] == "N/A": await update.answer("N/A", True) elif usr_cmd[0] == "close": await update.message.delete() elif usr_cmd[0] == "msgdelete": await update.message.edit_caption( caption= "**Cᴏɴғɪʀᴍ ʏᴏᴜ ᴡᴀɴᴛ ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴛʜᴇ Fɪʟᴇ**\n\n", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("ʏᴇs", callback_data=f"msgdelyes_{usr_cmd[1]}_{usr_cmd[2]}"), InlineKeyboardButton("ɴᴏ", callback_data=f"myfile_{usr_cmd[1]}_{usr_cmd[2]}")]]) ) elif usr_cmd[0] == "msgdelyes": await delete_user_file(usr_cmd[1], int(usr_cmd[2]), update) return elif usr_cmd[0] == "msgdelpvt": await update.message.edit_caption( caption= "**Cᴏɴғɪʀᴍ ʏᴏᴜ ᴡᴀɴᴛ ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴛʜᴇ Fɪʟᴇ**\n\n", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("ʏᴇs", callback_data=f"msgdelpvtyes_{usr_cmd[1]}"), InlineKeyboardButton("ɴᴏ", callback_data=f"mainstream_{usr_cmd[1]}")]]) ) elif usr_cmd[0] == "msgdelpvtyes": await delete_user_filex(usr_cmd[1], update) return
elif usr_cmd[0] == "mainstream": _id = usr_cmd[1] reply_markup, stream_text = await gen_link(_id=_id) await update.message.edit_text( text=stream_text, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=reply_markup, )
elif usr_cmd[0] == "userfiles": file_list, total_files = await gen_file_list_button(int(usr_cmd[1]), update.from_user.id) await update.message.edit_caption( caption="Total files: {}".format(total_files), reply_markup=InlineKeyboardMarkup(file_list) ) elif usr_cmd[0] == "myfile": await gen_file_menu(usr_cmd[1], usr_cmd[2], update) return elif usr_cmd[0] == "sendfile": myfile = await db.get_file(usr_cmd[1]) file_name = myfile['file_name'] await update.answer(f"Sending File {file_name}") await update.message.reply_cached_media(myfile['file_id'], caption=f'**{file_name}**') else: await update.message.delete()
#---------------------[ MY FILES FUNC ]---------------------#
async def gen_file_list_button(file_list_no: int, user_id: int):
file_range=[file_list_no*10-10+1, file_list_no*10] user_files, total_files=await db.find_files(user_id, file_range)
file_list=[] async for x in user_files: file_list.append([InlineKeyboardButton(x["file_name"], callback_data=f"myfile_{x['_id']}_{file_list_no}")]) if total_files > 10: file_list.append( [InlineKeyboardButton("◄", callback_data="{}".format("userfiles_"+str(file_list_no-1) if file_list_no > 1 else 'N/A')), InlineKeyboardButton(f"{file_list_no}/{math.ceil(total_files/10)}", callback_data="N/A"), InlineKeyboardButton("►", callback_data="{}".format("userfiles_"+str(file_list_no+1) if total_files > file_list_no*10 else 'N/A'))] ) if not file_list: file_list.append( [InlineKeyboardButton("ᴇᴍᴘᴛʏ", callback_data="N/A")]) file_list.append([InlineKeyboardButton("ᴄʟᴏsᴇ", callback_data="close")]) return file_list, total_files
async def gen_file_menu(_id, file_list_no, update: CallbackQuery): try: myfile_info=await db.get_file(_id) except FIleNotFound: await update.answer("File Not Found") return
file_id=FileId.decode(myfile_info['file_id'])
if file_id.file_type in PHOTO_TYPES: file_type = "Image" elif file_id.file_type == FileType.VOICE: file_type = "Voice" elif file_id.file_type in (FileType.VIDEO, FileType.ANIMATION, FileType.VIDEO_NOTE): file_type = "Video" elif file_id.file_type == FileType.DOCUMENT: file_type = "Document" elif file_id.file_type == FileType.STICKER: file_type = "Sticker" elif file_id.file_type == FileType.AUDIO: file_type = "Audio" else: file_type = "Unknown"
page_link = f"{Server.URL}watch/{myfile_info['_id']}" stream_link = f"{Server.URL}dl/{myfile_info['_id']}" if "video" in file_type.lower(): MYFILES_BUTTONS = InlineKeyboardMarkup( [ [InlineKeyboardButton("sᴛʀᴇᴀᴍ", url=page_link), InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)], [InlineKeyboardButton("ɢᴇᴛ ғɪʟᴇ", callback_data=f"sendfile_{myfile_info['_id']}"), InlineKeyboardButton("ʀᴇᴠᴏᴋᴇ ғɪʟᴇ", callback_data=f"msgdelete_{myfile_info['_id']}_{file_list_no}")], [InlineKeyboardButton("ʙᴀᴄᴋ", callback_data="userfiles_{}".format(file_list_no))] ] ) else: MYFILES_BUTTONS = InlineKeyboardMarkup( [ [InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)], [InlineKeyboardButton("ɢᴇᴛ ғɪʟᴇ", callback_data=f"sendfile_{myfile_info['_id']}"), InlineKeyboardButton("ʀᴇᴠᴏᴋᴇ ғɪʟᴇ", callback_data=f"msgdelete_{myfile_info['_id']}_{file_list_no}")], [InlineKeyboardButton("ʙᴀᴄᴋ", callback_data="userfiles_{}".format(file_list_no))] ] )
TiMe = myfile_info['time'] if type(TiMe) == float: date = datetime.datetime.fromtimestamp(TiMe) await update.edit_message_caption( caption="**File Name :** `{}`\n**File Size :** `{}`\n**File Type :** `{}`\n**Created On :** `{}`".format(myfile_info['file_name'], humanbytes(int(myfile_info['file_size'])), file_type, TiMe if isinstance(TiMe,str) else date.date()), reply_markup=MYFILES_BUTTONS )
async def delete_user_file(_id, file_list_no: int, update:CallbackQuery):
try: myfile_info=await db.get_file(_id) except FIleNotFound: await update.answer("File Already Deleted") return
await db.delete_one_file(myfile_info['_id']) await db.count_links(update.from_user.id, "-") await update.message.edit_caption( caption= "**Fɪʟᴇ Dᴇʟᴇᴛᴇᴅ Sᴜᴄᴄᴇssғᴜʟʟʏ !**" + update.message.caption.replace("Cᴏɴғɪʀᴍ ʏᴏᴜ ᴡᴀɴᴛ ᴛᴏ ᴅᴇʟᴇᴛᴇ ᴛʜᴇ Fɪʟᴇ", ""), reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("ʙᴀᴄᴋ", callback_data=f"userfiles_1")]]) )
async def delete_user_filex(_id, update:CallbackQuery):
try: myfile_info=await db.get_file(_id) except FIleNotFound: await update.answer("File Already Deleted") return
await db.delete_one_file(myfile_info['_id']) await db.count_links(update.from_user.id, "-") await update.message.edit_caption( caption= "**Fɪʟᴇ Dᴇʟᴇᴛᴇᴅ Sᴜᴄᴄᴇssғᴜʟʟʏ !**\n\n", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("ᴄʟᴏsᴇ", callback_data=f"close")]]) )
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149import loggingimport mathfrom FileStream import __version__from FileStream.bot import FileStreamfrom FileStream.server.exceptions import FIleNotFoundfrom FileStream.utils.bot_utils import gen_linkx, verify_userfrom FileStream.config import Telegramfrom FileStream.utils.database import Databasefrom FileStream.utils.translation import LANG, BUTTONfrom pyrogram import filters, Clientfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Messagefrom pyrogram.enums.parse_mode import ParseModeimport asyncio
db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
@FileStream.on_message(filters.command('start') & filters.private)async def start(bot: Client, message: Message): if not await verify_user(bot, message): return usr_cmd = message.text.split("_")[-1]
if usr_cmd == "/start": if Telegram.START_PIC: await message.reply_photo( photo=Telegram.START_PIC, caption=LANG.START_TEXT.format(message.from_user.mention, FileStream.username), parse_mode=ParseMode.HTML, reply_markup=BUTTON.START_BUTTONS ) else: await message.reply_text( text=LANG.START_TEXT.format(message.from_user.mention, FileStream.username), parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=BUTTON.START_BUTTONS ) else: if "stream_" in message.text: try: file_check = await db.get_file(usr_cmd) file_id = str(file_check['_id']) if file_id == usr_cmd: reply_markup, stream_text = await gen_linkx(m=message, _id=file_id, name=[FileStream.username, FileStream.fname]) await message.reply_text( text=stream_text, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=reply_markup, quote=True )
except FIleNotFound as e: await message.reply_text("File Not Found") except Exception as e: await message.reply_text("Something Went Wrong") logging.error(e)
elif "file_" in message.text: try: file_check = await db.get_file(usr_cmd) db_id = str(file_check['_id']) file_id = file_check['file_id'] file_name = file_check['file_name'] if db_id == usr_cmd: filex = await message.reply_cached_media(file_id=file_id, caption=f'**{file_name}**') await asyncio.sleep(3600) try: await filex.delete() await message.delete() except Exception: pass
except FIleNotFound as e: await message.reply_text("**File Not Found**") except Exception as e: await message.reply_text("Something Went Wrong") logging.error(e)
else: await message.reply_text(f"**Invalid Command**")
@FileStream.on_message(filters.private & filters.command(["about"]))async def start(bot, message): if not await verify_user(bot, message): return if Telegram.START_PIC: await message.reply_photo( photo=Telegram.START_PIC, caption=LANG.ABOUT_TEXT.format(FileStream.fname, __version__), parse_mode=ParseMode.HTML, reply_markup=BUTTON.ABOUT_BUTTONS ) else: await message.reply_text( text=LANG.ABOUT_TEXT.format(FileStream.fname, __version__), disable_web_page_preview=True, reply_markup=BUTTON.ABOUT_BUTTONS )
@FileStream.on_message((filters.command('help')) & filters.private)async def help_handler(bot, message): if not await verify_user(bot, message): return if Telegram.START_PIC: await message.reply_photo( photo=Telegram.START_PIC, caption=LANG.HELP_TEXT.format(Telegram.OWNER_ID), parse_mode=ParseMode.HTML, reply_markup=BUTTON.HELP_BUTTONS ) else: await message.reply_text( text=LANG.HELP_TEXT.format(Telegram.OWNER_ID), parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=BUTTON.HELP_BUTTONS )
# ---------------------------------------------------------------------------------------------------
@FileStream.on_message(filters.command('files') & filters.private)async def my_files(bot: Client, message: Message): if not await verify_user(bot, message): return user_files, total_files = await db.find_files(message.from_user.id, [1, 10])
file_list = [] async for x in user_files: file_list.append([InlineKeyboardButton(x["file_name"], callback_data=f"myfile_{x['_id']}_{1}")]) if total_files > 10: file_list.append( [ InlineKeyboardButton("◄", callback_data="N/A"), InlineKeyboardButton(f"1/{math.ceil(total_files / 10)}", callback_data="N/A"), InlineKeyboardButton("►", callback_data="userfiles_2") ], ) if not file_list: file_list.append( [InlineKeyboardButton("ᴇᴍᴘᴛʏ", callback_data="N/A")], ) file_list.append([InlineKeyboardButton("ᴄʟᴏsᴇ", callback_data="close")]) await message.reply_photo(photo=Telegram.FILE_PIC, caption="Total files: {}".format(total_files), reply_markup=InlineKeyboardMarkup(file_list))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
import asynciofrom FileStream.bot import FileStream, multi_clientsfrom FileStream.utils.bot_utils import is_user_banned, is_user_exist, is_user_joined, gen_link, is_channel_banned, is_channel_exist, is_user_authorizedfrom FileStream.utils.database import Databasefrom FileStream.utils.file_properties import get_file_ids, get_file_infofrom FileStream.config import Telegramfrom pyrogram import filters, Clientfrom pyrogram.errors import FloodWaitfrom pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButtonfrom pyrogram.enums.parse_mode import ParseModedb = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
@FileStream.on_message( filters.private & ( filters.document | filters.video | filters.video_note | filters.audio | filters.voice | filters.animation | filters.photo ), group=4,)async def private_receive_handler(bot: Client, message: Message): if not await is_user_authorized(message): return if await is_user_banned(message): return
await is_user_exist(bot, message) if Telegram.FORCE_SUB: if not await is_user_joined(bot, message): return try: inserted_id = await db.add_file(get_file_info(message)) await get_file_ids(False, inserted_id, multi_clients, message) reply_markup, stream_text = await gen_link(_id=inserted_id) await message.reply_text( text=stream_text, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=reply_markup, quote=True ) except FloodWait as e: print(f"Sleeping for {str(e.value)}s") await asyncio.sleep(e.value) await bot.send_message(chat_id=Telegram.ULOG_CHANNEL, text=f"Gᴏᴛ FʟᴏᴏᴅWᴀɪᴛ ᴏғ {str(e.value)}s ғʀᴏᴍ [{message.from_user.first_name}](tg://user?id={message.from_user.id})\n\n**ᴜsᴇʀ ɪᴅ :** `{str(message.from_user.id)}`", disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)
@FileStream.on_message( filters.channel & ~filters.forwarded & ~filters.media_group & ( filters.document | filters.video | filters.video_note | filters.audio | filters.voice | filters.photo ))async def channel_receive_handler(bot: Client, message: Message): if await is_channel_banned(bot, message): return await is_channel_exist(bot, message)
try: inserted_id = await db.add_file(get_file_info(message)) await get_file_ids(False, inserted_id, multi_clients, message) reply_markup, stream_link = await gen_link(_id=inserted_id) await bot.edit_message_reply_markup( chat_id=message.chat.id, message_id=message.id, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Dᴏᴡɴʟᴏᴀᴅ ʟɪɴᴋ 📥", url=f"https://t.me/{FileStream.username}?start=stream_{str(inserted_id)}")]]) )
except FloodWait as w: print(f"Sleeping for {str(w.x)}s") await asyncio.sleep(w.x) await bot.send_message(chat_id=Telegram.ULOG_CHANNEL, text=f"ɢᴏᴛ ғʟᴏᴏᴅᴡᴀɪᴛ ᴏғ {str(w.x)}s ғʀᴏᴍ {message.chat.title}\n\n**ᴄʜᴀɴɴᴇʟ ɪᴅ :** `{str(message.chat.id)}`", disable_web_page_preview=True) except Exception as e: await bot.send_message(chat_id=Telegram.ULOG_CHANNEL, text=f"**#EʀʀᴏʀTʀᴀᴄᴋᴇʙᴀᴄᴋ:** `{e}`", disable_web_page_preview=True) print(f"Cᴀɴ'ᴛ Eᴅɪᴛ Bʀᴏᴀᴅᴄᴀsᴛ Mᴇssᴀɢᴇ!\nEʀʀᴏʀ: **Gɪᴠᴇ ᴍᴇ ᴇᴅɪᴛ ᴘᴇʀᴍɪssɪᴏɴ ɪɴ ᴜᴘᴅᴀᴛᴇs ᴀɴᴅ ʙɪɴ Cʜᴀɴɴᴇʟ!{e}**")
1234567891011121314151617181920212223242526272829303132333435363738394041from os import environ as envfrom dotenv import load_dotenv
load_dotenv()
class Telegram: API_ID = int(env.get("API_ID")) API_HASH = str(env.get("API_HASH")) BOT_TOKEN = str(env.get("BOT_TOKEN")) OWNER_ID = int(env.get('OWNER_ID', '7978482443')) WORKERS = int(env.get("WORKERS", "6")) # 6 workers = 6 commands at once DATABASE_URL = str(env.get('DATABASE_URL')) UPDATES_CHANNEL = str(env.get('UPDATES_CHANNEL', "Telegram")) SESSION_NAME = str(env.get('SESSION_NAME', 'FileStream')) FORCE_SUB_ID = env.get('FORCE_SUB_ID', None) FORCE_SUB = env.get('FORCE_UPDATES_CHANNEL', False) FORCE_SUB = True if str(FORCE_SUB).lower() == "true" else False SLEEP_THRESHOLD = int(env.get("SLEEP_THRESHOLD", "60")) FILE_PIC = env.get('FILE_PIC', "https://graph.org/file/5bb9935be0229adf98b73.jpg") START_PIC = env.get('START_PIC', "https://graph.org/file/290af25276fa34fa8f0aa.jpg") VERIFY_PIC = env.get('VERIFY_PIC', "https://graph.org/file/736e21cc0efa4d8c2a0e4.jpg") MULTI_CLIENT = False FLOG_CHANNEL = int(env.get("FLOG_CHANNEL", None)) # Logs channel for file logs ULOG_CHANNEL = int(env.get("ULOG_CHANNEL", None)) # Logs channel for user logs MODE = env.get("MODE", "primary") SECONDARY = True if MODE.lower() == "secondary" else False AUTH_USERS = list(set(int(x) for x in str(env.get("AUTH_USERS", "")).split()))
class Server: PORT = int(env.get("PORT", 8080)) BIND_ADDRESS = str(env.get("BIND_ADDRESS", "0.0.0.0")) PING_INTERVAL = int(env.get("PING_INTERVAL", "1200")) HAS_SSL = str(env.get("HAS_SSL", "0").lower()) in ("1", "true", "t", "yes", "y") NO_PORT = str(env.get("NO_PORT", "0").lower()) in ("1", "true", "t", "yes", "y") FQDN = str(env.get("FQDN", BIND_ADDRESS)) URL = "http{}://{}{}/".format( "s" if HAS_SSL else "", FQDN, "" if NO_PORT else ":" + str(PORT) )
1234567from aiohttp import webfrom .stream_routes import routes
def web_server(): web_app = web.Application(client_max_size=30000000) web_app.add_routes(routes) return web_app12345class InvalidHash(Exception): message = "Invalid hash"
class FIleNotFound(Exception): message = "File not found"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import timeimport mathimport loggingimport mimetypesimport tracebackfrom aiohttp import webfrom aiohttp.http_exceptions import BadStatusLinefrom FileStream.bot import multi_clients, work_loads, FileStreamfrom FileStream.config import Telegram, Serverfrom FileStream.server.exceptions import FIleNotFound, InvalidHashfrom FileStream import utils, StartTime, __version__from FileStream.utils.render_template import render_page
routes = web.RouteTableDef()
@routes.get("/status", allow_head=True)async def root_route_handler(_): return web.json_response( { "server_status": "running", "uptime": utils.get_readable_time(time.time() - StartTime), "telegram_bot": "@" + FileStream.username, "connected_bots": len(multi_clients), "loads": dict( ("bot" + str(c + 1), l) for c, (_, l) in enumerate( sorted(work_loads.items(), key=lambda x: x[1], reverse=True) ) ), "version": __version__, } )
@routes.get("/watch/{path}", allow_head=True)async def stream_handler(request: web.Request): try: path = request.match_info["path"] return web.Response(text=await render_page(path), content_type='text/html') except InvalidHash as e: raise web.HTTPForbidden(text=e.message) except FIleNotFound as e: raise web.HTTPNotFound(text=e.message) except (AttributeError, BadStatusLine, ConnectionResetError): pass
@routes.get("/dl/{path}", allow_head=True)async def stream_handler(request: web.Request): try: path = request.match_info["path"] return await media_streamer(request, path) except InvalidHash as e: raise web.HTTPForbidden(text=e.message) except FIleNotFound as e: raise web.HTTPNotFound(text=e.message) except (AttributeError, BadStatusLine, ConnectionResetError): pass except Exception as e: traceback.print_exc() logging.critical(e.with_traceback(None)) logging.debug(traceback.format_exc()) raise web.HTTPInternalServerError(text=str(e))
class_cache = {}
async def media_streamer(request: web.Request, db_id: str): range_header = request.headers.get("Range", 0) index = min(work_loads, key=work_loads.get) faster_client = multi_clients[index] if Telegram.MULTI_CLIENT: logging.info(f"Client {index} is now serving {request.headers.get('X-FORWARDED-FOR',request.remote)}")
if faster_client in class_cache: tg_connect = class_cache[faster_client] logging.debug(f"Using cached ByteStreamer object for client {index}") else: logging.debug(f"Creating new ByteStreamer object for client {index}") tg_connect = utils.ByteStreamer(faster_client) class_cache[faster_client] = tg_connect logging.debug("before calling get_file_properties") file_id = await tg_connect.get_file_properties(db_id, multi_clients) logging.debug("after calling get_file_properties") file_size = file_id.file_size
if range_header: from_bytes, until_bytes = range_header.replace("bytes=", "").split("-") from_bytes = int(from_bytes) until_bytes = int(until_bytes) if until_bytes else file_size - 1 else: from_bytes = request.http_range.start or 0 until_bytes = (request.http_range.stop or file_size) - 1
if (until_bytes > file_size) or (from_bytes < 0) or (until_bytes < from_bytes): return web.Response( status=416, body="416: Range not satisfiable", headers={"Content-Range": f"bytes */{file_size}"}, )
chunk_size = 1024 * 1024 until_bytes = min(until_bytes, file_size - 1)
offset = from_bytes - (from_bytes % chunk_size) first_part_cut = from_bytes - offset last_part_cut = until_bytes % chunk_size + 1
req_length = until_bytes - from_bytes + 1 part_count = math.ceil(until_bytes / chunk_size) - math.floor(offset / chunk_size) body = tg_connect.yield_file( file_id, index, offset, first_part_cut, last_part_cut, part_count, chunk_size )
mime_type = file_id.mime_type file_name = utils.get_name(file_id) disposition = "attachment"
if not mime_type: mime_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
# if "video/" in mime_type or "audio/" in mime_type: # disposition = "inline"
return web.Response( status=206 if range_header else 200, body=body, headers={ "Content-Type": f"{mime_type}", "Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}", "Content-Length": str(req_length), "Content-Disposition": f'{disposition}; filename="{file_name}"', "Accept-Ranges": "bytes", }, )1234567891011121314151617181920212223242526272829303132333435363738394041424344<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta property="og:image" content="https://www.flaticon.com/premium-icon/icons/svg/2626/2626281.svg" itemprop="thumbnailUrl"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{file_name}}</title> <link rel="stylesheet" type='text/css' href="https://drive.google.com/uc?export=view&id=1pVLG4gZy7jdow3sO-wFS06aP_A9QX0O6"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Delius"></head>
<body class='cyber'> <header> <div class="toogle"></div> <div id="file-name" class="cyber"> {{file_name}} </div> </header>
<div class="container"> <a href="{{file_url}}"> <button class="cybr-btn"> Download <span aria-hidden>_</span> <span aria-hidden class="cybr-btn__glitch">_404 Error</span> <span aria-hidden class="cybr-btn__tag">_%s</span> </button> </a> </div> <script> const body = document.querySelector('body'); const title = document.querySelector('#file-name'); const footer = document.querySelector('footer'); const toogle = document.querySelector('.toogle'); toogle.onclick = () => { body.classList.toggle('dark') footer.classList.toggle('dark') title.classList.toggle('dark') } </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>FileStreamBot | {{file_name}}</title> <link rel="icon" href="https://i.ibb.co/Hh4kF2b/icon.png" type="image/x-icon"> <link rel="shortcut icon" href="https://i.ibb.co/Hh4kF2b/icon.png" type="image/x-icon"> <link rel="stylesheet" href="https://unpkg.com/sheryjs/dist/Shery.css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/proavipatil/data@main/fs/src/style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/proavipatil/data@main/fs/src/plyr.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@500;700&display=swap" rel="stylesheet"> <script src="https://cdn.tailwindcss.com"></script>
</head>
<body> <nav> <div class="nleft"> <a href="#"> <h3 id="heading" style="z-index: 100;" class="magnet title">FILE STREAM</h3> </a> </div> <div class="nryt"> <a class="home-btn magnet" href="#main" onclick="toggleWidthnav(this)">HOME</a>
<a href="#abtus" class="about-btn magnet" onclick="toggleWidthnav(this)">ABOUT</a> </div> </nav> <center> <div class="about-nav"> <a href="#abtus" class="wlcm magnet" onclick="toggleWidth(this)">WELCOME</a> <a href="#channels" class="abt-chnl magnet" onclick="toggleWidth(this)">CHANNELS</a> <a href="#contact" class="magnet contact-btn" onclick="toggleWidth(this)">CONTACT</a> </div> </center>
<div class="outer"> <div class="inner"> <div class="main" id="main"> <video id="player" class="player" src="{{file_url}}" type="video/mp4" playsinline controls width="100%"></video> <div class="player"></div> <div class="file-name"> <h4 style="display: inline;">File Name: </h4> <p style="display: inline;" id="myDiv">{{file_name}}</p><br> <h4 style="display: inline;">File Size: </h4> <p style="display: inline;">{{file_size}}</p> </div> <div class="downloadBtn"> <button class="magnet" onclick="streamDownload()"> <img style="height: 30px;" src="https://i.ibb.co/RjzYttX/dl.png" alt="">download video </button> <button class="magnet" onclick="copyStreamLink()"> <img src="https://i.ibb.co/CM4Y586/link.png" alt="Copy Link">copy link </button> <button class="magnet" onclick="vlc_player()"> <img src="https://i.ibb.co/px6fQs1/vlc.png" alt="">watch in VLC PLAYER </button> <button class="magnet" onclick="mx_player()"> <img src="https://i.ibb.co/41WvtQ3/mx.png" alt="">watch in MX PLAYER </button> <button class="magnet" onclick="n_player()"> <img src="https://i.ibb.co/Hd2dS4t/nPlayer.png" alt="">watch in nPlayer </button> </div>
</div> <div class="abt"> <div class="about"> <div class="about-dets">
<div class="abt-sec" id="abtus" style="padding: 160px 30px;"> <h1 style="text-align: center;">WELCOME TO OUR <Span>FILE STREAM</Span> BOT</h1> <p style="text-align: center; line-height: 2;word-spacing: 2px; letter-spacing: 0.8px;"> This is a Telegram Bot to Stream <span>Movies</span> and <span>Series</span> directly on Telegram. You can also <span>download</span> them if you want. This bot is developed by <a href="https://github.com/AviPatilPro"><span style="font-weight: 700;">Avi</span></a> <br><br>If you like this bot, then don't forget to share it with your friends and family. </p> </div>
<div class="abt-sec" id="channels"> <h1>JOIN OUR <span>TELEGRAM</span> CHANNELS</h1> <div class="links chnl-link"> <a class="magnet" href="https://t.me/CheapieDeals"> <button>CHEAP DEALS</button> </a> <a class="magnet" href="https://t.me/FilmyPixel"> <button>FILMYPIXEL</button> </a> <a class="magnet" href="https://t.me/PostersZone"> <button>POSTERS ZONE</button> </a> <a class="magnet" href="https://t.me/EpitomeQuality"> <button>EPITOME QUALITY</button> </a> </div> </div>
<div class="abt-sec" id="contact"> <p style="text-align: center;">Report Bugs and Contact us on Telegram Below</p> <div class="links contact"> <a href="https://t.me/AvishkarPatil"> <button>CONTACT</button> </a> </div> </div>
</div> </div> </div> </div> <footer> <center>
<div class="movie-cont"> <div class="movieSug"> <div class="movieDets">
</div> <div class="movieimg"> <img src=""> </div> </div> <div class="low-width-movie-dets"> <div class="movieStsBar"> <div class="movieDets-mini">
</div> </div> </div> <button class="ranMovBtn" onclick="getDets()">Get More Movies Suggestion</button> </div>
</center>
<center> <div class="copyright"> <h5 class="text-center">Copyright © 2024 <a href="https://github.com/AviPatilPro"><span style="font-weight: 700;">Avishkar Patil</span></a>. All Rights Reserved.</h5> </div> </center> </footer> </div></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.155.0/three.min.js"></script><script src="https://cdn.jsdelivr.net/gh/automat/controlkit.js@master/bin/controlKit.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sheryjs/dist/Shery.js"></script><script> document.addEventListener("DOMContentLoaded", function () { const uncopyableElement = document.querySelector(".uncopyable");
uncopyableElement.addEventListener("selectstart", function (event) { event.preventDefault(); }); });</script><script src="https://cdn.plyr.io/3.6.9/plyr.js"></script><script src="https://proavipatil.github.io/data/fs/src/script.js"></script>
</html>123from .time_format import get_readable_timefrom .file_properties import get_name, get_file_idsfrom .custom_dl import ByteStreamer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216from pyrogram.errors import UserNotParticipant, FloodWaitfrom pyrogram.enums.parse_mode import ParseModefrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Messagefrom FileStream.utils.translation import LANGfrom FileStream.utils.database import Databasefrom FileStream.utils.human_readable import humanbytesfrom FileStream.config import Telegram, Serverfrom FileStream.bot import FileStreamimport asynciofrom typing import ( Union)
db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
async def get_invite_link(bot, chat_id: Union[str, int]): try: invite_link = await bot.create_chat_invite_link(chat_id=chat_id) return invite_link except FloodWait as e: print(f"Sleep of {e.value}s caused by FloodWait ...") await asyncio.sleep(e.value) return await get_invite_link(bot, chat_id)
async def is_user_joined(bot, message: Message): if Telegram.FORCE_SUB_ID and Telegram.FORCE_SUB_ID.startswith("-100"): channel_chat_id = int(Telegram.FORCE_SUB_ID) # When id startswith with -100 elif Telegram.FORCE_SUB_ID and (not Telegram.FORCE_SUB_ID.startswith("-100")): channel_chat_id = Telegram.FORCE_SUB_ID # When id not startswith -100 else: return 200 try: user = await bot.get_chat_member(chat_id=channel_chat_id, user_id=message.from_user.id) if user.status == "BANNED": await message.reply_text( text=LANG.BAN_TEXT.format(Telegram.OWNER_ID), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True ) return False except UserNotParticipant: invite_link = await get_invite_link(bot, chat_id=channel_chat_id) if Telegram.VERIFY_PIC: ver = await message.reply_photo( photo=Telegram.VERIFY_PIC, caption="<i>Jᴏɪɴ ᴍʏ ᴜᴘᴅᴀᴛᴇ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴜsᴇ ᴍᴇ 🔐</i>", parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton("❆ Jᴏɪɴ Oᴜʀ Cʜᴀɴɴᴇʟ ❆", url=invite_link.invite_link) ]] ) ) else: ver = await message.reply_text( text = "<i>Jᴏɪɴ ᴍʏ ᴜᴘᴅᴀᴛᴇ ᴄʜᴀɴɴᴇʟ ᴛᴏ ᴜsᴇ ᴍᴇ 🔐</i>", reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton("❆ Jᴏɪɴ Oᴜʀ Cʜᴀɴɴᴇʟ ❆", url=invite_link.invite_link) ]] ), parse_mode=ParseMode.HTML ) await asyncio.sleep(30) try: await ver.delete() await message.delete() except Exception: pass return False except Exception: await message.reply_text( text = f"<i>Sᴏᴍᴇᴛʜɪɴɢ ᴡʀᴏɴɢ ᴄᴏɴᴛᴀᴄᴛ ᴍʏ ᴅᴇᴠᴇʟᴏᴘᴇʀ</i> <b><a href='https://t.me/{Telegram.UPDATES_CHANNEL}'>[ ᴄʟɪᴄᴋ ʜᴇʀᴇ ]</a></b>", parse_mode=ParseMode.HTML, disable_web_page_preview=True) return False return True
#---------------------[ PRIVATE GEN LINK + CALLBACK ]---------------------#
async def gen_link(_id): file_info = await db.get_file(_id) file_name = file_info['file_name'] file_size = humanbytes(file_info['file_size']) mime_type = file_info['mime_type']
page_link = f"{Server.URL}watch/{_id}" stream_link = f"{Server.URL}dl/{_id}" file_link = f"https://t.me/{FileStream.username}?start=file_{_id}"
if "video" in mime_type: stream_text = LANG.STREAM_TEXT.format(file_name, file_size, stream_link, page_link, file_link) reply_markup = InlineKeyboardMarkup( [ [InlineKeyboardButton("sᴛʀᴇᴀᴍ", url=page_link), InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)], [InlineKeyboardButton("ɢᴇᴛ ғɪʟᴇ", url=file_link), InlineKeyboardButton("ʀᴇᴠᴏᴋᴇ ғɪʟᴇ", callback_data=f"msgdelpvt_{_id}")], [InlineKeyboardButton("ᴄʟᴏsᴇ", callback_data="close")] ] ) else: stream_text = LANG.STREAM_TEXT_X.format(file_name, file_size, stream_link, file_link) reply_markup = InlineKeyboardMarkup( [ [InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)], [InlineKeyboardButton("ɢᴇᴛ ғɪʟᴇ", url=file_link), InlineKeyboardButton("ʀᴇᴠᴏᴋᴇ ғɪʟᴇ", callback_data=f"msgdelpvt_{_id}")], [InlineKeyboardButton("ᴄʟᴏsᴇ", callback_data="close")] ] ) return reply_markup, stream_text
#---------------------[ GEN STREAM LINKS FOR CHANNEL ]---------------------#
async def gen_linkx(m:Message , _id, name: list): file_info = await db.get_file(_id) file_name = file_info['file_name'] mime_type = file_info['mime_type'] file_size = humanbytes(file_info['file_size'])
page_link = f"{Server.URL}watch/{_id}" stream_link = f"{Server.URL}dl/{_id}" file_link = f"https://t.me/{FileStream.username}?start=file_{_id}"
if "video" in mime_type: stream_text= LANG.STREAM_TEXT_X.format(file_name, file_size, stream_link, page_link) reply_markup = InlineKeyboardMarkup( [ [InlineKeyboardButton("sᴛʀᴇᴀᴍ", url=page_link), InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)] ] ) else: stream_text= LANG.STREAM_TEXT_X.format(file_name, file_size, stream_link, file_link) reply_markup = InlineKeyboardMarkup( [ [InlineKeyboardButton("ᴅᴏᴡɴʟᴏᴀᴅ", url=stream_link)] ] ) return reply_markup, stream_text
#---------------------[ USER BANNED ]---------------------#
async def is_user_banned(message): if await db.is_user_banned(message.from_user.id): await message.reply_text( text=LANG.BAN_TEXT.format(Telegram.OWNER_ID), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True ) return True return False
#---------------------[ CHANNEL BANNED ]---------------------#
async def is_channel_banned(bot, message): if await db.is_user_banned(message.chat.id): await bot.edit_message_reply_markup( chat_id=message.chat.id, message_id=message.id, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(f"ᴄʜᴀɴɴᴇʟ ɪs ʙᴀɴɴᴇᴅ", callback_data="N/A")]]) ) return True return False
#---------------------[ USER AUTH ]---------------------#
async def is_user_authorized(message): if hasattr(Telegram, 'AUTH_USERS') and Telegram.AUTH_USERS: user_id = message.from_user.id
if user_id == Telegram.OWNER_ID: return True
if not (user_id in Telegram.AUTH_USERS): await message.reply_text( text="Yᴏᴜ ᴀʀᴇ ɴᴏᴛ ᴀᴜᴛʜᴏʀɪᴢᴇᴅ ᴛᴏ ᴜsᴇ ᴛʜɪs ʙᴏᴛ.", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True ) return False
return True
#---------------------[ USER EXIST ]---------------------#
async def is_user_exist(bot, message): if not bool(await db.get_user(message.from_user.id)): await db.add_user(message.from_user.id) await bot.send_message( Telegram.ULOG_CHANNEL, f"**#NᴇᴡUsᴇʀ**\n**⬩ ᴜsᴇʀ ɴᴀᴍᴇ :** [{message.from_user.first_name}](tg://user?id={message.from_user.id})\n**⬩ ᴜsᴇʀ ɪᴅ :** `{message.from_user.id}`" )
async def is_channel_exist(bot, message): if not bool(await db.get_user(message.chat.id)): await db.add_user(message.chat.id) members = await bot.get_chat_members_count(message.chat.id) await bot.send_message( Telegram.ULOG_CHANNEL, f"**#NᴇᴡCʜᴀɴɴᴇʟ** \n**⬩ ᴄʜᴀᴛ ɴᴀᴍᴇ :** `{message.chat.title}`\n**⬩ ᴄʜᴀᴛ ɪᴅ :** `{message.chat.id}`\n**⬩ ᴛᴏᴛᴀʟ ᴍᴇᴍʙᴇʀs :** `{members}`" )
async def verify_user(bot, message): if not await is_user_authorized(message): return False
if await is_user_banned(message): return False
await is_user_exist(bot, message)
if Telegram.FORCE_SUB: if not await is_user_joined(bot, message): return False
return True12345678910111213141516171819import asyncioimport tracebackfrom pyrogram.errors import FloodWait, InputUserDeactivated, UserIsBlocked, PeerIdInvalid
async def send_msg(user_id, message): try: await message.copy(chat_id=user_id) return 200, None except FloodWait as e: await asyncio.sleep(e.value) return send_msg(user_id, message) except InputUserDeactivated: return 400, f"{user_id} : deactivated\n" except UserIsBlocked: return 400, f"{user_id} : blocked the bot\n" except PeerIdInvalid: return 400, f"{user_id} : user id invalid\n" except Exception as e: return 500, f"{user_id} : {traceback.format_exc()}\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214import asyncioimport loggingfrom typing import Dict, Unionfrom FileStream.bot import work_loadsfrom pyrogram import Client, utils, rawfrom .file_properties import get_file_idsfrom pyrogram.session import Session, Authfrom pyrogram.errors import AuthBytesInvalidfrom pyrogram.file_id import FileId, FileType, ThumbnailSourcefrom pyrogram.types import Message
class ByteStreamer: def __init__(self, client: Client): self.clean_timer = 30 * 60 self.client: Client = client self.cached_file_ids: Dict[str, FileId] = {} asyncio.create_task(self.clean_cache())
async def get_file_properties(self, db_id: str, multi_clients) -> FileId: """ Returns the properties of a media of a specific message in a FIleId class. if the properties are cached, then it'll return the cached results. or it'll generate the properties from the Message ID and cache them. """ if not db_id in self.cached_file_ids: logging.debug("Before Calling generate_file_properties") await self.generate_file_properties(db_id, multi_clients) logging.debug(f"Cached file properties for file with ID {db_id}") return self.cached_file_ids[db_id] async def generate_file_properties(self, db_id: str, multi_clients) -> FileId: """ Generates the properties of a media file on a specific message. returns ths properties in a FIleId class. """ logging.debug("Before calling get_file_ids") file_id = await get_file_ids(self.client, db_id, multi_clients, Message) logging.debug(f"Generated file ID and Unique ID for file with ID {db_id}") self.cached_file_ids[db_id] = file_id logging.debug(f"Cached media file with ID {db_id}") return self.cached_file_ids[db_id]
async def generate_media_session(self, client: Client, file_id: FileId) -> Session: """ Generates the media session for the DC that contains the media file. This is required for getting the bytes from Telegram servers. """
media_session = client.media_sessions.get(file_id.dc_id, None)
if media_session is None: if file_id.dc_id != await client.storage.dc_id(): media_session = Session( client, file_id.dc_id, await Auth( client, file_id.dc_id, await client.storage.test_mode() ).create(), await client.storage.test_mode(), is_media=True, ) await media_session.start()
for _ in range(6): exported_auth = await client.invoke( raw.functions.auth.ExportAuthorization(dc_id=file_id.dc_id) )
try: await media_session.invoke( raw.functions.auth.ImportAuthorization( id=exported_auth.id, bytes=exported_auth.bytes ) ) break except AuthBytesInvalid: logging.debug( f"Invalid authorization bytes for DC {file_id.dc_id}" ) continue else: await media_session.stop() raise AuthBytesInvalid else: media_session = Session( client, file_id.dc_id, await client.storage.auth_key(), await client.storage.test_mode(), is_media=True, ) await media_session.start() logging.debug(f"Created media session for DC {file_id.dc_id}") client.media_sessions[file_id.dc_id] = media_session else: logging.debug(f"Using cached media session for DC {file_id.dc_id}") return media_session
@staticmethod async def get_location(file_id: FileId) -> Union[raw.types.InputPhotoFileLocation, raw.types.InputDocumentFileLocation, raw.types.InputPeerPhotoFileLocation,]: """ Returns the file location for the media file. """ file_type = file_id.file_type
if file_type == FileType.CHAT_PHOTO: if file_id.chat_id > 0: peer = raw.types.InputPeerUser( user_id=file_id.chat_id, access_hash=file_id.chat_access_hash ) else: if file_id.chat_access_hash == 0: peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id) else: peer = raw.types.InputPeerChannel( channel_id=utils.get_channel_id(file_id.chat_id), access_hash=file_id.chat_access_hash, )
location = raw.types.InputPeerPhotoFileLocation( peer=peer, volume_id=file_id.volume_id, local_id=file_id.local_id, big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG, ) elif file_type == FileType.PHOTO: location = raw.types.InputPhotoFileLocation( id=file_id.media_id, access_hash=file_id.access_hash, file_reference=file_id.file_reference, thumb_size=file_id.thumbnail_size, ) else: location = raw.types.InputDocumentFileLocation( id=file_id.media_id, access_hash=file_id.access_hash, file_reference=file_id.file_reference, thumb_size=file_id.thumbnail_size, ) return location
async def yield_file( self, file_id: FileId, index: int, offset: int, first_part_cut: int, last_part_cut: int, part_count: int, chunk_size: int, ) -> Union[str, None]: """ Custom generator that yields the bytes of the media file. Modded from <https://github.com/eyaadh/megadlbot_oss/blob/master/mega/telegram/utils/custom_download.py#L20> Thanks to Eyaadh <https://github.com/eyaadh> """ client = self.client work_loads[index] += 1 logging.debug(f"Starting to yielding file with client {index}.") media_session = await self.generate_media_session(client, file_id)
current_part = 1
location = await self.get_location(file_id)
try: r = await media_session.invoke( raw.functions.upload.GetFile( location=location, offset=offset, limit=chunk_size ), ) if isinstance(r, raw.types.upload.File): while True: chunk = r.bytes if not chunk: break elif part_count == 1: yield chunk[first_part_cut:last_part_cut] elif current_part == 1: yield chunk[first_part_cut:] elif current_part == part_count: yield chunk[:last_part_cut] else: yield chunk
current_part += 1 offset += chunk_size
if current_part > part_count: break
r = await media_session.invoke( raw.functions.upload.GetFile( location=location, offset=offset, limit=chunk_size ), ) except (TimeoutError, AttributeError): pass finally: logging.debug(f"Finished yielding file with {current_part} parts.") work_loads[index] -= 1
async def clean_cache(self) -> None: """ function to clean the cache to reduce memory usage """ while True: await asyncio.sleep(self.clean_timer) self.cached_file_ids.clear() logging.debug("Cleaned the cache")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import pymongoimport timeimport motor.motor_asynciofrom bson.objectid import ObjectIdfrom bson.errors import InvalidIdfrom FileStream.server.exceptions import FIleNotFound
class Database: def __init__(self, uri, database_name): self._client = motor.motor_asyncio.AsyncIOMotorClient(uri) self.db = self._client[database_name] self.col = self.db.users self.black = self.db.blacklist self.file = self.db.file
#---------------------[ NEW USER ]---------------------# def new_user(self, id): return dict( id=id, join_date=time.time(), Links=0 )
# ---------------------[ ADD USER ]---------------------# async def add_user(self, id): user = self.new_user(id) await self.col.insert_one(user)
# ---------------------[ GET USER ]---------------------# async def get_user(self, id): user = await self.col.find_one({'id': int(id)}) return user
# ---------------------[ CHECK USER ]---------------------# async def total_users_count(self): count = await self.col.count_documents({}) return count
async def get_all_users(self): all_users = self.col.find({}) return all_users
# ---------------------[ REMOVE USER ]---------------------# async def delete_user(self, user_id): await self.col.delete_many({'id': int(user_id)})
# ---------------------[ BAN, UNBAN USER ]---------------------# def black_user(self, id): return dict( id=id, ban_date=time.time() )
async def ban_user(self, id): user = self.black_user(id) await self.black.insert_one(user)
async def unban_user(self, id): await self.black.delete_one({'id': int(id)})
async def is_user_banned(self, id): user = await self.black.find_one({'id': int(id)}) return True if user else False
async def total_banned_users_count(self): count = await self.black.count_documents({}) return count # ---------------------[ ADD FILE TO DB ]---------------------# async def add_file(self, file_info): file_info["time"] = time.time() fetch_old = await self.get_file_by_fileuniqueid(file_info["user_id"], file_info["file_unique_id"]) if fetch_old: return fetch_old["_id"] await self.count_links(file_info["user_id"], "+") return (await self.file.insert_one(file_info)).inserted_id
# ---------------------[ FIND FILE IN DB ]---------------------# async def find_files(self, user_id, range): user_files=self.file.find({"user_id": user_id}) user_files.skip(range[0] - 1) user_files.limit(range[1] - range[0] + 1) user_files.sort('_id', pymongo.DESCENDING) total_files = await self.file.count_documents({"user_id": user_id}) return user_files, total_files
async def get_file(self, _id): try: file_info=await self.file.find_one({"_id": ObjectId(_id)}) if not file_info: raise FIleNotFound return file_info except InvalidId: raise FIleNotFound async def get_file_by_fileuniqueid(self, id, file_unique_id, many=False): if many: return self.file.find({"file_unique_id": file_unique_id}) else: file_info=await self.file.find_one({"user_id": id, "file_unique_id": file_unique_id}) if file_info: return file_info return False
# ---------------------[ TOTAL FILES ]---------------------# async def total_files(self, id=None): if id: return await self.file.count_documents({"user_id": id}) return await self.file.count_documents({})
# ---------------------[ DELETE FILES ]---------------------# async def delete_one_file(self, _id): await self.file.delete_one({'_id': ObjectId(_id)})
# ---------------------[ UPDATE FILES ]---------------------# async def update_file_ids(self, _id, file_ids: dict): await self.file.update_one({"_id": ObjectId(_id)}, {"$set": {"file_ids": file_ids}})
# ---------------------[ PAID SYS ]---------------------## async def link_available(self, id):# user = await self.col.find_one({"id": id})# if user.get("Plan") == "Plus":# return "Plus"# elif user.get("Plan") == "Free":# files = await self.file.count_documents({"user_id": id})# if files < 11:# return True# return False async def count_links(self, id, operation: str): if operation == "-": await self.col.update_one({"id": id}, {"$inc": {"Links": -1}}) elif operation == "+": await self.col.update_one({"id": id}, {"$inc": {"Links": 1}})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144from __future__ import annotationsimport loggingfrom datetime import datetimefrom pyrogram import Clientfrom typing import Any, Optional
from pyrogram.enums import ParseMode, ChatTypefrom pyrogram.types import Messagefrom pyrogram.file_id import FileIdfrom FileStream.bot import FileStreamfrom FileStream.utils.database import Databasefrom FileStream.config import Telegram, Server
db = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
async def get_file_ids(client: Client | bool, db_id: str, multi_clients, message) -> Optional[FileId]: logging.debug("Starting of get_file_ids") file_info = await db.get_file(db_id) if (not "file_ids" in file_info) or not client: logging.debug("Storing file_id of all clients in DB") log_msg = await send_file(FileStream, db_id, file_info['file_id'], message) await db.update_file_ids(db_id, await update_file_id(log_msg.id, multi_clients)) logging.debug("Stored file_id of all clients in DB") if not client: return file_info = await db.get_file(db_id)
file_id_info = file_info.setdefault("file_ids", {}) if not str(client.id) in file_id_info: logging.debug("Storing file_id in DB") log_msg = await send_file(FileStream, db_id, file_info['file_id'], message) msg = await client.get_messages(Telegram.FLOG_CHANNEL, log_msg.id) media = get_media_from_message(msg) file_id_info[str(client.id)] = getattr(media, "file_id", "") await db.update_file_ids(db_id, file_id_info) logging.debug("Stored file_id in DB")
logging.debug("Middle of get_file_ids") file_id = FileId.decode(file_id_info[str(client.id)]) setattr(file_id, "file_size", file_info['file_size']) setattr(file_id, "mime_type", file_info['mime_type']) setattr(file_id, "file_name", file_info['file_name']) setattr(file_id, "unique_id", file_info['file_unique_id']) logging.debug("Ending of get_file_ids") return file_id
def get_media_from_message(message: "Message") -> Any: media_types = ( "audio", "document", "photo", "sticker", "animation", "video", "voice", "video_note", ) for attr in media_types: media = getattr(message, attr, None) if media: return media
def get_media_file_size(m): media = get_media_from_message(m) return getattr(media, "file_size", "None")
def get_name(media_msg: Message | FileId) -> str: if isinstance(media_msg, Message): media = get_media_from_message(media_msg) file_name = getattr(media, "file_name", "")
elif isinstance(media_msg, FileId): file_name = getattr(media_msg, "file_name", "")
if not file_name: if isinstance(media_msg, Message) and media_msg.media: media_type = media_msg.media.value elif media_msg.file_type: media_type = media_msg.file_type.name.lower() else: media_type = "file"
formats = { "photo": "jpg", "audio": "mp3", "voice": "ogg", "video": "mp4", "animation": "mp4", "video_note": "mp4", "sticker": "webp" }
ext = formats.get(media_type) ext = "." + ext if ext else ""
date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") file_name = f"{media_type}-{date}{ext}"
return file_name
def get_file_info(message): media = get_media_from_message(message) if message.chat.type == ChatType.PRIVATE: user_idx = message.from_user.id else: user_idx = message.chat.id return { "user_id": user_idx, "file_id": getattr(media, "file_id", ""), "file_unique_id": getattr(media, "file_unique_id", ""), "file_name": get_name(message), "file_size": getattr(media, "file_size", 0), "mime_type": getattr(media, "mime_type", "None/unknown") }
async def update_file_id(msg_id, multi_clients): file_ids = {} for client_id, client in multi_clients.items(): log_msg = await client.get_messages(Telegram.FLOG_CHANNEL, msg_id) media = get_media_from_message(log_msg) file_ids[str(client.id)] = getattr(media, "file_id", "")
return file_ids
async def send_file(client: Client, db_id, file_id: str, message): file_caption = getattr(message, 'caption', None) or get_name(message) log_msg = await client.send_cached_media(chat_id=Telegram.FLOG_CHANNEL, file_id=file_id, caption=f'**{file_caption}**')
if message.chat.type == ChatType.PRIVATE: await log_msg.reply_text( text=f"**RᴇQᴜᴇꜱᴛᴇᴅ ʙʏ :** [{message.from_user.first_name}](tg://user?id={message.from_user.id})\n**Uꜱᴇʀ ɪᴅ :** `{message.from_user.id}`\n**Fɪʟᴇ ɪᴅ :** `{db_id}`", disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN, quote=True) else: await log_msg.reply_text( text=f"**RᴇQᴜᴇꜱᴛᴇᴅ ʙʏ :** {message.chat.title} \n**Cʜᴀɴɴᴇʟ ɪᴅ :** `{message.chat.id}`\n**Fɪʟᴇ ɪᴅ :** `{db_id}`", disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN, quote=True)
return log_msg # return await client.send_cached_media(Telegram.BIN_CHANNEL, file_id)
12345678910def humanbytes(size): if not size: return "" power = 2**10 n = 0 Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'} while size > power: size /= power n += 1 return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'123456789101112131415161718192021222324252627282930import aiohttpimport jinja2import urllib.parsefrom FileStream.config import Telegram, Serverfrom FileStream.utils.database import Databasefrom FileStream.utils.human_readable import humanbytesdb = Database(Telegram.DATABASE_URL, Telegram.SESSION_NAME)
async def render_page(db_id): file_data=await db.get_file(db_id) src = urllib.parse.urljoin(Server.URL, f'dl/{file_data["_id"]}') file_size = humanbytes(file_data['file_size']) file_name = file_data['file_name'].replace("_", " ")
if str((file_data['mime_type']).split('/')[0].strip()) == 'video': template_file = "FileStream/template/play.html" else: template_file = "FileStream/template/dl.html" async with aiohttp.ClientSession() as s: async with s.get(src) as u: file_size = humanbytes(int(u.headers.get('Content-Length')))
with open(template_file) as f: template = jinja2.Template(f.read())
return template.render( file_name=file_name, file_url=src, file_size=file_size )12345678910111213141516171819202122def get_readable_time(seconds: int) -> str: count = 0 readable_time = "" time_list = [] time_suffix_list = ["s", "m", "h", " days"] while count < 4: count += 1 if count < 3: remainder, result = divmod(seconds, 60) else: remainder, result = 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_time123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom FileStream.config import Telegram
class LANG(object):
START_TEXT = """<b>👋 Hᴇʏ, </b>{}\n <b>I'ᴍ ᴛᴇʟᴇɢʀᴀᴍ ғɪʟᴇs sᴛʀᴇᴀᴍɪɴɢ ʙᴏᴛ ᴀs ᴡᴇʟʟ ᴅɪʀᴇᴄᴛ ʟɪɴᴋs ɢᴇɴᴇʀᴀᴛᴏʀ</b>\n<b>ᴡᴏʀᴋɪɴɢ ᴏɴ ᴄʜᴀɴɴᴇʟs ᴀɴᴅ ᴘʀɪᴠᴀᴛᴇ ᴄʜᴀᴛ</b>\n<b>💕 @{}</b>\n"""
HELP_TEXT = """<b>- ᴀᴅᴅ ᴍᴇ ᴀs ᴀɴ ᴀᴅᴍɪɴ ᴏɴ ᴛʜᴇ ᴄʜᴀɴɴᴇʟ</b><b>- sᴇɴᴅ ᴍᴇ ᴀɴʏ ᴅᴏᴄᴜᴍᴇɴᴛ ᴏʀ ᴍᴇᴅɪᴀ</b><b>- ɪ'ʟʟ ᴘʀᴏᴠɪᴅᴇ sᴛʀᴇᴀᴍᴀʙʟᴇ ʟɪɴᴋ</b>\n<b>🔞 ᴀᴅᴜʟᴛ ᴄᴏɴᴛᴇɴᴛ sᴛʀɪᴄᴛʟʏ ᴘʀᴏʜɪʙɪᴛᴇᴅ.</b>\n<i><b> ʀᴇᴘᴏʀᴛ ʙᴜɢs ᴛᴏ <a href='https://telegram.me/AvishkarPatil'>ᴅᴇᴠᴇʟᴏᴘᴇʀ</a></b></i>"""
ABOUT_TEXT = """<b>⚜ ᴍʏ ɴᴀᴍᴇ : {}</b>\n<b>✦ ᴠᴇʀsɪᴏɴ : {}</b><b>✦ ᴜᴘᴅᴀᴛᴇᴅ ᴏɴ : 06-January-2024</b><b>✦ ᴅᴇᴠᴇʟᴏᴘᴇʀ : <a href='https://telegram.me/AvishkarPatil'>Avishkar Patil</a></b>\n"""
STREAM_TEXT = """<i><u>𝗬𝗼𝘂𝗿 𝗟𝗶𝗻𝗸 𝗚𝗲𝗻𝗲𝗿𝗮𝘁𝗲𝗱 !</u></i>\n<b>📂 Fɪʟᴇ ɴᴀᴍᴇ :</b> <b>{}</b>\n<b>📦 Fɪʟᴇ ꜱɪᴢᴇ :</b> <code>{}</code>\n<b>📥 Dᴏᴡɴʟᴏᴀᴅ :</b> <code>{}</code>\n<b>🖥 Wᴀᴛᴄʜ :</b> <code>{}</code>\n<b>🔗 Sʜᴀʀᴇ :</b> <code>{}</code>\n"""
STREAM_TEXT_X = """<i><u>𝗬𝗼𝘂𝗿 𝗟𝗶𝗻𝗸 𝗚𝗲𝗻𝗲𝗿𝗮𝘁𝗲𝗱 !</u></i>\n<b>📂 Fɪʟᴇ ɴᴀᴍᴇ :</b> <b>{}</b>\n<b>📦 Fɪʟᴇ ꜱɪᴢᴇ :</b> <code>{}</code>\n<b>📥 Dᴏᴡɴʟᴏᴀᴅ :</b> <code>{}</code>\n<b>🔗 Sʜᴀʀᴇ :</b> <code>{}</code>\n"""
BAN_TEXT = "__Sᴏʀʀʏ Sɪʀ, Yᴏᴜ ᴀʀᴇ Bᴀɴɴᴇᴅ ᴛᴏ ᴜsᴇ ᴍᴇ.__\n\n**[Cᴏɴᴛᴀᴄᴛ Dᴇᴠᴇʟᴏᴘᴇʀ](tg://user?id={}) Tʜᴇʏ Wɪʟʟ Hᴇʟᴘ Yᴏᴜ**"
class BUTTON(object): START_BUTTONS = InlineKeyboardMarkup( [[ InlineKeyboardButton('ʜᴇʟᴘ', callback_data='help'), InlineKeyboardButton('ᴀʙᴏᴜᴛ', callback_data='about'), InlineKeyboardButton('ᴄʟᴏsᴇ', callback_data='close') ], [InlineKeyboardButton("📢 ᴜᴘᴅᴀᴛᴇ ᴄʜᴀɴɴᴇʟ", url=f'https://t.me/{Telegram.UPDATES_CHANNEL}')] ] ) HELP_BUTTONS = InlineKeyboardMarkup( [[ InlineKeyboardButton('ʜᴏᴍᴇ', callback_data='home'), InlineKeyboardButton('ᴀʙᴏᴜᴛ', callback_data='about'), InlineKeyboardButton('ᴄʟᴏsᴇ', callback_data='close'), ], [InlineKeyboardButton("📢 ᴜᴘᴅᴀᴛᴇ ᴄʜᴀɴɴᴇʟ", url=f'https://t.me/{Telegram.UPDATES_CHANNEL}')] ] ) ABOUT_BUTTONS = InlineKeyboardMarkup( [[ InlineKeyboardButton('ʜᴏᴍᴇ', callback_data='home'), InlineKeyboardButton('ʜᴇʟᴘ', callback_data='help'), InlineKeyboardButton('ᴄʟᴏsᴇ', callback_data='close'), ], [InlineKeyboardButton("📢 ᴜᴘᴅᴀᴛᴇ ᴄʜᴀɴɴᴇʟ", url=f'https://t.me/{Telegram.UPDATES_CHANNEL}')] ] )1Subproject commit 1068087588910dc4095952e5159b97ff8f5cf86e1Subproject commit a7e554d4bd09fe3349e988e498f2413e4c3dc4aa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.1web: python -m FileStream12345678910111213141516171819covidemojifonttoolsgtts# gingeritjikanpygit+https://github.com/New-dev0/AsyncLyricsExtractor.gitgit+https://github.com/ufoptg/drawHub.gitpokedex.pypyfigletpygmentspyjokesquotefancyshazamiospeechrecognitionspeedtest-clitextblobwikipediahttps://github.com/ufoptg/google_trans_new/archive/refs/tags/1.2.0.zip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117{ "name": "FileStreamBot", "description": "A Telegram Bot to Convert Telegram Files To Direct & Streamable Links.", "keywords": [ "telegram", "files", "stream" ], "repository": "https://github.com/avipatilpro/FileStreamBot/", "success_url": "/", "logo": "https://i.ibb.co/ZJzJ9Hq/link-3x.png", "env": { "ENV": { "description": "Set this to True if you don't want to crash the bot", "value": "True" }, "API_ID": { "description": "Get this value from https://my.telegram.org" }, "API_HASH": { "description": "Get this value from https://my.telegram.org" }, "BOT_TOKEN": { "description": "Get this value from @BotFather" }, "FLOG_CHANNEL": { "description": "ID of Channel Where store files sent by users. Read the readme for more info about this var" }, "ULOG_CHANNEL": { "description": "ID of Channel Where store New Users data. Read the readme for more info about this var" }, "OWNER_ID": { "description": "Your Telegram User ID as Owner" }, "DATABASE_URL": { "description": "MongoDB URI for saving User Data and Files List created by user." }, "AUTH_USERS": { "description": "Put IDs of Auth Usrs where bot will work. You can add multiple IDs & separate with Space.", "required": false }, "UPDATES_CHANNEL": { "description": "Channel Username without `@` to set channel as Update Channel", "required": false }, "FORCE_SUB_ID": { "description": "Channel ID starts with -100 to set channel as Force Sub Channel", "required": false }, "FORCE_SUB": { "description": "Set to True, so every user have to Join update channel to use the bot.", "required": false }, "SLEEP_THRESHOLD": { "description": "Set global flood wait threshold, auto-retry requests under 60s. ", "required": false }, "WORKERS": { "description": "No. of workers that is to be assigned.", "required": false }, "PORT": { "description": "The port that you want your webapp to be listened to", "required": false }, "NO_PORT": { "description": "If you don't want your port to be displayed. Set True or False", "value": "True", "required": false }, "HAS_SSL": { "description": "(can be either True or False) If you want the generated links in https format.", "value": "True", "required": false }, "BIND_ADDRESS": { "description": "Your server bind address. default to 0.0.0.0", "required": false }, "FQDN": { "description": "Heroku app Link without http/s://, you can set later. its required", "required": false }, "SESSION_NAME": { "description": "Name for the Database created on your MongoDB. Defaults to FileStream", "required": false }, "FILE_PIC": { "description": "To set Image at /files command. Defaults to pre-set image.", "required": false }, "START_PIC": { "description": "To set Image at /start command. Defaults to pre-set image.", "required": false }, "VERIFY_PIC": { "description": "To set Image at Force Subscribe Verify. Defaults to pre-set image.", "required": false }, "MODE": { "description": "Should be set to `secondary` if you only want to use the server for serving files.", "required": false } }, "buildpacks": [ { "url": "heroku/python" } ], "stack": "heroku-22", "formation": { "web": { "quantity": 1, "size": "eco" } }}12345678910111213141516171819202122232425262728293031323334# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from telethon import Button, custom
from plugins import ATRA_COL, InlinePluginfrom pyUltroid import *from pyUltroid import _ult_cachefrom pyUltroid._misc import owner_and_sudosfrom pyUltroid._misc._assistant import asst_cmd, callback, in_patternfrom pyUltroid.fns.helper import *from pyUltroid.fns.tools import get_stored_filefrom strings import get_languages, get_string
OWNER_NAME = ultroid_bot.full_nameOWNER_ID = ultroid_bot.uid
AST_PLUGINS = {}
async def setit(event, name, value): try: udB.set_key(name, value) except BaseException as er: LOGS.exception(er) return await event.edit("`Something Went Wrong`")
def get_back_button(name): return [Button.inline("« Bᴀᴄᴋ", data=f"{name}")]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import astimport asyncioimport reimport sysimport timefrom asyncio.exceptions import TimeoutError as AsyncTimeOutfrom os import execl, removefrom random import choice
from bs4 import BeautifulSoup as bs
try: from pyUltroid.fns.gDrive import GDriveManagerexcept ImportError: GDriveManager = Nonefrom telegraph import upload_file as uplfrom telethon import Button, eventsfrom telethon.tl.types import MessageMediaWebPagefrom telethon.utils import get_peer_id
from pyUltroid.fns.helper import fast_download, progressfrom pyUltroid.fns.tools import Carbon, async_searcher, get_paste, telegraph_clientfrom pyUltroid.startup.loader import Loader
from . import *
# --------------------------------------------------------------------#telegraph = telegraph_client()GDrive = GDriveManager() if GDriveManager else None# --------------------------------------------------------------------#
def text_to_url(event): """function to get media url (with|without) Webpage""" if isinstance(event.media, MessageMediaWebPage): webpage = event.media.webpage if not isinstance(webpage, types.WebPageEmpty) and webpage.type in ["photo"]: return webpage.display_url return event.text
# --------------------------------------------------------------------#
_buttons = { "otvars": { "text": "Other Variables to set for @TeamUltroid:", "buttons": [ [ Button.inline("Tᴀɢ Lᴏɢɢᴇʀ", data="taglog"), Button.inline("SᴜᴘᴇʀFʙᴀɴ", data="cbs_sfban"), ], [ Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ", data="sudo"), Button.inline("Hᴀɴᴅʟᴇʀ", data="hhndlr"), ], [ Button.inline("Exᴛʀᴀ Pʟᴜɢɪɴs", data="plg"), Button.inline("Aᴅᴅᴏɴs", data="eaddon"), ], [ Button.inline("Eᴍᴏᴊɪ ɪɴ Hᴇʟᴘ", data="emoj"), Button.inline("Sᴇᴛ ɢDʀɪᴠᴇ", data="gdrive"), ], [ Button.inline("Iɴʟɪɴᴇ Pɪᴄ", data="inli_pic"), Button.inline("Sᴜᴅᴏ HNDLR", data="shndlr"), ], [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ", "cbs_oofdm")], [Button.inline("« Bᴀᴄᴋ", data="setter")], ], }, "sfban": { "text": "SuperFban Settings:", "buttons": [ [Button.inline("FBᴀɴ Gʀᴏᴜᴘ", data="sfgrp")], [Button.inline("Exᴄʟᴜᴅᴇ Fᴇᴅs", data="abs_sfexf")], [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], ], }, "apauto": { "text": "This'll auto approve on outgoing messages", "buttons": [ [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ ON", data="apon")], [Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ OFF", data="apof")], [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], ], }, "alvcstm": { "text": f"Customise your {HNDLR}alive. Choose from the below options -", "buttons": [ [Button.inline("Aʟɪᴠᴇ Tᴇxᴛ", data="abs_alvtx")], [Button.inline("Aʟɪᴠᴇ ᴍᴇᴅɪᴀ", data="alvmed")], [Button.inline("Dᴇʟᴇᴛᴇ Aʟɪᴠᴇ Mᴇᴅɪᴀ", data="delmed")], [Button.inline("« Bᴀᴄᴋ", data="setter")], ], }, "pmcstm": { "text": "Customise your PMPERMIT Settings -", "buttons": [ [ Button.inline("Pᴍ Tᴇxᴛ", data="pmtxt"), Button.inline("Pᴍ Mᴇᴅɪᴀ", data="pmmed"), ], [ Button.inline("Aᴜᴛᴏ Aᴘᴘʀᴏᴠᴇ", data="cbs_apauto"), Button.inline("PMLOGGER", data="pml"), ], [ Button.inline("Sᴇᴛ Wᴀʀɴs", data="swarn"), Button.inline("Dᴇʟᴇᴛᴇ Pᴍ Mᴇᴅɪᴀ", data="delpmmed"), ], [Button.inline("PMPermit Type", data="cbs_pmtype")], [Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")], ], }, "pmtype": { "text": "Select the type of PMPermit needed.", "buttons": [ [Button.inline("Inline", data="inpm_in")], [Button.inline("Normal", data="inpm_no")], [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], ], }, "ppmset": { "text": "PMPermit Settings:", "buttons": [ [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oɴ", data="pmon")], [Button.inline("Tᴜʀɴ PMPᴇʀᴍɪᴛ Oғғ", data="pmoff")], [Button.inline("Cᴜsᴛᴏᴍɪᴢᴇ PMPᴇʀᴍɪᴛ", data="cbs_pmcstm")], [Button.inline("« Bᴀᴄᴋ", data="setter")], ], }, "chatbot": { "text": "From This Feature U can chat with ppls Via ur Assistant Bot.\n[More info](https://t.me/UltroidUpdates/2)", "buttons": [ [ Button.inline("Cʜᴀᴛ Bᴏᴛ Oɴ", data="onchbot"), Button.inline("Cʜᴀᴛ Bᴏᴛ Oғғ", data="ofchbot"), ], [ Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ", data="bwel"), Button.inline("Bᴏᴛ Wᴇʟᴄᴏᴍᴇ Mᴇᴅɪᴀ", data="botmew"), ], [Button.inline("Bᴏᴛ Iɴғᴏ Tᴇxᴛ", data="botinfe")], [Button.inline("Fᴏʀᴄᴇ Sᴜʙsᴄʀɪʙᴇ", data="pmfs")], [Button.inline("« Bᴀᴄᴋ", data="setter")], ], }, "vcb": { "text": "From This Feature U can play songs in group voice chat\n\n[moreinfo](https://t.me/UltroidUpdates/4)", "buttons": [ [Button.inline("VC Sᴇssɪᴏɴ", data="abs_vcs")], [Button.inline("« Bᴀᴄᴋ", data="setter")], ], }, "oofdm": { "text": "About [Dual Mode](https://t.me/UltroidUpdates/18)", "buttons": [ [ Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oɴ", "dmof"), Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Oғғ", "dmof"), ], [Button.inline("Dᴜᴀʟ Mᴏᴅᴇ Hɴᴅʟʀ", "dmhn")], [Button.inline("« Back", data="cbs_otvars")], ], }, "apiset": { "text": get_string("ast_1"), "buttons": [ [Button.inline("Remove.bg API", data="abs_rmbg")], [Button.inline("DEEP API", data="abs_dapi")], [Button.inline("OCR API", data="abs_oapi")], [Button.inline("SERP API", data="abs_sapi")], [Button.inline("« Back", data="setter")], ], },}
_convo = { "rmbg": { "var": "RMBG_API", "name": "Remove.bg API Key", "text": get_string("ast_2"), "back": "cbs_apiset", }, "dapi": { "var": "DEEP_AI", "name": "Deep AI Api Key", "text": "Get Your Deep Api from deepai.org and send here.", "back": "cbs_apiset", }, "oapi": { "var": "OCR_API", "name": "Ocr Api Key", "text": "Get Your OCR api from ocr.space and send that Here.", "back": "cbs_apiset", }, "sapi": { "var": "SERPAPI", "name": "Serp Api Key", "text": "Get Your SERP api from https://serpapi.com/users/sign_in and send that Here.", "back": "cbs_apiset", }, "pmlgg": { "var": "PMLOGGROUP", "name": "Pm Log Group", "text": "Send chat id of chat which you want to save as Pm log Group.", "back": "pml", }, "vcs": { "var": "VC_SESSION", "name": "Vc Session", "text": "**Vc session**\nEnter the New session u generated for vc bot.\n\nUse /cancel to terminate the operation.", "back": "cbs_vcb", }, "settag": { "var": "TAG_LOG", "name": "Tag Log Group", "text": f"Make a group, add your assistant and make it admin.\nGet the `{HNDLR}id` of that group and send it here for tag logs.\n\nUse /cancel to cancel.", "back": "taglog", }, "alvtx": { "var": "ALIVE_TEXT", "name": "Alive Text", "text": "**Alive Text**\nEnter the new alive text.\n\nUse /cancel to terminate the operation.", "back": "cbs_alvcstm", }, "sfexf": { "var": "EXCLUDE_FED", "name": "Excluded Fed", "text": "Send the Fed IDs you want to exclude in the ban. Split by a space.\neg`id1 id2 id3`\nSet is as `None` if you dont want any.\nUse /cancel to go back.", "back": "cbs_sfban", },}
TOKEN_FILE = "resources/auths/auth_token.txt"
@callback( re.compile( "sndplug_(.*)", ), owner=True,)async def send(eve): key, name = (eve.data_match.group(1)).decode("UTF-8").split("_") thumb = "resources/extras/inline.jpg" await eve.answer("■ Sending ■") data = f"uh_{key}_" index = None if "|" in name: name, index = name.split("|") key = "plugins" if key == "Official" else key.lower() plugin = f"{key}/{name}.py" _ = f"pasta-{plugin}" if index is not None: data += f"|{index}" _ += f"|{index}" buttons = [ [ Button.inline( "« Pᴀsᴛᴇ »", data=_, ) ], [ Button.inline("« Bᴀᴄᴋ", data=data), ], ] try: await eve.edit(file=plugin, thumb=thumb, buttons=buttons) except Exception as er: await eve.answer(str(er), alert=True)
heroku_api, app_name = Var.HEROKU_API, Var.HEROKU_APP_NAME
@callback("updatenow", owner=True)async def update(eve): repo = Repo() ac_br = repo.active_branch ups_rem = repo.remote("upstream") if heroku_api: import heroku3
try: heroku = heroku3.from_key(heroku_api) heroku_app = None heroku_applications = heroku.apps() except BaseException as er: LOGS.exception(er) return await eve.edit("`Wrong HEROKU_API.`") for app in heroku_applications: if app.name == app_name: heroku_app = app if not heroku_app: await eve.edit("`Wrong HEROKU_APP_NAME.`") repo.__del__() return await eve.edit(get_string("clst_1")) ups_rem.fetch(ac_br) repo.git.reset("--hard", "FETCH_HEAD") heroku_git_url = heroku_app.git_url.replace( "https://", f"https://api:{heroku_api}@" )
if "heroku" in repo.remotes: remote = repo.remote("heroku") remote.set_url(heroku_git_url) else: remote = repo.create_remote("heroku", heroku_git_url) try: remote.push(refspec=f"HEAD:refs/heads/{ac_br}", force=True) except GitCommandError as error: await eve.edit(f"`Here is the error log:\n{error}`") repo.__del__() return await eve.edit("`Successfully Updated!\nRestarting, please wait...`") else: await eve.edit(get_string("clst_1")) call_back() await bash("git pull && pip3 install -r requirements.txt") execl(sys.executable, sys.executable, "-m", "pyUltroid")
@callback(re.compile("changes(.*)"), owner=True)async def changes(okk): match = okk.data_match.group(1).decode("utf-8") await okk.answer(get_string("clst_3")) repo = Repo.init() button = [[Button.inline("Update Now", data="updatenow")]] changelog, tl_chnglog = await gen_chlog( repo, f"HEAD..upstream/{repo.active_branch}" ) cli = "\n\nClick the below button to update!" if not match: try: if len(tl_chnglog) > 700: tl_chnglog = f"{tl_chnglog[:700]}..." button.append([Button.inline("View Complete", "changesall")]) await okk.edit("• Writing Changelogs 📝 •") img = await Carbon( file_name="changelog", code=tl_chnglog, backgroundColor=choice(ATRA_COL), language="md", ) return await okk.edit( f"**• Ultroid Userbot •**{cli}", file=img, buttons=button ) except Exception as er: LOGS.exception(er) changelog_str = changelog + cli if len(changelog_str) > 1024: await okk.edit(get_string("upd_4")) await asyncio.sleep(2) with open("ultroid_updates.txt", "w+") as file: file.write(tl_chnglog) await okk.edit( get_string("upd_5"), file="ultroid_updates.txt", buttons=button, ) remove("ultroid_updates.txt") return await okk.edit( changelog_str, buttons=button, parse_mode="html", )
@callback( re.compile( "pasta-(.*)", ), owner=True,)async def _(e): ok = (e.data_match.group(1)).decode("UTF-8") index = None if "|" in ok: ok, index = ok.split("|") with open(ok, "r") as hmm: _, key = await get_paste(hmm.read()) link = f"https://spaceb.in/{key}" raw = f"https://spaceb.in/api/v1/documents/{key}/raw" if not _: return await e.answer(key[:30], alert=True) if ok.startswith("addons"): key = "Addons" elif ok.startswith("vcbot"): key = "VCBot" else: key = "Official" data = f"uh_{key}_" if index is not None: data += f"|{index}" await e.edit( "", buttons=[ [Button.url("Lɪɴᴋ", link), Button.url("Rᴀᴡ", raw)], [Button.inline("« Bᴀᴄᴋ", data=data)], ], )
@callback(re.compile("cbs_(.*)"), owner=True)async def _edit_to(event): match = event.data_match.group(1).decode("utf-8") data = _buttons.get(match) if not data: return await event.edit(data["text"], buttons=data["buttons"], link_preview=False)
@callback(re.compile("abs_(.*)"), owner=True)async def convo_handler(event: events.CallbackQuery): match = event.data_match.group(1).decode("utf-8") if not _convo.get(match): return await event.delete() get_ = _convo[match] back = get_["back"] async with event.client.conversation(event.sender_id) as conv: await conv.send_message(get_["text"]) response = await conv.get_response() themssg = response.message try: themssg = ast.literal_eval(themssg) except Exception: pass if themssg == "/cancel": return await conv.send_message( "Cancelled!!", buttons=get_back_button(back), ) await setit(event, get_["var"], themssg) await conv.send_message( f"{get_['name']} changed to `{themssg}`", buttons=get_back_button(back), )
@callback("authorise", owner=True)async def _(e): if not e.is_private: return url = GDrive._create_token_file() await e.edit("Go to the below link and send the code!") async with asst.conversation(e.sender_id) as conv: await conv.send_message(url) code = await conv.get_response() if GDrive._create_token_file(code=code.text): await conv.send_message( "`Success!\nYou are all set to use Google Drive with Ultroid Userbot.`", buttons=Button.inline("Main Menu", data="setter"), ) else: await conv.send_message("Wrong code! Click authorise again.")
@callback("folderid", owner=True, func=lambda x: x.is_private)async def _(e): if not e.is_private: return msg = ( "Send your FOLDER ID\n\n" + "For FOLDER ID:\n" + "1. Open Google Drive App.\n" + "2. Create Folder.\n" + "3. Make that folder public.\n" + "4. Send link of that folder." ) await e.delete() async with asst.conversation(e.sender_id, timeout=150) as conv: await conv.send_message(msg) repl = await conv.get_response() id = repl.text if id.startswith("https"): id = id.split("?id=")[-1] udB.set_key("GDRIVE_FOLDER_ID", id) await repl.reply( "`Success.`", buttons=get_back_button("gdrive"), )
@callback("gdrive", owner=True)async def _(e): if not e.is_private: return await e.edit( "Click Authorise and send the code.\n\nYou can use your own CLIENT ID and SECRET by [this](https://t.me/UltroidUpdates/37)", buttons=[ [ Button.inline("Folder ID", data="folderid"), Button.inline("Authorise", data="authorise"), ], [Button.inline("« Back", data="cbs_otvars")], ], link_preview=False, )
@callback("dmof", owner=True)async def rhwhe(e): if udB.get_key("DUAL_MODE"): udB.del_key("DUAL_MODE") key = "Off" else: udB.set_key("DUAL_MODE", "True") key = "On" Msg = f"Dual Mode : {key}" await e.edit(Msg, buttons=get_back_button("cbs_otvars"))
@callback("dmhn", owner=True)async def hndlrr(event): await event.delete() pru = event.sender_id var = "DUAL_HNDLR" name = "Dual Handler" CH = udB.get_key(var) or "/" async with event.client.conversation(pru) as conv: await conv.send_message( f"Send The Symbol Which u want as Handler/Trigger to use your Assistant bot\nUr Current Handler is [ `{CH}` ]\n\n use /cancel to cancel.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_otvars"), ) elif len(themssg) > 1: await conv.send_message( "Incorrect Handler", buttons=get_back_button("cbs_otvars"), ) else: await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}", buttons=get_back_button("cbs_otvars"), )
@callback("emoj", owner=True)async def emoji(event): await event.delete() pru = event.sender_id var = "EMOJI_IN_HELP" name = f"Emoji in `{HNDLR}help` menu" async with event.client.conversation(pru) as conv: await conv.send_message("Send emoji u want to set 🙃.\n\nUse /cancel to cancel.") response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_otvars"), ) elif themssg.startswith(("/", HNDLR)): await conv.send_message( "Incorrect Emoji", buttons=get_back_button("cbs_otvars"), ) else: await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}\n", buttons=get_back_button("cbs_otvars"), )
@callback("plg", owner=True)async def pluginch(event): await event.delete() pru = event.sender_id var = "PLUGIN_CHANNEL" name = "Plugin Channel" async with event.client.conversation(pru) as conv: await conv.send_message( "Send id or username of a channel from where u want to install all plugins\n\nOur Channel~ @ultroidplugins\n\nUse /cancel to cancel.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_otvars"), ) elif themssg.startswith(("/", HNDLR)): await conv.send_message( "Incorrect channel", buttons=get_back_button("cbs_otvars"), ) else: await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}\n After Setting All Things Do Restart", buttons=get_back_button("cbs_otvars"), )
@callback("hhndlr", owner=True)async def hndlrr(event): await event.delete() pru = event.sender_id var = "HNDLR" name = "Handler/ Trigger" async with event.client.conversation(pru) as conv: await conv.send_message( f"Send The Symbol Which u want as Handler/Trigger to use bot\nUr Current Handler is [ `{HNDLR}` ]\n\n use /cancel to cancel.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_otvars"), ) elif len(themssg) > 1: await conv.send_message( "Incorrect Handler", buttons=get_back_button("cbs_otvars"), ) elif themssg.startswith(("/", "#", "@")): await conv.send_message( "This cannot be used as handler", buttons=get_back_button("cbs_otvars"), ) else: await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}", buttons=get_back_button("cbs_otvars"), )
@callback("shndlr", owner=True)async def hndlrr(event): await event.delete() pru = event.sender_id var = "SUDO_HNDLR" name = "Sudo Handler" async with event.client.conversation(pru) as conv: await conv.send_message( "Send The Symbol Which u want as Sudo Handler/Trigger to use bot\n\n use /cancel to cancel." )
response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_otvars"), ) elif len(themssg) > 1: await conv.send_message( "Incorrect Handler", buttons=get_back_button("cbs_otvars"), ) elif themssg.startswith(("/", "#", "@")): await conv.send_message( "This cannot be used as handler", buttons=get_back_button("cbs_otvars"), ) else: await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}", buttons=get_back_button("cbs_otvars"), )
@callback("taglog", owner=True)async def tagloggrr(e): BUTTON = [ [Button.inline("SET TAG LOG", data="abs_settag")], [Button.inline("DELETE TAG LOG", data="deltag")], get_back_button("cbs_otvars"), ] await e.edit( "Choose Options", buttons=BUTTON, )
@callback("deltag", owner=True)async def _(e): udB.del_key("TAG_LOG") await e.answer("Done!!! Tag Logger has been turned Off")
@callback("eaddon", owner=True)async def pmset(event): BT = ( [Button.inline("Aᴅᴅᴏɴs Oғғ", data="edof")] if udB.get_key("ADDONS") else [Button.inline("Aᴅᴅᴏɴs Oɴ", data="edon")] )
await event.edit( "ADDONS~ Extra Plugins:", buttons=[ BT, [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], ], )
@callback("edon", owner=True)async def eddon(event): var = "ADDONS" await setit(event, var, "True") await event.edit( "Done! ADDONS has been turned on!!\n\n After Setting All Things Do Restart", buttons=get_back_button("eaddon"), )
@callback("edof", owner=True)async def eddof(event): udB.set_key("ADDONS", "False") await event.edit( "Done! ADDONS has been turned off!! After Setting All Things Do Restart", buttons=get_back_button("eaddon"), )
@callback("sudo", owner=True)async def pmset(event): BT = ( [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oғғ", data="ofsudo")] if udB.get_key("SUDO") else [Button.inline("Sᴜᴅᴏ Mᴏᴅᴇ Oɴ", data="onsudo")] )
await event.edit( f"SUDO MODE ~ Some peoples can use ur Bot which u selected. To know More use `{HNDLR}help sudo`", buttons=[ BT, [Button.inline("« Bᴀᴄᴋ", data="cbs_otvars")], ], )
@callback("onsudo", owner=True)async def eddon(event): var = "SUDO" await setit(event, var, "True") await event.edit( "Done! SUDO MODE has been turned on!!\n\n After Setting All Things Do Restart", buttons=get_back_button("sudo"), )
@callback("ofsudo", owner=True)async def eddof(event): var = "SUDO" await setit(event, var, "False") await event.edit( "Done! SUDO MODE has been turned off!! After Setting All Things Do Restart", buttons=get_back_button("sudo"), )
@callback("sfgrp", owner=True)async def sfgrp(event): await event.delete() name = "FBan Group ID" var = "FBAN_GROUP_ID" pru = event.sender_id async with asst.conversation(pru) as conv: await conv.send_message( f"Make a group, add @MissRose_Bot, send `{HNDLR}id`, copy that and send it here.\nUse /cancel to go back.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": return await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_sfban"), ) await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}", buttons=get_back_button("cbs_sfban"), )
@callback("alvmed", owner=True)async def media(event): await event.delete() pru = event.sender_id var = "ALIVE_PIC" name = "Alive Media" async with event.client.conversation(pru) as conv: await conv.send_message( "**Alive Media**\nSend me a pic/gif/media to set as alive media.\n\nUse /cancel to terminate the operation.", ) response = await conv.get_response() try: themssg = response.message if themssg == "/cancel": return await conv.send_message( "Operation cancelled!!", buttons=get_back_button("cbs_alvcstm"), ) except BaseException as er: LOGS.exception(er) if ( not (response.text).startswith("/") and response.text != "" and (not response.media or isinstance(response.media, MessageMediaWebPage)) ): url = text_to_url(response) elif response.sticker: url = response.file.id else: media = await event.client.download_media(response, "alvpc") try: x = upl(media) url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( "Terminated.", buttons=get_back_button("cbs_alvcstm"), ) await setit(event, var, url) await conv.send_message( f"{name} has been set.", buttons=get_back_button("cbs_alvcstm"), )
@callback("delmed", owner=True)async def dell(event): try: udB.del_key("ALIVE_PIC") return await event.edit( get_string("clst_5"), buttons=get_back_button("cbs_alabs_vcstm") ) except BaseException as er: LOGS.exception(er) return await event.edit( get_string("clst_4"), buttons=get_back_button("cbs_alabs_vcstm"), )
@callback("inpm_in", owner=True)async def inl_on(event): var = "INLINE_PM" await setit(event, var, "True") await event.edit( "Done!! PMPermit type has been set to inline!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]], )
@callback("inpm_no", owner=True)async def inl_on(event): var = "INLINE_PM" await setit(event, var, "False") await event.edit( "Done!! PMPermit type has been set to normal!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_pmtype")]], )
@callback("pmtxt", owner=True)async def name(event): await event.delete() pru = event.sender_id var = "PM_TEXT" name = "PM Text" async with event.client.conversation(pru) as conv: await conv.send_message( "**PM Text**\nEnter the new Pmpermit text.\n\nu can use `{name}` `{fullname}` `{count}` `{mention}` `{username}` to get this from user Too\n\nUse /cancel to terminate the operation.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": return await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_pmcstm"), ) if len(themssg) > 4090: return await conv.send_message( "Message too long!\nGive a shorter message please!!", buttons=get_back_button("cbs_pmcstm"), ) await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}\n\nAfter Setting All Things Do restart", buttons=get_back_button("cbs_pmcstm"), )
@callback("swarn", owner=True)async def name(event): m = range(1, 10) tultd = [Button.inline(f"{x}", data=f"wrns_{x}") for x in m] lst = list(zip(tultd[::3], tultd[1::3], tultd[2::3])) lst.append([Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")]) await event.edit( "Select the number of warnings for a user before getting blocked in PMs.", buttons=lst, )
@callback(re.compile(b"wrns_(.*)"), owner=True)async def set_wrns(event): value = int(event.data_match.group(1).decode("UTF-8")) if dn := udB.set_key("PMWARNS", value): await event.edit( f"PM Warns Set to {value}.\nNew users will have {value} chances in PMs before getting banned.", buttons=get_back_button("cbs_pmcstm"), ) else: await event.edit( f"Something went wrong, please check your {HNDLR}logs!", buttons=get_back_button("cbs_pmcstm"), )
@callback("pmmed", owner=True)async def media(event): await event.delete() pru = event.sender_id var = "PMPIC" name = "PM Media" async with event.client.conversation(pru) as conv: await conv.send_message( "**PM Media**\nSend me a pic/gif/sticker/link to set as pmpermit media.\n\nUse /cancel to terminate the operation.", ) response = await conv.get_response() try: themssg = response.message if themssg == "/cancel": return await conv.send_message( "Operation cancelled!!", buttons=get_back_button("cbs_pmcstm"), ) except BaseException as er: LOGS.exception(er) media = await event.client.download_media(response, "pmpc") if ( not (response.text).startswith("/") and response.text != "" and (not response.media or isinstance(response.media, MessageMediaWebPage)) ): url = text_to_url(response) elif response.sticker: url = response.file.id else: try: x = upl(media) url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( "Terminated.", buttons=get_back_button("cbs_pmcstm"), ) await setit(event, var, url) await conv.send_message( f"{name} has been set.", buttons=get_back_button("cbs_pmcstm"), )
@callback("delpmmed", owner=True)async def dell(event): try: udB.del_key("PMPIC") return await event.edit( get_string("clst_5"), buttons=get_back_button("cbs_pmcstm") ) except BaseException as er: LOGS.exception(er) return await event.edit( get_string("clst_4"), buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], )
@callback("apon", owner=True)async def apon(event): var = "AUTOAPPROVE" await setit(event, var, "True") await event.edit( "Done!! AUTOAPPROVE Started!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]], )
@callback("apof", owner=True)async def apof(event): try: udB.set_key("AUTOAPPROVE", "False") return await event.edit( "Done! AUTOAPPROVE Stopped!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_apauto")]], ) except BaseException as er: LOGS.exception(er) return await event.edit( get_string("clst_4"), buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], )
@callback("pml", owner=True)async def l_vcs(event): BT = ( [Button.inline("PMLOGGER OFF", data="pmlogof")] if udB.get_key("PMLOG") else [Button.inline("PMLOGGER ON", data="pmlog")] )
await event.edit( "PMLOGGER This Will Forward Ur Pm to Ur Private Group -", buttons=[ BT, [Button.inline("PᴍLᴏɢɢᴇʀ Gʀᴏᴜᴘ", "abs_pmlgg")], [Button.inline("« Bᴀᴄᴋ", data="cbs_pmcstm")], ], )
@callback("pmlog", owner=True)async def pmlog(event): await setit(event, "PMLOG", "True") await event.edit( "Done!! PMLOGGER Started!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]], )
@callback("pmlogof", owner=True)async def pmlogof(event): try: udB.del_key("PMLOG") return await event.edit( "Done! PMLOGGER Stopped!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="pml")]], ) except BaseException as er: LOGS.exception(er) return await event.edit( get_string("clst_4"), buttons=[[Button.inline("« Sᴇᴛᴛɪɴɢs", data="setter")]], )
@callback("pmon", owner=True)async def pmonn(event): var = "PMSETTING" await setit(event, var, "True") await event.edit( "Done! PMPermit has been turned on!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]], )
@callback("pmoff", owner=True)async def pmofff(event): var = "PMSETTING" await setit(event, var, "False") await event.edit( "Done! PMPermit has been turned off!!", buttons=[[Button.inline("« Bᴀᴄᴋ", data="cbs_ppmset")]], )
@callback("botmew", owner=True)async def hhh(e): async with e.client.conversation(e.chat_id) as conv: await conv.send_message("Send Any Media to keep at your Bot's welcome ") msg = await conv.get_response() if not msg.media or msg.text.startswith("/"): return await conv.send_message( "Terminated!", buttons=get_back_button("cbs_chatbot") ) udB.set_key("STARTMEDIA", msg.file.id) await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
@callback("botinfe", owner=True)async def hhh(e): async with e.client.conversation(e.chat_id) as conv: await conv.send_message( "Send message to set to Display, when user Press Info button in Bot Welcome!\n\nsend `False` to completely remove that button.." ) msg = await conv.get_response() if msg.media or msg.text.startswith("/"): return await conv.send_message( "Terminated!", buttons=get_back_button("cbs_chatbot") ) udB.set_key("BOT_INFO_START", msg.text) await conv.send_message("Done!", buttons=get_back_button("cbs_chatbot"))
@callback("pmfs", owner=True)async def heheh(event): Ll = [] err = "" async with event.client.conversation(event.chat_id) as conv: await conv.send_message( "• Send The Chat Id(s), which you want user to Join Before using Chat/Pm Bot\n\n• Send /clear to disable PmBot Force sub..\n• • Send /cancel to stop this process.." ) await conv.send_message( "Example : \n`-1001234567\n-100778888`\n\nFor Multiple Chat(s)." ) try: msg = await conv.get_response() except AsyncTimeOut: return await conv.send_message("**• TimeUp!**\nStart from /start back.") if not msg.text or msg.text.startswith("/"): timyork = "Cancelled!" if msg.text == "/clear": udB.del_key("PMBOT_FSUB") timyork = "Done! Force Subscribe Stopped\nRestart your Bot!" return await conv.send_message( "Cancelled!", buttons=get_back_button("cbs_chatbot") ) for chat in msg.message.split("\n"): if chat.startswith("-") or chat.isdigit(): chat = int(chat) try: CHSJSHS = await event.client.get_entity(chat) Ll.append(get_peer_id(CHSJSHS)) except Exception as er: err += f"**{chat}** : {er}\n" if err: return await conv.send_message(err) udB.set_key("PMBOT_FSUB", str(Ll)) await conv.send_message( "Done!\nRestart Your Bot.", buttons=get_back_button("cbs_chatbot") )
@callback("bwel", owner=True)async def name(event): await event.delete() pru = event.sender_id var = "STARTMSG" name = "Bot Welcome Message:" async with event.client.conversation(pru) as conv: await conv.send_message( "**BOT WELCOME MSG**\nEnter the msg which u want to show when someone start your assistant Bot.\nYou Can use `{me}` , `{mention}` Parameters Too\nUse /cancel to terminate the operation.", ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": return await conv.send_message( "Cancelled!!", buttons=get_back_button("cbs_chatbot"), ) await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}", buttons=get_back_button("cbs_chatbot"), )
@callback("onchbot", owner=True)async def chon(event): var = "PMBOT" await setit(event, var, "True") Loader(path="assistant/pmbot.py", key="PM Bot").load() if AST_PLUGINS.get("pmbot"): for i, e in AST_PLUGINS["pmbot"]: event.client.remove_event_handler(i) for i, e in AST_PLUGINS["pmbot"]: event.client.add_event_handler(i, events.NewMessage(**e)) await event.edit( "Done! Now u Can Chat With People Via This Bot", buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")], )
@callback("ofchbot", owner=True)async def chon(event): var = "PMBOT" await setit(event, var, "False") if AST_PLUGINS.get("pmbot"): for i, e in AST_PLUGINS["pmbot"]: event.client.remove_event_handler(i) await event.edit( "Done! Chat People Via This Bot Stopped.", buttons=[Button.inline("« Bᴀᴄᴋ", data="cbs_chatbot")], )
@callback("inli_pic", owner=True)async def media(event): await event.delete() pru = event.sender_id var = "INLINE_PIC" name = "Inline Media" async with event.client.conversation(pru) as conv: await conv.send_message( "**Inline Media**\nSend me a pic/gif/ or link to set as inline media.\n\nUse /cancel to terminate the operation.", ) response = await conv.get_response() try: themssg = response.message if themssg == "/cancel": return await conv.send_message( "Operation cancelled!!", buttons=get_back_button("setter"), ) except BaseException as er: LOGS.exception(er) media = await event.client.download_media(response, "inlpic") if ( not (response.text).startswith("/") and response.text != "" and (not response.media or isinstance(response.media, MessageMediaWebPage)) ): url = text_to_url(response) else: try: x = upl(media) url = f"https://graph.org/{x[0]}" remove(media) except BaseException as er: LOGS.exception(er) return await conv.send_message( "Terminated.", buttons=get_back_button("setter"), ) await setit(event, var, url) await conv.send_message( f"{name} has been set.", buttons=get_back_button("setter"), )
FD_MEDIA = {}
@callback(re.compile("fd(.*)"), owner=True)async def fdroid_dler(event): uri = event.data_match.group(1).decode("utf-8") if FD_MEDIA.get(uri): return await event.edit(file=FD_MEDIA[uri]) await event.answer("• Starting Download •", alert=True) await event.edit("• Downloading.. •") URL = f"https://f-droid.org/packages/{uri}" conte = await async_searcher(URL, re_content=True) BSC = bs(conte, "html.parser", from_encoding="utf-8") dl_ = BSC.find("p", "package-version-download").find("a")["href"] title = BSC.find("h3", "package-name").text.strip() thumb = BSC.find("img", "package-icon")["src"] if thumb.startswith("/"): thumb = f"https://f-droid.org{thumb}" thumb, _ = await fast_download(thumb, filename=f"{uri}.png") s_time = time.time() file, _ = await fast_download( dl_, filename=f"{title}.apk", progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, event, s_time, "Downloading...", ) ), )
time.time() n_file = await event.client.fast_uploader( file, show_progress=True, event=event, message="Uploading...", to_delete=True ) buttons = Button.switch_inline("Search Back", query="fdroid", same_peer=True) try: msg = await event.edit( f"**• [{title}]({URL}) •**", file=n_file, thumb=thumb, buttons=buttons ) except Exception as er: LOGS.exception(er) try: msg = await event.client.edit_message( await event.get_input_chat(), event.message_id, f"**• [{title}]({URL}) •**", buttons=buttons, thumb=thumb, file=n_file, ) except Exception as er: os.remove(thumb) LOGS.exception(er) return await event.edit(f"**ERROR**: `{er}`", buttons=buttons) if msg and hasattr(msg, "media"): FD_MEDIA.update({uri: msg.media}) os.remove(thumb)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317# Ultroid - UserBot# Copyright (C) 2021-2024 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""• `{i}akinator` | `/akinator` Start akinator game from Userbot/Assistant
• `/startgame` Open Portal for Games"""
import asyncioimport re
from akipy.async_akipy import Akinator, akipyLOGSfrom telethon.errors.rpcerrorlist import BotMethodInvalidErrorfrom telethon.events import Rawfrom telethon.tl.types import InputMediaPoll, Poll, PollAnswer, UpdateMessagePollVote
from pyUltroid._misc._decorators import ultroid_cmdfrom pyUltroid.fns.helper import inline_mentionfrom pyUltroid.fns.tools import async_searcher
from . import * # Ensure this import matches your project structure
games = {}aki_photo = "https://graph.org/file/3cc8825c029fd0cab9edc.jpg"
@ultroid_cmd(pattern="akinator")async def akina(e): sta = Akinator() games[e.chat_id] = {e.id: sta} LOGS.info(f"Game started for chat {e.chat_id} with ID {e.id}.") try: m = await e.client.inline_query(asst.me.username, f"aki_{e.chat_id}_{e.id}") await m[0].click(e.chat_id) akipyLOGS.info(f"Clicked inline result for chat {e.chat_id}") except BotMethodInvalidError as err: akipyLOGS.error(f"BotMethodInvalidError: {err}") await asst.send_file( e.chat_id, aki_photo, buttons=Button.inline(get_string("aki_2"), data=f"aki_{e.chat_id}_{e.id}"), ) except Exception as er: akipyLOGS.error(f"Unexpected error: {er}") return await e.eor(f"ERROR : {er}") if e.out: await e.delete()
@asst_cmd(pattern="akinator", owner=True)async def _akokk(e): await akina(e)
@callback(re.compile("aki_(.*)"), owner=True)async def doai(e): adt = e.pattern_match.group(1).strip().decode("utf-8") dt = adt.split("_") ch = int(dt[0]) mid = int(dt[1]) await e.edit(get_string("com_1")) try: await games[ch][mid].start_game(child_mode=False) bts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Yes", "No", "Idk"]] cts = [Button.inline(o, f"aka_{adt}_{o}") for o in ["Probably", "Probably Not"]] bts = [bts, cts] await e.edit(f"Q. {games[ch][mid].question}", buttons=bts) except KeyError: return await e.answer(get_string("aki_1"), alert=True)
@callback(re.compile("aka_(.*)"), owner=True)async def okah(e): try: mk = e.pattern_match.group(1).decode("utf-8").split("_") #akipyLOGS.info(f"Parsed values: {mk}")
if len(mk) < 3: akipyLOGS.error("Pattern match did not return enough parts.") return await e.answer("Invalid data received.", alert=True)
ch = int(mk[0]) mid = int(mk[1]) ans = mk[2]
gm = games[ch][mid] await gm.answer(ans)
# Check for the final guess in the API response if gm.name_proposition and gm.description_proposition: gm.win = True text = f"It's {gm.name_proposition}\n{gm.description_proposition}" await e.edit(text, file=gm.photo) else: # Game is not won yet, continue asking questions buttons = [ [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Yes", "No", "Idk"]], [Button.inline(o, f"aka_{ch}_{mid}_{o}") for o in ["Probably", "Probably Not"]], ] await e.edit(gm.question, buttons=buttons)
except KeyError: await e.answer(get_string("aki_3")) except Exception as ex: akipyLOGS.error(f"An unexpected error occurred: {ex}")
@in_pattern(re.compile("aki_?(.*)"), owner=True)async def eiagx(e): bts = Button.inline(get_string("aki_2"), data=e.text) ci = types.InputWebDocument(aki_photo, 0, "image/jpeg", []) ans = [ await e.builder.article( "Akinator", type="photo", content=ci, text="Akinator", thumb=ci, buttons=bts, include_media=True, ) ] await e.answer(ans)
# ----------------------- Main Command ------------------- #
GIMAGES = [ "https://graph.org/file/1c51015bae5205a65fd69.jpg", "https://imgwhale.xyz/3xyr322l64j9590",]
@asst_cmd(pattern="startgame", owner=True)async def magic(event): buttons = [ [Button.inline("Trivia Quiz", "trzia")], [Button.inline("Cancel ❌", "delit")], ] await event.reply( get_string("games_1"), file=choice(GIMAGES), buttons=buttons, )
# -------------------------- Trivia ----------------------- #
TR_BTS = {}DIFI_KEYS = ["Easy", "Medium", "Hard"]TRIVIA_CHATS = {}POLLS = {}CONGO_STICKER = [ "CAADAgADSgIAAladvQrJasZoYBh68AI", "CAADAgADXhIAAuyZKUl879mlR_dkOwI", "CAADAgADpQAD9wLID-xfZCDwOI5LAg", "CAADAgADjAADECECEFZM-SrKO9GgAg", "CAADAgADSwIAAj-VzArAzNCDiGWAHAI", "CAADAgADhQADwZxgDIuMHR9IU10iAg", "CAADAgADiwMAAsSraAuoe2BwYu1sdQI",]
@callback("delit", owner=True)async def delete_it(event): await event.delete()
@callback(re.compile("ctdown(.*)"), owner=True)async def ct_spam(e): n = e.data_match.group(1).decode("utf-8") await e.answer(f"Wait {n} seconds..", alert=True)
@callback(re.compile("trzia(.*)"), owner=True)async def choose_cata(event): match = event.data_match.group(1).decode("utf-8") if not match: if TR_BTS.get("category"): buttons = TR_BTS["category"] else: req = ( await async_searcher( "https://opentdb.com/api_category.php", re_json=True ) )["trivia_categories"] btt = [] for i in req: name = i["name"] if ":" in name: name = name.split(":")[1] btt.append(Button.inline(name, f"trziad_{i['id']}")) buttons = list(zip(btt[::2], btt[1::2])) if len(btt) % 2 == 1: buttons.append((btt[-1],)) buttons.append([Button.inline("Cancel ❌", "delit")]) TR_BTS.update({"category": buttons}) text = get_string("games_2") elif match[0] == "d": cat = match[1:] buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]] buttons.append(get_back_button("trzia")) text = get_string("games_3") elif match[0] == "c": m = match[1:] buttons = [[Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)]] text = get_string("games_4") elif match[0] == "t": m_ = match[1:] buttons = [ [Button.inline(str(i), f"trzias{m_}_{i}") for i in [10, 30, 60, 120]] ] text = get_string("games_5") elif match[0] == "s": chat = event.chat_id cat, le, nu, in_ = match[2:].split("_") msg = await event.edit(get_string("games_6").format(le, nu)) for i in reversed(range(5)): msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}")) await asyncio.sleep(1) await msg.edit( msg.text + "\n\n• Send /cancel to stop the Quiz...", buttons=None ) qsss = await async_searcher( f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}", re_json=True, ) qs = qsss["results"] if not qs: await event.respond("Sorry, No Question Found for the given Criteria..") await event.delete() return TRIVIA_CHATS.update({chat: {}}) for copper, q in enumerate(qs): if TRIVIA_CHATS[chat].get("cancel") is not None: break ansi = str(uuid.uuid1()).split("-")[0].encode() opts = [PollAnswer(unescape(q["correct_answer"]), ansi)] [ opts.append( PollAnswer(unescape(a), str(uuid.uuid1()).split("-")[0].encode()) ) for a in q["incorrect_answers"] ] shuffle(opts) poll = InputMediaPoll( Poll( 0, f"[{copper+1}]. " + unescape(q["question"]), answers=opts, public_voters=True, quiz=True, close_period=int(in_), ), correct_answers=[ansi], solution="Join @TeamUltroid", solution_entities=[], ) m_ = await event.client.send_message(chat, file=poll) POLLS.update({m_.poll.poll.id: {"chat": m_.chat_id, "answer": ansi}}) await asyncio.sleep(int(in_)) if not TRIVIA_CHATS[chat]: await event.respond( "No-One Got Any Score in the Quiz!\nBetter Luck Next Time!" ) else: try: await event.respond(file=choice(CONGO_STICKER)) except ChatSendStickersForbiddenError: pass LBD = "🎯 **Scoreboard of the Quiz.**\n\n" TRC = TRIVIA_CHATS[chat] if "cancel" in TRC.keys(): del TRC["cancel"] for userid, user_score in dict( sorted(TRC.items(), key=operator.itemgetter(1), reverse=True) ).items(): user = inline_mention(await event.client.get_entity(userid)) LBD += f"••• {user} - {user_score}\n" await event.respond(LBD) del TRIVIA_CHATS[chat] list_ = list(POLLS.copy().keys()) for key in list_: if POLLS[key]["chat"] == chat: del POLLS[key] return await event.edit(text, buttons=buttons)
@asst.on( Raw(UpdateMessagePollVote, func=lambda x: TRIVIA_CHATS and POLLS.get(x.poll_id)))async def pollish(eve): if POLLS.get(eve.poll_id)["chat"] not in TRIVIA_CHATS.keys(): return if POLLS[eve.poll_id]["answer"] != eve.options[0]: return chat = POLLS.get(eve.poll_id)["chat"] user = eve.user_id if not TRIVIA_CHATS.get(chat, {}).get(user): TRIVIA_CHATS[chat][user] = 1 else: TRIVIA_CHATS[chat][user] += 1
@asst_cmd("cancel", owner=True, func=lambda x: TRIVIA_CHATS.get(x.chat_id))async def cancelish(event): chat = TRIVIA_CHATS.get(event.chat_id) chat.update({"cancel": True}) await event.respond("Cancelled!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import re
from . import *
STRINGS = { 1: """🎇 **Thanks for Deploying Ultroid Userbot!**
• Here, are the Some Basic stuff from, where you can Know, about its Usage.""", 2: """🎉** About Ultroid**
🧿 Ultroid is Pluggable and powerful Telethon Userbot, made in Python from Scratch. It is Aimed to Increase Security along with Addition of Other Useful Features.
❣ Made by **@TeamUltroid**""", 3: """**💡• FAQs •**
-> [Username Tracker](https://t.me/UltroidUpdates/24)-> [Keeping Custom Addons Repo](https://t.me/UltroidUpdates/28)-> [Disabling Deploy message](https://t.me/UltroidUpdates/27)-> [Setting up TimeZone](https://t.me/UltroidUpdates/22)-> [About Inline PmPermit](https://t.me/UltroidUpdates/21)-> [About Dual Mode](https://t.me/UltroidUpdates/18)-> [Custom Thumbnail](https://t.me/UltroidUpdates/13)-> [About FullSudo](https://t.me/UltroidUpdates/11)-> [Setting Up PmBot](https://t.me/UltroidUpdates/2)-> [Also Check](https://t.me/UltroidUpdates/14)
**• To Know About Updates** - Join @TeamUltroid.""", 4: f"""• `To Know All Available Commands`
- `{HNDLR}help` - `{HNDLR}cmds`""", 5: """• **For Any Other Query or Suggestion** - Move to **@UltroidSupportChat**.
• Thanks for Reaching till END.""",}
@callback(re.compile("initft_(\\d+)"))async def init_depl(e): CURRENT = int(e.data_match.group(1)) if CURRENT == 5: return await e.edit( STRINGS[5], buttons=Button.inline("<< Back", "initbk_4"), link_preview=False, )
await e.edit( STRINGS[CURRENT], buttons=[ Button.inline("<<", f"initbk_{str(CURRENT - 1)}"), Button.inline(">>", f"initft_{str(CURRENT + 1)}"), ], link_preview=False, )
@callback(re.compile("initbk_(\\d+)"))async def ineiq(e): CURRENT = int(e.data_match.group(1)) if CURRENT == 1: return await e.edit( STRINGS[1], buttons=Button.inline("Start Back >>", "initft_2"), link_preview=False, )
await e.edit( STRINGS[CURRENT], buttons=[ Button.inline("<<", f"initbk_{str(CURRENT - 1)}"), Button.inline(">>", f"initft_{str(CURRENT + 1)}"), ], link_preview=False, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import base64import inspectfrom datetime import datetimefrom html import unescapefrom random import choicefrom re import compile as re_compile
from bs4 import BeautifulSoup as bsfrom telethon import Buttonfrom telethon.tl.alltlobjects import LAYER, tlobjectsfrom telethon.tl.types import DocumentAttributeAudio as Audiofrom telethon.tl.types import InputWebDocument as wb
from pyUltroid.fns.misc import google_searchfrom pyUltroid.fns.tools import ( _webupload_cache, async_searcher, get_ofox, saavn_search, webuploader,)
from . import *from . import _ult_cache
SUP_BUTTONS = [ [ Button.url("• Repo •", url="https://github.com/TeamUltroid/Ultroid"), Button.url("• Support •", url="t.me/UltroidSupportChat"), ],]
ofox = "https://graph.org/file/231f0049fcd722824f13b.jpg"gugirl = "https://graph.org/file/0df54ae4541abca96aa11.jpg"ultpic = "https://graph.org/file/4136aa1650bc9d4109cc5.jpg"
apis = [ "QUl6YVN5QXlEQnNZM1dSdEI1WVBDNmFCX3c4SkF5NlpkWE5jNkZV", "QUl6YVN5QkYwenhMbFlsUE1wOXh3TVFxVktDUVJxOERnZHJMWHNn", "QUl6YVN5RGRPS253blB3VklRX2xiSDVzWUU0Rm9YakFLSVFWMERR",]
@in_pattern("ofox", owner=True)async def _(e): try: match = e.text.split(" ", maxsplit=1)[1] except IndexError: kkkk = e.builder.article( title="Enter Device Codename", thumb=wb(ofox, 0, "image/jpeg", []), text="**OFᴏx🦊Rᴇᴄᴏᴠᴇʀʏ**\n\nYou didn't search anything", buttons=Button.switch_inline("Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True), ) return await e.answer([kkkk]) device, releases = await get_ofox(match) if device.get("detail") is None: fox = [] fullname = device["full_name"] codename = device["codename"] str(device["supported"]) maintainer = device["maintainer"]["name"] link = f"https://orangefox.download/device/{codename}" for data in releases["data"]: release = data["type"] version = data["version"] size = humanbytes(data["size"]) release_date = datetime.utcfromtimestamp(data["date"]).strftime("%Y-%m-%d") text = f"[\xad]({ofox})**OʀᴀɴɢᴇFᴏx Rᴇᴄᴏᴠᴇʀʏ Fᴏʀ**\n\n" text += f"` Fᴜʟʟ Nᴀᴍᴇ: {fullname}`\n" text += f"` Cᴏᴅᴇɴᴀᴍᴇ: {codename}`\n" text += f"` Mᴀɪɴᴛᴀɪɴᴇʀ: {maintainer}`\n" text += f"` Bᴜɪʟᴅ Tʏᴘᴇ: {release}`\n" text += f"` Vᴇʀsɪᴏɴ: {version}`\n" text += f"` Sɪᴢᴇ: {size}`\n" text += f"` Bᴜɪʟᴅ Dᴀᴛᴇ: {release_date}`" fox.append( await e.builder.article( title=f"{fullname}", description=f"{version}\n{release_date}", text=text, thumb=wb(ofox, 0, "image/jpeg", []), link_preview=True, buttons=[ Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}"), Button.switch_inline( "Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="ofox ", same_peer=True ), ], ) ) await e.answer( fox, switch_pm="OrangeFox Recovery Search.", switch_pm_param="start" ) else: await e.answer( [], switch_pm="OrangeFox Recovery Search.", switch_pm_param="start" )
@in_pattern("fl2lnk ?(.*)", owner=True)async def _(e): match = e.pattern_match.group(1) chat_id, msg_id = match.split(":") filename = _webupload_cache[int(chat_id)][int(msg_id)] if "/" in filename: filename = filename.split("/")[-1] __cache = f"{chat_id}:{msg_id}" buttons = [ [ Button.inline("anonfiles", data=f"flanonfiles//{__cache}"), Button.inline("transfer", data=f"fltransfer//{__cache}"), ], [ Button.inline("bayfiles", data=f"flbayfiles//{__cache}"), Button.inline("x0.at", data=f"flx0.at//{__cache}"), ], [ Button.inline("file.io", data=f"flfile.io//{__cache}"), Button.inline("siasky", data=f"flsiasky//{__cache}"), ], ] try: lnk = [ await e.builder.article( title=f"Upload {filename}", text=f"**File:**\n{filename}", buttons=buttons, ) ] except BaseException as er: LOGS.exception(er) lnk = [ await e.builder.article( title="fl2lnk", text="File not found", ) ] await e.answer(lnk, switch_pm="File to Link.", switch_pm_param="start")
@callback( re_compile( "fl(.*)", ), owner=True,)async def _(e): t = (e.data).decode("UTF-8") data = t[2:] host = data.split("//")[0] chat_id, msg_id = data.split("//")[1].split(":") filename = _webupload_cache[int(chat_id)][int(msg_id)] if "/" in filename: filename = filename.split("/")[-1] await e.edit(f"Uploading `{filename}` on {host}") link = (await webuploader(chat_id, msg_id, host)).strip().replace("\n", "") await e.edit(f"Uploaded `{filename}` on {host}.", buttons=Button.url("View", link))
@in_pattern("repo", owner=True)async def repo(e): res = [ await e.builder.article( title="Ultroid Userbot", description="Userbot | Telethon", thumb=wb(ultpic, 0, "image/jpeg", []), text="• **ULTROID USERBOT** •", buttons=SUP_BUTTONS, ), ] await e.answer(res, switch_pm="Ultroid Repo.", switch_pm_param="start")
@in_pattern("go", owner=True)async def gsearch(q_event): try: match = q_event.text.split(maxsplit=1)[1] except IndexError: return await q_event.answer( [], switch_pm="Google Search. Enter a query!", switch_pm_param="start" ) searcher = [] gresults = await google_search(match) for i in gresults: try: title = i["title"] link = i["link"] desc = i["description"] searcher.append( await q_event.builder.article( title=title, description=desc, thumb=wb(gugirl, 0, "image/jpeg", []), text=f"**Gᴏᴏɢʟᴇ Sᴇᴀʀᴄʜ**\n\n**••Tɪᴛʟᴇ••**\n`{title}`\n\n**••Dᴇsᴄʀɪᴘᴛɪᴏɴ••**\n`{desc}`", link_preview=False, buttons=[ [Button.url("Lɪɴᴋ", url=f"{link}")], [ Button.switch_inline( "Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="go ", same_peer=True, ), Button.switch_inline( "Sʜᴀʀᴇ", query=f"go {match}", same_peer=False, ), ], ], ), ) except IndexError: break await q_event.answer(searcher, switch_pm="Google Search.", switch_pm_param="start")
@in_pattern("mods", owner=True)async def _(e): try: quer = e.text.split(" ", maxsplit=1)[1] except IndexError: return await e.answer( [], switch_pm="Mod Apps Search. Enter app name!", switch_pm_param="start" ) start = 0 * 3 + 1 da = base64.b64decode(choice(apis)).decode("ascii") url = f"https://www.googleapis.com/customsearch/v1?key={da}&cx=25b3b50edb928435b&q={quer}&start={start}" data = await async_searcher(url, re_json=True) search_items = data.get("items", []) modss = [] for a in search_items: title = a.get("title") desc = a.get("snippet") link = a.get("link") text = f"**••Tɪᴛʟᴇ••** `{title}`\n\n" text += f"**Dᴇsᴄʀɪᴘᴛɪᴏɴ** `{desc}`" modss.append( await e.builder.article( title=title, description=desc, text=text, link_preview=True, buttons=[ [Button.url("Dᴏᴡɴʟᴏᴀᴅ", url=f"{link}")], [ Button.switch_inline( "Mᴏʀᴇ Mᴏᴅs", query="mods ", same_peer=True, ), Button.switch_inline( "Sʜᴀʀᴇ", query=f"mods {quer}", same_peer=False, ), ], ], ), ) await e.answer(modss, switch_pm="Search Mod Applications.", switch_pm_param="start")
APP_CACHE = {}RECENTS = {}PLAY_API = "https://googleplay.onrender.com/api/apps?q="
@in_pattern("app", owner=True)async def _(e): try: f = e.text.split(maxsplit=1)[1].lower() except IndexError: get_string("instu_1") res = [] if APP_CACHE and RECENTS.get(e.sender_id): res.extend( APP_CACHE[a][0] for a in RECENTS[e.sender_id] if APP_CACHE.get(a) ) return await e.answer( res, switch_pm=get_string("instu_2"), switch_pm_param="start" ) try: return await e.answer( APP_CACHE[f], switch_pm="Application Searcher.", switch_pm_param="start" ) except KeyError: pass foles = [] url = PLAY_API + f.replace(" ", "+") aap = await async_searcher(url, re_json=True) for z in aap["results"][:50]: url = "https://play.google.com/store/apps/details?id=" + z["appId"] name = z["title"] desc = unescape(z["summary"])[:300].replace("<br>", "\n") + "..." dev = z["developer"]["devId"] text = f"**••Aᴘᴘ Nᴀᴍᴇ••** [{name}]({url})\n" text += f"**••Dᴇᴠᴇʟᴏᴘᴇʀ••** `{dev}`\n" text += f"**••Dᴇsᴄʀɪᴘᴛɪᴏɴ••**\n`{desc}`" foles.append( await e.builder.article( title=name, description=dev, thumb=wb(z["icon"], 0, "image/jpeg", []), text=text, link_preview=True, buttons=[ [Button.url("Lɪɴᴋ", url=url)], [ Button.switch_inline( "Mᴏʀᴇ Aᴘᴘs", query="app ", same_peer=True, ), Button.switch_inline( "Sʜᴀʀᴇ", query=f"app {f}", same_peer=False, ), ], ], ), ) APP_CACHE.update({f: foles}) if RECENTS.get(e.sender_id): RECENTS[e.sender_id].append(f) else: RECENTS.update({e.sender_id: [f]}) await e.answer(foles, switch_pm="Application Searcher.", switch_pm_param="start")
PISTON_URI = "https://emkc.org/api/v2/piston/"PISTON_LANGS = {}
@in_pattern("run", owner=True)async def piston_run(event): try: lang = event.text.split()[1] code = event.text.split(maxsplit=2)[2] except IndexError: result = await event.builder.article( title="Bad Query", description="Usage: [Language] [code]", thumb=wb( "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", [] ), text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)', ) return await event.answer([result]) if not PISTON_LANGS: se = await async_searcher(f"{PISTON_URI}runtimes", re_json=True) PISTON_LANGS.update({lang.pop("language"): lang for lang in se}) if lang in PISTON_LANGS.keys(): version = PISTON_LANGS[lang]["version"] else: result = await event.builder.article( title="Unsupported Language", description="Usage: [Language] [code]", thumb=wb( "https://graph.org/file/e33c57fc5f1044547e4d8.jpg", 0, "image/jpeg", [] ), text=f'**Inline Usage**\n\n`@{asst.me.username} run python print("hello world")`\n\n[Language List](https://graph.org/Ultroid-09-01-6)', ) return await event.answer([result]) output = await async_searcher( f"{PISTON_URI}execute", post=True, json={ "language": lang, "version": version, "files": [{"content": code}], }, re_json=True, )
output = output["run"]["output"] or get_string("instu_4") if len(output) > 3000: output = f"{output[:3000]}..." result = await event.builder.article( title="Result", description=output, text=f"• **Language:**\n`{lang}`\n\n• **Code:**\n`{code}`\n\n• **Result:**\n`{output}`", thumb=wb( "https://graph.org/file/871ee4a481f58117dccc4.jpg", 0, "image/jpeg", [] ), buttons=Button.switch_inline("Fork", query=event.text, same_peer=True), ) await event.answer([result], switch_pm="• Piston •", switch_pm_param="start")
FDROID_ = {}
@in_pattern("fdroid", owner=True)async def do_magic(event): try: match = event.text.split(" ", maxsplit=1)[1].lower() except IndexError: return await event.answer( [], switch_pm="Enter Query to Search", switch_pm_param="start" ) if FDROID_.get(match): return await event.answer( FDROID_[match], switch_pm=f"• Results for {match}", switch_pm_param="start" ) link = "https://search.f-droid.org/?q=" + match.replace(" ", "+") content = await async_searcher(link, re_content=True) BSC = bs(content, "html.parser", from_encoding="utf-8") ress = [] for dat in BSC.find_all("a", "package-header")[:10]: image = dat.find("img", "package-icon")["src"] if image.endswith("/"): image = "https://graph.org/file/a8dd4a92c5a53a89d0eff.jpg" title = dat.find("h4", "package-name").text.strip() desc = dat.find("span", "package-summary").text.strip() text = f"• **Name :** `{title}`\n\n" text += f"• **Description :** `{desc}`\n" text += f"• **License :** `{dat.find('span', 'package-license').text.strip()}`" imga = wb(image, 0, "image/jpeg", []) ress.append( await event.builder.article( title=title, type="photo", description=desc, text=text, content=imga, thumb=imga, include_media=True, buttons=[ Button.inline( "• Download •", "fd" + dat["href"].split("packages/")[-1] ), Button.switch_inline("• Share •", query=event.text), ], ) ) msg = f"Showing {len(ress)} Results!" if ress else "No Results Found" FDROID_.update({match: ress}) await event.answer(ress, switch_pm=msg, switch_pm_param="start")
# Thanks to OpenSource_bearer_collected = [ "AAAAAAAAAAAAAAAAAAAAALIKKgEAAAAA1DRuS%2BI7ZRKiagD6KHYmreaXomo%3DP5Vaje4UTtEkODg0fX7nCh5laSrchhtLxeyEqxXpv0w9ZKspLD", "AAAAAAAAAAAAAAAAAAAAAL5iUAEAAAAAmo6FYRjqdKlI3cNziIm%2BHUQB9Xs%3DS31pj0mxARMTOk2g9dvQ1yP9wknvY4FPBPUlE00smJcncw4dPR", "AAAAAAAAAAAAAAAAAAAAAN6sVgEAAAAAMMjMMWrwgGyv7YQOWN%2FSAsO5SGM%3Dg8MG9Jq93Rlllaok6eht7HvRCruN4Vpzp4NaVsZaaHHWSTzKI8",]
@in_pattern("twitter", owner=True)async def twitter_search(event): try: match = event.text.split(maxsplit=1)[1].lower() except IndexError: return await event.answer( [], switch_pm="Enter Query to Search", switch_pm_param="start" ) try: return await event.answer( _ult_cache["twitter"][match], switch_pm="• Twitter Search •", switch_pm_param="start", ) except KeyError: pass headers = {"Authorization": f"bearer {choice(_bearer_collected)}"} res = await async_searcher( f"https://api.twitter.com/1.1/users/search.json?q={match}", headers=headers, re_json=True, ) reso = [] for user in res: thumb = wb(user["profile_image_url_https"], 0, "image/jpeg", []) if user.get("profile_banner_url"): url = user["profile_banner_url"] text = f"[\xad]({url})• **Name :** `{user['name']}`\n" else: text = f"• **Name :** `{user['name']}`\n" text += f"• **Description :** `{user['description']}`\n" text += f"• **Username :** `@{user['screen_name']}`\n" text += f"• **Followers :** `{user['followers_count']}` • **Following :** `{user['friends_count']}`\n" pro_ = "https://twitter.com/" + user["screen_name"] text += f"• **Link :** [Click Here]({pro_})\n_" reso.append( await event.builder.article( title=user["name"], description=user["description"], url=pro_, text=text, thumb=thumb, ) ) swi_ = f"🐦 Showing {len(reso)} Results!" if reso else "No User Found :(" await event.answer(reso, switch_pm=swi_, switch_pm_param="start") if _ult_cache.get("twitter"): _ult_cache["twitter"].update({match: reso}) else: _ult_cache.update({"twitter": {match: reso}})
_savn_cache = {}
@in_pattern("saavn", owner=True)async def savn_s(event): try: query = event.text.split(maxsplit=1)[1].lower() except IndexError: return await event.answer( [], switch_pm="Enter Query to search 🔍", switch_pm_param="start" ) if query in _savn_cache: return await event.answer( _savn_cache[query], switch_pm=f"Showing Results for {query}", switch_pm_param="start", ) results = await saavn_search(query) swi = "🎵 Saavn Search" if results else "No Results Found!" res = [] for song in results: thumb = wb(song["image"], 0, "image/jpeg", []) text = f"• **Title :** {song['title']}" text += f"\n• **Year :** {song['year']}" text += f"\n• **Lang :** {song['language']}" text += f"\n• **Artist :** {song['artists']}" text += f"\n• **Release Date :** {song['release_date']}" res.append( await event.builder.article( title=song["title"], description=song["artists"], type="audio", text=text, include_media=True, buttons=Button.switch_inline( "Search Again 🔍", query="saavn", same_peer=True ), thumb=thumb, content=wb( song["url"], 0, "audio/mp4", [ Audio( title=song["title"], duration=int(song["duration"]), performer=song["artists"], ) ], ), ) ) await event.answer(res, switch_pm=swi, switch_pm_param="start") _savn_cache.update({query: res})
@in_pattern("tl", owner=True)async def inline_tl(ult): try: match = ult.text.split(maxsplit=1)[1] except IndexError: text = f"**Telegram TlObjects Searcher.**\n__(Don't use if you don't know what it is!)__\n\n• Example Usage\n`@{asst.me.username} tl GetFullUserRequest`" return await ult.answer( [ await ult.builder.article( title="How to Use?", description="Tl Searcher by Ultroid", url="https://t.me/TeamUltroid", text=text, ) ], switch_pm="Tl Search 🔍", switch_pm_param="start", ) res = [] for key in tlobjects.values(): if match.lower() in key.__name__.lower(): tyyp = "Function" if "tl.functions." in str(key) else "Type" text = f"**Name:** `{key.__name__}`\n" text += f"**Category:** `{tyyp}`\n" text += f"\n`from {key.__module__} import {key.__name__}`\n\n" if args := str(inspect.signature(key))[1:][:-1]: text += "**Parameter:**\n" for para in args.split(","): text += " " * 4 + "`" + para + "`\n" text += f"\n**Layer:** `{LAYER}`" res.append( await ult.builder.article( title=key.__name__, description=tyyp, url="https://t.me/TeamUltroid", text=text[:4000], ) ) mo = f"Showing {len(res)} results!" if res else f"No Results for {match}!" await ult.answer(res[:50], switch_pm=mo, switch_pm_param="start")
InlinePlugin.update( { "Pʟᴀʏ Sᴛᴏʀᴇ Aᴘᴘs": "app telegram", "Mᴏᴅᴅᴇᴅ Aᴘᴘs": "mods minecraft", "Sᴇᴀʀᴄʜ Oɴ Gᴏᴏɢʟᴇ": "go TeamUltroid", "WʜɪSᴘᴇʀ": "wspr @username Hello🎉", "YᴏᴜTᴜʙᴇ Dᴏᴡɴʟᴏᴀᴅᴇʀ": "yt Ed Sheeran Perfect", "Piston Eval": "run javascript console.log('Hello Ultroid')", "OʀᴀɴɢᴇFᴏx🦊": "ofox beryllium", "Tᴡɪᴛᴛᴇʀ Usᴇʀ": "twitter theultroid", "Fᴅʀᴏɪᴅ Sᴇᴀʀᴄʜ": "fdroid telegram", "Sᴀᴀᴠɴ sᴇᴀʀᴄʜ": "saavn", "Tʟ Sᴇᴀʀᴄʜ": "tl", })1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import re
from . import ( Button, ULTConfig, callback, get_back_button, get_languages, get_string, udB,)
@callback("lang", owner=True)async def setlang(event): languages = get_languages() tultd = [ Button.inline( f"{languages[ult]['natively']} [{ult.lower()}]", data=f"set_{ult}", ) for ult in languages ] buttons = list(zip(tultd[::2], tultd[1::2])) if len(tultd) % 2 == 1: buttons.append((tultd[-1],)) buttons.append([Button.inline("« Back", data="mainmenu")]) await event.edit(get_string("ast_4"), buttons=buttons)
@callback(re.compile(b"set_(.*)"), owner=True)async def settt(event): lang = event.data_match.group(1).decode("UTF-8") languages = get_languages() ULTConfig.lang = lang udB.del_key("language") if lang == "en" else udB.set_key("language", lang) await event.edit( f"Your language has been set to {languages[lang]['natively']} [{lang}].", buttons=get_back_button("lang"), )1234567891011# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from pyUltroid._misc._decorators import ultroid_cmdfrom pyUltroid.fns.helper import inline_mention
from .. import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from . import *
START = """🪅 **Help Menu** 🪅
✘ /start : Check I am Alive or not.✘ /help : Get This Message.✘ /repo : Get Bot's Repo..
🧑💻 Join **@TeamUltroid**"""
ADMINTOOLS = """✘ **AdminTools** ✘
• /pin : Pins the Replied Message• /pinned : Get Pinned message in chat.• /unpin : Unpin the Replied message• /unpin all : Unpin all Pinned Messages.
• /ban (username/id/reply) : Ban the User• /unban (username/id/reply) : UnBan the User.
• /mute (username/id/reply) : Mute the User.• /unmute (username/id/reply) : Unmute the User.
• /tban (username/id/reply) (time) : Temporary ban a user• /tmute (username/id/reply) (time) : temporary Mutes a User.
• /purge (purge messages)
• /setgpic (reply photo) : keep Chat Photo of Group.• /delgpic : remove current chat Photo."""
UTILITIES = """✘ ** Utilities ** ✘
• /info (reply/username/id) : get detailed info of user.• /id : get chat/user id.• /tr : Translate Languages..• /q : Create Quotes.
• /paste (reply file/text) : paste content on Spaceb.in• /meaning (text) : Get Meaning of that Word.• /google (query) : Search Something on Google..
• /suggest (query/reply) : Creates a Yes / No Poll."""
LOCKS = """✘ ** Locks ** ✘
• /lock (query) : lock particular content in chat.• /unlock (query) : Unlock some content.
• All Queries- `msgs` : for messages.- `inlines` : for inline queries.- `media` : for all medias.- `games` : for games.- `sticker` : for stickers.- `polls` : for polls.- `gif` : for gifs.- `pin` : for pins.- `changeinfo` : for change info right."""
MISC = """✘ **Misc** ✘
• /joke : Get Random Jokes.• /decide : Decide Something..
**✘ Stickertools ✘**• /kang : add sticker to your pack.• /listpack : get all of yours pack.."""
STRINGS = {"Admintools": ADMINTOOLS, "locks": LOCKS, "Utils": UTILITIES, "Misc": MISC}
MNGE = udB.get_key("MNGR_EMOJI") or "•"
def get_buttons(): BTTS = [] keys = STRINGS.copy() while keys: BT = [] for i in list(keys)[:2]: text = f"{MNGE} {i} {MNGE}" BT.append(Button.inline(text, f"hlp_{i}")) del keys[i] BTTS.append(BT) url = f"https://t.me/{asst.me.username}?startgroup=true" BTTS.append([Button.url("Add me to Group", url)]) return BTTS
@asst_cmd(pattern="help")async def helpish(event): if not event.is_private: url = f"https://t.me/{asst.me.username}?start=start" return await event.reply( "Contact me in PM for help!", buttons=Button.url("Click me for Help", url) ) if str(event.sender_id) in owner_and_sudos() and ( udB.get_key("DUAL_MODE") and (udB.get_key("DUAL_HNDLR") == "/") ): return await event.reply(START, buttons=get_buttons())
@callback("mngbtn", owner=True)async def ehwhshd(e): buttons = get_buttons() buttons.append([Button.inline("<< Back", "open")]) await e.edit(buttons=buttons)
@callback("mnghome")async def home_aja(e): await e.edit(START, buttons=get_buttons())
@callback(re.compile("hlp_(.*)"))async def do_something(event): match = event.pattern_match.group(1).strip().decode("utf-8") await event.edit(STRINGS[match], buttons=Button.inline("<< Back", "mnghome"))1234567891011121314151617181920212223# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from telethon import events
from . import *
@asst.on(events.ChatAction(func=lambda x: x.user_added))async def dueha(e): user = await e.get_user() if not user.is_self: return sm = udB.get_key("ON_MNGR_ADD") if sm == "OFF": return if not sm: sm = "Thanks for Adding me :)" await e.reply(sm, link_preview=False)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import re
from telethon.errors.rpcerrorlist import UserNotParticipantError
from pyUltroid import _ult_cache
from . import *
@ultroid_cmd(pattern="d(kick|ban)", manager=True, require="ban_users")async def dowj(e): replied = await e.get_reply_message() if replied: user = replied.sender_id else: return await e.eor("Reply to a message...") try: await replied.delete() if e.pattern_match.group(1).strip() == "kick": await e.client.kick_participant(e.chat_id, user) te = "Kicked" else: await e.client.edit_permissions(e.chat_id, user, view_messages=False) te = "Banned" await e.eor(f"{te} Successfully!") except Exception as E: await e.eor(str(E))
@callback(re.compile("cc_(.*)"), func=_ult_cache.get("admin_callback"))async def callback_(event): data = event.data_match.group(1).decode("utf-8") if data not in _ult_cache.get("admin_callback", {}): return try: perm = await event.client.get_permissions(event.chat_id, event.sender_id) except UserNotParticipantError: return await event.answer("Join the Group First!", alert=True) if not perm.is_admin: return await event.answer("You are not an Admin!", alert=True) _ult_cache["admin_callback"].update({data: (event.sender, perm)}) await event.answer("Verification Done!") await event.delete()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from datetime import datetime as dt
from telethon.events import NewMessagefrom telethon.tl.types import ( Message, MessageEntityMention, MessageEntityMentionName, User,)from telethon.utils import get_display_name
from pyUltroid.fns.helper import inline_mention, time_formatter
from . import asst, asst_cmd
AFK = {}
@asst_cmd(pattern="afk", func=lambda x: not x.is_private)async def go_afk(event): sender = await event.get_sender() if (not isinstance(sender, User)) or sender.bot: return try: reason = event.text.split(" ", maxsplit=1)[1] except IndexError: reason = None if event.is_reply and not reason: replied = await event.get_reply_message() if not reason and replied.text and not replied.media: reason = replied.text else: reason = replied time_ = dt.now() if AFK.get(event.chat_id): AFK[event.chat_id].update({event.sender_id: {"reason": reason, "time": time_}}) else: AFK.update( {event.chat_id: {event.sender_id: {"reason": reason, "time": time_}}} ) mention = inline_mention(sender) msg = f"**{mention} went AFK Now!**" if reason and not isinstance(reason, str): await event.reply(reason) else: msg += f"\n\n**Reason : ** `{reason}`" await event.reply(msg)
@asst.on(NewMessage(func=lambda x: AFK.get(x.chat_id) and not x.is_private))async def make_change(event): if event.text.startswith("/afk"): return sender = await event.get_sender() if (not isinstance(sender, User)) or sender.bot: return chat_ = AFK[event.chat_id] if event.sender_id in chat_.keys(): name = get_display_name(event.sender) cha_send = chat_[event.sender_id] time_ = time_formatter((dt.now() - cha_send["time"]).seconds * 1000) msg = f"**{name}** is No Longer AFK!\n**Was AFK for** {time_}" await event.reply(msg) del chat_[event.sender_id] if not chat_: del AFK[event.chat_id] ST_SPAM = [] replied = await event.get_reply_message() if replied: name = get_display_name(replied.sender) if replied.sender_id in chat_.keys(): s_der = chat_[replied.sender_id] res_ = s_der["reason"] time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000) msg = f"**{name}** is AFK Currently!\n**From :** {time_}" if res_ and isinstance(res_, str): msg += f"\n**Reason :** {res_}" elif res_ and isinstance(res_, Message): await event.reply(res_) await event.reply(msg) ST_SPAM.append(replied.sender_id) for ent, text in event.get_entities_text(): dont_send, entity = None, None if isinstance(ent, MessageEntityMentionName): c_id = ent.user_id elif isinstance(ent, MessageEntityMention): c_id = text else: c_id = None if c_id: entity = await event.client.get_entity(c_id) if entity and entity.id in chat_.keys() and entity.id not in ST_SPAM: ST_SPAM.append(entity.id) s_der = chat_[entity.id] name = get_display_name(entity) res_ = s_der["reason"] time_ = time_formatter((dt.now() - s_der["time"]).seconds * 1000) msg = f"**{name}** is AFK Currently!\n**From :** {time_}" if res_ and isinstance(res_, str): msg += f"\n**Reason :** {res_}" elif res_ and isinstance(res_, Message): await event.reply(res_) await event.reply(msg)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import random
import aiohttp
from pyUltroid.dB import DEVLISTfrom pyUltroid.fns.admins import admin_check
from . import *
@asst_cmd(pattern="decide")async def dheh(e): text = ["Yes", "NoU", "Maybe", "IDK"] text = random.choice(text) ri = e.reply_to_msg_id or e.id await e.client.send_message(e.chat_id, text, reply_to=ri)
@asst_cmd(pattern="echo( (.*)|$)")async def oqha(e): if not await admin_check(e): return if match := e.pattern_match.group(1).strip(): text = match reply_to = e elif e.is_reply: text = (await e.get_reply_message()).text reply_to = e.reply_to_msg_id else: return await e.eor("What to Echo?", time=5) try: await e.delete() except BaseException as ex: LOGS.error(ex) await e.client.send_message(e.chat_id, text, reply_to=reply_to)
@asst_cmd(pattern="kickme$")async def doit(e): if e.sender_id in DEVLIST: return await eod(e, "`I will Not Kick You, my Developer..`") try: await e.client.kick_participant(e.chat_id, e.sender_id) except Exception as Fe: return await e.eor(str(Fe), time=5) await e.eor("Yes, You are right, get out.", time=5)
@asst_cmd(pattern="joke$")async def do_joke(e): e = await e.get_reply_message() if e.is_reply else e link = "https://v2.jokeapi.dev/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&type=single" async with aiohttp.ClientSession() as ses: async with ses.get(link) as out: out = await out.json() await e.reply(out["joke"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
import random
from telethon import errorsfrom telethon.errors.rpcerrorlist import StickersetInvalidErrorfrom telethon.tl.functions.messages import GetStickerSetRequest as GetStickerfrom telethon.tl.functions.messages import UploadMediaRequestfrom telethon.tl.functions.stickers import AddStickerToSetRequest as AddStickerfrom telethon.tl.functions.stickers import CreateStickerSetRequestfrom telethon.tl.types import InputPeerSelffrom telethon.tl.types import InputStickerSetItem as SetItemfrom telethon.tl.types import InputStickerSetShortName, Userfrom telethon.utils import get_display_name, get_input_document
from pyUltroid.fns.misc import Quotlyfrom pyUltroid.fns.tools import TgConverter
from . import LOGS, asst, asst_cmd, udB
@asst_cmd( pattern="kang",)async def kang_cmd(ult): sender = await ult.get_sender() if not isinstance(sender, User): return if not ult.is_reply: return await ult.eor("`Reply to a sticker/photo..`", time=5) reply = await ult.get_reply_message() if sender.username: pre = sender.username[:4] else: pre = random.random_string(length=3) animated, dl, video = None, None, None try: emoji = ult.text.split(maxsplit=1)[1] except IndexError: emoji = None if reply.sticker: file = get_input_document(reply.sticker) emoji = emoji or reply.file.emoji name = reply.file.name if name.endswith(".tgs"): animated = True dl = await reply.download_media() elif name.endswith(".webm"): video = True dl = await reply.download_media() elif reply.photo: dl = await reply.download_media() name = "sticker.webp" image = TgConverter.resize_photo_sticker(dl) image.save(name, "WEBP") elif reply.text: dl = await Quotly().create_quotly(reply) else: return await ult.eor("`Reply to sticker or text to add it in your pack...`") if not emoji: emoji = "🏵" if dl: upl = await ult.client.upload_file(dl) file = get_input_document( await ult.client(UploadMediaRequest(InputPeerSelf(), upl)) ) get_ = udB.get_key("STICKERS") or {} type_ = "anim" if animated else "static" if not get_.get(ult.sender_id) or not get_.get(ult.sender_id, {}).get(type_): sn = f"{pre}_{ult.sender_id}" title = f"{get_display_name(sender)}'s Kang Pack" if animated: type_ = "anim" sn += "_anim" title += " (Animated)" elif video: type_ = "vid" sn += "_vid" title += " (Video)" sn += f"_by_{asst.me.username}" try: await asst(GetSticker(InputStickerSetShortName(sn), hash=0)) sn = sn.replace(str(ult.sender_id), f"{ult.sender_id}_{ult.id}") except StickersetInvalidError: pass try: pack = await ult.client( CreateStickerSetRequest( user_id=sender.id, title=title, short_name=sn, stickers=[SetItem(file, emoji=emoji)], videos=video, animated=animated, software="@TeamUltroid", ) ) except Exception as er: return await ult.eor(str(er)) sn = pack.set.short_name if not get_.get(ult.sender_id): get_.update({ult.sender_id: {type_: [sn]}}) else: get_[ult.sender_id].update({type_: [sn]}) udB.set_key("STICKERS", get_) return await ult.reply( f"**Kanged Successfully!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})" ) name = get_[ult.sender_id][type_][-1] try: await asst(GetSticker(InputStickerSetShortName(name), hash=0)) except StickersetInvalidError: get_[ult.sender_id][type_].remove(name) try: await asst( AddSticker(InputStickerSetShortName(name), SetItem(file, emoji=emoji)) ) except (errors.StickerpackStickersTooMuchError, errors.StickersTooMuchError): sn = f"{pre}{ult.sender_id}_{ult.id}" title = f"{get_display_name(sender)}'s Kang Pack" if animated: sn += "_anim" title += " (Animated)" elif video: sn += "_vid" title += "(Video)" sn += f"_by_{asst.me.username}" try: pack = await ult.client( CreateStickerSetRequest( user_id=sender.id, title=title, short_name=sn, stickers=[SetItem(file, emoji=emoji)], animated=animated, ) ) except Exception as er: return await ult.eor(str(er)) get_[ult.sender_id][type_].append(pack.set.short_name) udB.set_key("STICKERS", get_) return await ult.reply( f"**Created New Kang Pack!\nEmoji :** {emoji}\n**Link :** [Click Here](https://t.me/addstickers/{sn})" ) except Exception as er: LOGS.exception(er) return await ult.reply(str(er)) await ult.reply( f"Sticker Added to Pack Successfully\n**Link :** [Click Here](https://t.me/addstickers/{name})" )
@asst_cmd(pattern="listpack")async def do_magic(ult): ko = udB.get_key("STICKERS") or {} if not ko.get(ult.sender_id): return await ult.reply("No Sticker Pack Found!") al_ = [] ul = ko[ult.sender_id] for _ in ul.keys(): al_.extend(ul[_]) msg = "• **Stickers Owned by You!**\n\n" for _ in al_: try: pack = await ult.client(GetSticker(InputStickerSetShortName(_), hash=0)) msg += f"• [{pack.set.title}](https://t.me/addstickers/{_})\n" except StickerSetInvalidError: if ul.get("anim") and _ in ul["anim"]: ul["anim"].remove(_) elif ul.get("vid") and _ in ul["vid"]: ul["vid"].remove(_) else: ul["static"].remove(_) udB.set_key("STICKERS", ko) await ult.reply(msg)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
# https://github.com/xditya/TeleBot/blob/master/telebot/plugins/mybot/pmbot/incoming.py
# --------------------------------------- Imports -------------------------------------------- #
import os
from telethon.errors.rpcerrorlist import UserNotParticipantErrorfrom telethon.tl.custom import Buttonfrom telethon.tl.functions.channels import GetFullChannelRequestfrom telethon.tl.functions.messages import GetFullChatRequestfrom telethon.tl.types import Channel, Chatfrom telethon.utils import get_display_name
from pyUltroid.dB.base import KeyManagerfrom pyUltroid.dB.botchat_db import *from pyUltroid.fns.helper import inline_mention
from . import *
botb = KeyManager("BOTBLS", cast=list)FSUB = udB.get_key("PMBOT_FSUB")CACHE = {}# --------------------------------------- Incoming -------------------------------------------- #
@asst_cmd( load=AST_PLUGINS, incoming=True, func=lambda e: e.is_private and not botb.contains(e.sender_id),)async def on_new_mssg(event): who = event.sender_id # doesn't reply to that user anymore if event.text.startswith("/") or who == OWNER_ID: return if FSUB: MSG = "" BTTS = [] for chat in FSUB: try: await event.client.get_permissions(chat, event.sender_id) except UserNotParticipantError: if not MSG: MSG += get_string("pmbot_1") try: uri = "" TAHC_ = await event.client.get_entity(chat) if hasattr(TAHC_, "username") and TAHC_.username: uri = f"t.me/{TAHC_.username}" elif CACHE.get(chat): uri = CACHE[chat] else: if isinstance(TAHC_, Channel): FUGB = await event.client(GetFullChannelRequest(chat)) elif isinstance(TAHC_, Chat): FUGB = await event.client(GetFullChatRequest(chat)) else: return if FUGB.full_chat.exported_invite: CACHE[chat] = FUGB.full_chat.exported_invite.link uri = CACHE[chat] BTTS.append(Button.url(get_display_name(TAHC_), uri)) except Exception as er: LOGS.exception(f"Error On PmBot Force Sub!\n - {chat} \n{er}") if MSG and BTTS: return await event.reply(MSG, buttons=BTTS) xx = await event.forward_to(OWNER_ID) if event.fwd_from: await xx.reply(f"From {inline_mention(event.sender)} [`{event.sender_id}`]") add_stuff(xx.id, who)
# --------------------------------------- Outgoing -------------------------------------------- #
@asst_cmd( load=AST_PLUGINS, from_users=[OWNER_ID], incoming=True, func=lambda e: e.is_private and e.is_reply,)async def on_out_mssg(event): x = event.reply_to_msg_id to_user = get_who(x) if event.text.startswith("/who"): try: k = await asst.get_entity(to_user) photu = await event.client.download_profile_photo(k.id) await event.reply( f"• **Name :** {get_display_name(k)}\n• **ID :** `{k.id}`\n• **Link :** {inline_mention(k)}", file=photu, ) if photu: os.remove(photu) return except BaseException as er: return await event.reply(f"**ERROR : **{str(er)}") elif event.text.startswith("/"): return if to_user: await asst.send_message(to_user, event.message)
# --------------------------------------- Ban/Unban -------------------------------------------- #
@asst_cmd( pattern="ban", load=AST_PLUGINS, from_users=[OWNER_ID], func=lambda x: x.is_private,)async def banhammer(event): if not event.is_reply: return await event.reply(get_string("pmbot_2")) target = get_who(event.reply_to_msg_id) if botb.contains(target): return await event.reply(get_string("pmbot_3"))
botb.add(target) await event.reply(f"#BAN\nUser : {target}") await asst.send_message(target, get_string("pmbot_4"))
@asst_cmd( pattern="unban", load=AST_PLUGINS, from_users=[OWNER_ID], func=lambda x: x.is_private,)async def unbanhammer(event): if not event.is_reply: return await event.reply(get_string("pmbot_5")) target = get_who(event.reply_to_msg_id) if not botb.contains(target): return await event.reply(get_string("pmbot_6"))
botb.remove(target) await event.reply(f"#UNBAN\nUser : {target}") await asst.send_message(target, get_string("pmbot_7"))
# --------------------------------------- END -------------------------------------------- #123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240# Ultroid - UserBot# Copyright (C) 2021-2023 TeamUltroid## This file is a part of < https://github.com/TeamUltroid/Ultroid/ ># PLease read the GNU Affero General Public License in# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
from datetime import datetime
from pytz import timezone as tzfrom telethon import Button, eventsfrom telethon.errors.rpcerrorlist import MessageDeleteForbiddenErrorfrom telethon.utils import get_display_name
from pyUltroid._misc import SUDO_M, owner_and_sudosfrom pyUltroid.dB.base import KeyManagerfrom pyUltroid.fns.helper import inline_mentionfrom strings import get_string
from . import *
Owner_info_msg = udB.get_key("BOT_INFO_START")custom_info = Trueif Owner_info_msg is None: custom_info = False Owner_info_msg = f"""**Owner** - {OWNER_NAME}**OwnerID** - `{OWNER_ID}`
**Message Forwards** - {udB.get_key("PMBOT")}
**Ultroid [v{ultroid_version}](https://github.com/TeamUltroid/Ultroid), powered by @TeamUltroid**"""
_settings = [ [ Button.inline("API Kᴇʏs", data="cbs_apiset"), Button.inline("Pᴍ Bᴏᴛ", data="cbs_chatbot"), ], [ Button.inline("Aʟɪᴠᴇ", data="cbs_alvcstm"), Button.inline("PᴍPᴇʀᴍɪᴛ", data="cbs_ppmset"), ], [ Button.inline("Fᴇᴀᴛᴜʀᴇs", data="cbs_otvars"), Button.inline("VC Sᴏɴɢ Bᴏᴛ", data="cbs_vcb"), ], [Button.inline("« Bᴀᴄᴋ", data="mainmenu")],]
_start = [ [ Button.inline("Lᴀɴɢᴜᴀɢᴇ 🌐", data="lang"), Button.inline("Sᴇᴛᴛɪɴɢs ⚙️", data="setter"), ], [ Button.inline("Sᴛᴀᴛs ✨", data="stat"), Button.inline("Bʀᴏᴀᴅᴄᴀsᴛ 📻", data="bcast"), ], [Button.inline("TɪᴍᴇZᴏɴᴇ 🌎", data="tz")],]
@callback("ownerinfo")async def own(event): msg = Owner_info_msg.format( mention=inline_mention(event.sender), me=inline_mention(ultroid_bot.me) ) if custom_info: msg += "\n\n• Powered by **@TeamUltroid**" await event.edit( msg, buttons=[Button.inline("Close", data="closeit")], link_preview=False, )
@callback("closeit")async def closet(lol): try: await lol.delete() except MessageDeleteForbiddenError: await lol.answer("MESSAGE_TOO_OLD", alert=True)
@asst_cmd(pattern="start( (.*)|$)", forwards=False, func=lambda x: not x.is_group)async def ultroid(event): args = event.pattern_match.group(1).strip() keym = KeyManager("BOT_USERS", cast=list) if not keym.contains(event.sender_id) and event.sender_id not in owner_and_sudos(): keym.add(event.sender_id) kak_uiw = udB.get_key("OFF_START_LOG") if not kak_uiw or kak_uiw != True: msg = f"{inline_mention(event.sender)} `[{event.sender_id}]` started your [Assistant bot](@{asst.me.username})." buttons = [[Button.inline("Info", "itkkstyo")]] if event.sender.username: buttons[0].append( Button.mention( "User", await event.client.get_input_entity(event.sender_id) ) ) await event.client.send_message( udB.get_key("LOG_CHANNEL"), msg, buttons=buttons ) if event.sender_id not in SUDO_M.fullsudos: ok = "" me = inline_mention(ultroid_bot.me) mention = inline_mention(event.sender) if args and args != "set": await get_stored_file(event, args) if not udB.get_key("STARTMSG"): if udB.get_key("PMBOT"): ok = "You can contact my master using this bot!!\n\nSend your Message, I will Deliver it To Master." await event.reply( f"Hey there {mention}, this is Ultroid Assistant of {me}!\n\n{ok}", file=udB.get_key("STARTMEDIA"), buttons=[Button.inline("Info.", data="ownerinfo")] if Owner_info_msg else None, ) else: await event.reply( udB.get_key("STARTMSG").format(me=me, mention=mention), file=udB.get_key("STARTMEDIA"), buttons=[Button.inline("Info.", data="ownerinfo")] if Owner_info_msg else None, ) else: name = get_display_name(event.sender) if args == "set": await event.reply( "Choose from the below options -", buttons=_settings, ) elif args: await get_stored_file(event, args) else: await event.reply( get_string("ast_3").format(name), buttons=_start, )
@callback("itkkstyo", owner=True)async def ekekdhdb(e): text = f"When New Visitor will visit your Assistant Bot. You will get this log message!\n\nTo Disable : {HNDLR}setdb OFF_START_LOG True" await e.answer(text, alert=True)
@callback("mainmenu", owner=True, func=lambda x: not x.is_group)async def ultroid(event): await event.edit( get_string("ast_3").format(OWNER_NAME), buttons=_start, )
@callback("stat", owner=True)async def botstat(event): ok = len(udB.get_key("BOT_USERS") or []) msg = """Ultroid Assistant - StatsTotal Users - {}""".format( ok, ) await event.answer(msg, cache_time=0, alert=True)
@callback("bcast", owner=True)async def bdcast(event): keym = KeyManager("BOT_USERS", cast=list) total = keym.count() await event.edit(f"• Broadcast to {total} users.") async with event.client.conversation(OWNER_ID) as conv: await conv.send_message( "Enter your broadcast message.\nUse /cancel to stop the broadcast.", ) response = await conv.get_response() if response.message == "/cancel": return await conv.send_message("Cancelled!!") success = 0 fail = 0 await conv.send_message(f"Starting a broadcast to {total} users...") start = datetime.now() for i in keym.get(): try: await asst.send_message(int(i), response) success += 1 except BaseException: fail += 1 end = datetime.now() time_taken = (end - start).seconds await conv.send_message( f"""**Broadcast completed in {time_taken} seconds.**Total Users in Bot - {total}**Sent to** : `{success} users.`**Failed for** : `{fail} user(s).`""", )
@callback("setter", owner=True)async def setting(event): await event.edit( "Choose from the below options -", buttons=_settings, )
@callback("tz", owner=True)async def timezone_(event): await event.delete() pru = event.sender_id var = "TIMEZONE" name = "Timezone" async with event.client.conversation(pru) as conv: await conv.send_message( "Send Your TimeZone From This List [Check From Here](http://www.timezoneconverter.com/cgi-bin/findzone.tzc)" ) response = conv.wait_event(events.NewMessage(chats=pru)) response = await response themssg = response.message.message if themssg == "/cancel": return await conv.send_message( "Cancelled!!", buttons=get_back_button("mainmenu"), ) try: tz(themssg) await setit(event, var, themssg) await conv.send_message( f"{name} changed to {themssg}\n", buttons=get_back_button("mainmenu"), ) except BaseException: await conv.send_message( "Wrong TimeZone, Try again", buttons=get_back_button("mainmenu"), ).envDeleted-12
.gitattributes+3
CODE_OF_CONDUCT.mdAdded+128
CONTRIBUTING.mdAdded+23
Dockerfile+57-16
FileStream/__init__.pyDeleted-5
FileStream/__main__.pyDeleted-77
FileStream/bot/__init__.pyDeleted-25
FileStream/bot/clients.pyDeleted-59
FileStream/bot/plugins/admin.pyDeleted-160
FileStream/bot/plugins/callback.pyDeleted-198
FileStream/bot/plugins/start.pyDeleted-149
FileStream/bot/plugins/stream.pyDeleted-96
FileStream/config.pyDeleted-41
FileStream/server/__init__.pyDeleted-7
FileStream/server/exceptions.pyDeleted-5
FileStream/server/stream_routes.pyDeleted-136
FileStream/template/dl.htmlDeleted-44
FileStream/template/play.htmlDeleted-171
FileStream/utils/__init__.pyDeleted-3
FileStream/utils/bot_utils.pyDeleted-216
FileStream/utils/broadcast_helper.pyDeleted-19
FileStream/utils/custom_dl.pyDeleted-214
FileStream/utils/database.pyDeleted-134
FileStream/utils/file_properties.pyDeleted-144
FileStream/utils/human_readable.pyDeleted-10
FileStream/utils/render_template.pyDeleted-30
FileStream/utils/time_format.pyDeleted-22
FileStream/utils/translation.pyDeleted-72
FileStreamBotDeleted-1
FilerAdded+1
LICENSEAdded+661
ProcfileDeleted-1
addons.txtAdded+19
app.jsonDeleted-117
assistant/__init__.pyAdded+34
assistant/callbackstuffs.pyAdded+1325
assistant/games.pyAdded+317
assistant/initial.pyAdded+84
assistant/inlinestuff.pyAdded+623
assistant/localization.pyAdded+47
assistant/manager/__init__.pyAdded+11
assistant/manager/_help.pyAdded+134
assistant/manager/_on_adds.pyAdded+23
assistant/manager/admins.pyAdded+50
assistant/manager/afk.pyAdded+110
assistant/manager/misc.pyAdded+64
assistant/manager/stickermanager.pyAdded+180
assistant/pmbot.pyAdded+150
assistant/start.pyAdded+240