diff --git a/Dockerfile b/Dockerfile index 0222be4..ca4a7d1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,33 +1,11 @@ -FROM ubuntu:18.04 +FROM python:3.8-slim-buster -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update -RUN echo y | apt-get install locales -RUN echo y | apt install build-essential -RUN apt -qq install -y --no-install-recommends \ - curl \ - git \ - gnupg2 \ - wget \ +WORKDIR /app -RUN set -ex; \ - apt-get update \ - && apt-get install -y --no-install-recommends \ - busybox \ - git \ - python3 \ - python3-dev \ - python3-pip \ - python3-lxml \ - pv \ - && apt-get autoclean \ - && apt-get autoremove \ - && rm -rf /var/lib/apt/lists/* - -RUN pip3 install setuptools wheel yarl multidict COPY requirements.txt . -RUN pip3 install -r requirements.txt -RUN dpkg-reconfigure locales -COPY . /app + +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . CMD ["python3", "bot.py"] diff --git a/Procfile b/Procfile index a561093..a18caa2 100644 --- a/Procfile +++ b/Procfile @@ -1 +1 @@ -worker: python3 bot.py \ No newline at end of file +web: python3 bot.py diff --git a/bot.py b/bot.py index 79771c4..8b702ac 100644 --- a/bot.py +++ b/bot.py @@ -1,471 +1,36 @@ -#@MxA_Bots | @iSmartBoi_Ujjwal +import os, logging, asyncio +from aiohttp import web +from pyrogram import Client +from configs import * +from server import web_server -import os -import asyncio -import traceback -from binascii import ( - Error -) -from pyrogram import ( - Client, - enums, - filters -) -from pyrogram.errors import ( - UserNotParticipant, - FloodWait, - QueryIdInvalid -) -from pyrogram.types import ( - InlineKeyboardMarkup, - InlineKeyboardButton, - CallbackQuery, - Message -) -from configs import Config -from handlers.database import db -from handlers.add_user_to_db import add_user_to_database -from handlers.send_file import send_media_and_reply -from handlers.helpers import b64_to_str, str_to_b64 -from handlers.check_user_status import handle_user_status -from handlers.force_sub_handler import ( - handle_force_sub, - get_invite_link -) -from handlers.broadcast_handlers import main_broadcast_handler -from handlers.save_media import ( - save_media_in_channel, - save_batch_media_in_channel -) +logging.basicConfig(level=logging.INFO, format='%(message)s') +logger = logging.getLogger("Filestore") -MediaList = {} - -Bot = Client( - name=Config.BOT_USERNAME, - in_memory=True, - bot_token=Config.BOT_TOKEN, - api_id=Config.API_ID, - api_hash=Config.API_HASH -) - - -@Bot.on_message(filters.private) -async def _(bot: Client, cmd: Message): - await handle_user_status(bot, cmd) - - -@Bot.on_message(filters.command("start") & filters.private) -async def start(bot: Client, cmd: Message): - - if cmd.from_user.id in Config.BANNED_USERS: - await cmd.reply_text("Sorry, You are banned.") - return - if Config.UPDATES_CHANNEL is not None: - back = await handle_force_sub(bot, cmd) - if back == 400: - return - - usr_cmd = cmd.text.split("_", 1)[-1] - if usr_cmd == "/start": - await add_user_to_database(bot, cmd) - await cmd.reply_text( - Config.HOME_TEXT.format(cmd.from_user.first_name, cmd.from_user.id), - disable_web_page_preview=True, - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url="https://t.me/movies_X_animes") - ], - [ - InlineKeyboardButton("About Bot", callback_data="aboutbot"), - InlineKeyboardButton("About Dev", callback_data="aboutdevs"), - InlineKeyboardButton("Close πŸšͺ", callback_data="closeMessage") - ], - [ - InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), - InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") - ] - ] - ) - ) - else: - try: - try: - file_id = int(b64_to_str(usr_cmd).split("_")[-1]) - except (Error, UnicodeDecodeError): - file_id = int(usr_cmd.split("_")[-1]) - GetMessage = await bot.get_messages(chat_id=Config.DB_CHANNEL, message_ids=file_id) - message_ids = [] - if GetMessage.text: - message_ids = GetMessage.text.split(" ") - _response_msg = await cmd.reply_text( - text=f"**Total Files:** `{len(message_ids)}`", - quote=True, - disable_web_page_preview=True - ) - else: - message_ids.append(int(GetMessage.id)) - for i in range(len(message_ids)): - await send_media_and_reply(bot, user_id=cmd.from_user.id, file_id=int(message_ids[i])) - except Exception as err: - await cmd.reply_text(f"Something went wrong!\n\n**Error:** `{err}`") - - -@Bot.on_message((filters.document | filters.video | filters.audio) & ~filters.chat(Config.DB_CHANNEL)) -async def main(bot: Client, message: Message): - - if message.chat.type == enums.ChatType.PRIVATE: - - await add_user_to_database(bot, message) - - if Config.UPDATES_CHANNEL is not None: - back = await handle_force_sub(bot, message) - if back == 400: - return - - if message.from_user.id in Config.BANNED_USERS: - await message.reply_text("Sorry, You are banned!\n\nContact [Support Group](https://t.me/TeleRoid14)", - disable_web_page_preview=True) - return - - if Config.OTHER_USERS_CAN_SAVE_FILE is False: - return - - await message.reply_text( - text="**Choose an option from below:**", - reply_markup=InlineKeyboardMarkup([ - [InlineKeyboardButton("Save in Batch", callback_data="addToBatchTrue")], - [InlineKeyboardButton("Get Sharable Link", callback_data="addToBatchFalse")] - ]), - quote=True, - disable_web_page_preview=True - ) - elif message.chat.type == enums.ChatType.CHANNEL: - if (message.chat.id == int(Config.LOG_CHANNEL)) or (message.chat.id == int(Config.UPDATES_CHANNEL)) or message.forward_from_chat or message.forward_from: - return - elif int(message.chat.id) in Config.BANNED_CHAT_IDS: - await bot.leave_chat(message.chat.id) - return - else: - pass - - try: - forwarded_msg = await message.forward(Config.DB_CHANNEL) - file_er_id = str(forwarded_msg.id) - share_link = f"https://t.me/{Config.BOT_USERNAME}?start=PredatorHackerzZ_{str_to_b64(file_er_id)}" - CH_edit = await bot.edit_message_reply_markup(message.chat.id, message.id, - reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton( - "Get Sharable Link", url=share_link)]])) - if message.chat.username: - await forwarded_msg.reply_text( - f"#CHANNEL_BUTTON:\n\n[{message.chat.title}](https://t.me/{message.chat.username}/{CH_edit.id}) Channel's Broadcasted File's Button Added!") - else: - private_ch = str(message.chat.id)[4:] - await forwarded_msg.reply_text( - f"#CHANNEL_BUTTON:\n\n[{message.chat.title}](https://t.me/c/{private_ch}/{CH_edit.id}) Channel's Broadcasted File's Button Added!") - except FloodWait as sl: - await asyncio.sleep(sl.value) - await bot.send_message( - chat_id=int(Config.LOG_CHANNEL), - text=f"#FloodWait:\nGot FloodWait of `{str(sl.value)}s` from `{str(message.chat.id)}` !!", - disable_web_page_preview=True - ) - except Exception as err: - await bot.leave_chat(message.chat.id) - await bot.send_message( - chat_id=int(Config.LOG_CHANNEL), - text=f"#ERROR_TRACEBACK:\nGot Error from `{str(message.chat.id)}` !!\n\n**Traceback:** `{err}`", - disable_web_page_preview=True - ) - - -@Bot.on_message(filters.private & filters.command("broadcast") & filters.user(Config.BOT_OWNER) & filters.reply) -async def broadcast_handler_open(_, m: Message): - await main_broadcast_handler(m, db) - - -@Bot.on_message(filters.private & filters.command("status") & filters.user(Config.BOT_OWNER)) -async def sts(_, m: Message): - total_users = await db.total_users_count() - await m.reply_text( - text=f"**Total Users in DB:** `{total_users}`", - quote=True - ) - - -@Bot.on_message(filters.private & filters.command("ban_user") & filters.user(Config.BOT_OWNER)) -async def ban(c: Client, m: Message): - - if len(m.command) == 1: - await m.reply_text( - f"Use this command to ban any user from the bot.\n\n" - f"Usage:\n\n" - f"`/ban_user user_id ban_duration ban_reason`\n\n" - f"Eg: `/ban_user 1234567 28 You misused me.`\n" - f"This will ban user with id `1234567` for `28` days for the reason `You misused me`.", - quote=True - ) - return - - try: - user_id = int(m.command[1]) - ban_duration = int(m.command[2]) - ban_reason = ' '.join(m.command[3:]) - ban_log_text = f"Banning user {user_id} for {ban_duration} days for the reason {ban_reason}." - try: - await c.send_message( - user_id, - f"You are banned to use this bot for **{ban_duration}** day(s) for the reason __{ban_reason}__ \n\n" - f"**Message from the admin**" - ) - ban_log_text += '\n\nUser notified successfully!' - except: - traceback.print_exc() - ban_log_text += f"\n\nUser notification failed! \n\n`{traceback.format_exc()}`" - - await db.ban_user(user_id, ban_duration, ban_reason) - print(ban_log_text) - await m.reply_text( - ban_log_text, - quote=True - ) - except: - traceback.print_exc() - await m.reply_text( - f"Error occoured! Traceback given below\n\n`{traceback.format_exc()}`", - quote=True - ) - - -@Bot.on_message(filters.private & filters.command("unban_user") & filters.user(Config.BOT_OWNER)) -async def unban(c: Client, m: Message): - - if len(m.command) == 1: - await m.reply_text( - f"Use this command to unban any user.\n\n" - f"Usage:\n\n`/unban_user user_id`\n\n" - f"Eg: `/unban_user 1234567`\n" - f"This will unban user with id `1234567`.", - quote=True - ) - return - - try: - user_id = int(m.command[1]) - unban_log_text = f"Unbanning user {user_id}" - try: - await c.send_message( - user_id, - f"Your ban was lifted!" - ) - unban_log_text += '\n\nUser notified successfully!' - except: - traceback.print_exc() - unban_log_text += f"\n\nUser notification failed! \n\n`{traceback.format_exc()}`" - await db.remove_ban(user_id) - print(unban_log_text) - await m.reply_text( - unban_log_text, - quote=True - ) - except: - traceback.print_exc() - await m.reply_text( - f"Error occurred! Traceback given below\n\n`{traceback.format_exc()}`", - quote=True - ) - - -@Bot.on_message(filters.private & filters.command("banned_users") & filters.user(Config.BOT_OWNER)) -async def _banned_users(_, m: Message): +class Filestore(Client): - all_banned_users = await db.get_all_banned_users() - banned_usr_count = 0 - text = '' - - async for banned_user in all_banned_users: - user_id = banned_user['id'] - ban_duration = banned_user['ban_status']['ban_duration'] - banned_on = banned_user['ban_status']['banned_on'] - ban_reason = banned_user['ban_status']['ban_reason'] - banned_usr_count += 1 - text += f"> **user_id**: `{user_id}`, **Ban Duration**: `{ban_duration}`, " \ - f"**Banned on**: `{banned_on}`, **Reason**: `{ban_reason}`\n\n" - reply_text = f"Total banned user(s): `{banned_usr_count}`\n\n{text}" - if len(reply_text) > 4096: - with open('banned-users.txt', 'w') as f: - f.write(reply_text) - await m.reply_document('banned-users.txt', True) - os.remove('banned-users.txt') - return - await m.reply_text(reply_text, True) - - -@Bot.on_message(filters.private & filters.command("clear_batch")) -async def clear_user_batch(bot: Client, m: Message): - MediaList[f"{str(m.from_user.id)}"] = [] - await m.reply_text("Cleared your batch files successfully!") - - -@Bot.on_callback_query() -async def button(bot: Client, cmd: CallbackQuery): - - cb_data = cmd.data - if "aboutbot" in cb_data: - await cmd.message.edit( - Config.ABOUT_BOT_TEXT, - disable_web_page_preview=True, - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("Source Codes of Bot", - url="https://te.legra.ph/file/42e9a66c3df08a9c1987a.mp4") - ], - [ - InlineKeyboardButton("Go Home", callback_data="gotohome"), - InlineKeyboardButton("About Dev", callback_data="aboutdevs") - ] - ] - ) - ) - - elif "aboutdevs" in cb_data: - await cmd.message.edit( - Config.ABOUT_DEV_TEXT, - disable_web_page_preview=True, - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("Source Codes of Bot", - url="https://te.legra.ph/file/42e9a66c3df08a9c1987a.mp4") - ], - [ - InlineKeyboardButton("About Bot", callback_data="aboutbot"), - InlineKeyboardButton("Go Home", callback_data="gotohome") - ] - ] - ) - ) - - elif "gotohome" in cb_data: - await cmd.message.edit( - Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id), - disable_web_page_preview=True, - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url="https://t.me/movies_X_animes") - ], - [ - InlineKeyboardButton("About Bot", callback_data="aboutbot"), - InlineKeyboardButton("About Dev", callback_data="aboutdevs"), - InlineKeyboardButton("Close πŸšͺ", callback_data="closeMessage") - ], - [ - InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), - InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") - ] - ] - ) - ) - - elif "refreshForceSub" in cb_data: - if Config.UPDATES_CHANNEL: - if Config.UPDATES_CHANNEL.startswith("-100"): - channel_chat_id = int(Config.UPDATES_CHANNEL) - else: - channel_chat_id = Config.UPDATES_CHANNEL - try: - user = await bot.get_chat_member(channel_chat_id, cmd.message.chat.id) - if user.status == "kicked": - await cmd.message.edit( - text="Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/TeleRoid14).", - disable_web_page_preview=True - ) - return - except UserNotParticipant: - invite_link = await get_invite_link(channel_chat_id) - await cmd.message.edit( - text="**I like Your Smartness But Don't Be Oversmart! πŸ˜‘**\n\n", - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url=invite_link.invite_link) - ], - [ - InlineKeyboardButton("πŸ”„ Refresh πŸ”„", callback_data="refreshmeh") - ] - ] - ) - ) - return - except Exception: - await cmd.message.edit( - text="Something went Wrong. Contact my [Support](https://t.me/iSmartBoiUjjwal_ib_bot).", - disable_web_page_preview=True - ) - return - await cmd.message.edit( - text=Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id), - disable_web_page_preview=True, - reply_markup=InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), - InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") - ], - [ - InlineKeyboardButton("About Bot", callback_data="aboutbot"), - InlineKeyboardButton("About Dev", callback_data="aboutdevs") - ] - ] - ) - ) - - elif cb_data.startswith("ban_user_"): - user_id = cb_data.split("_", 2)[-1] - if Config.UPDATES_CHANNEL is None: - await cmd.answer("Sorry Sir, You didn't Set any Updates Channel!", show_alert=True) - return - if not int(cmd.from_user.id) == Config.BOT_OWNER: - await cmd.answer("You are not allowed to do that!", show_alert=True) - return - try: - await bot.kick_chat_member(chat_id=int(Config.UPDATES_CHANNEL), user_id=int(user_id)) - await cmd.answer("User Banned from Updates Channel!", show_alert=True) - except Exception as e: - await cmd.answer(f"Can't Ban Him!\n\nError: {e}", show_alert=True) - - elif "addToBatchTrue" in cb_data: - if MediaList.get(f"{str(cmd.from_user.id)}", None) is None: - MediaList[f"{str(cmd.from_user.id)}"] = [] - file_id = cmd.message.reply_to_message.id - MediaList[f"{str(cmd.from_user.id)}"].append(file_id) - await cmd.message.edit("File Saved in Batch!\n\n" - "Press below button to get batch link.", - reply_markup=InlineKeyboardMarkup([ - [InlineKeyboardButton("Get Batch Link", callback_data="getBatchLink")], - [InlineKeyboardButton("Close Message", callback_data="closeMessage")] - ])) - - elif "addToBatchFalse" in cb_data: - await save_media_in_channel(bot, editable=cmd.message, message=cmd.message.reply_to_message) - - elif "getBatchLink" in cb_data: - message_ids = MediaList.get(f"{str(cmd.from_user.id)}", None) - if message_ids is None: - await cmd.answer("Batch List Empty!", show_alert=True) - return - await cmd.message.edit("Please wait, generating batch link ...") - await save_batch_media_in_channel(bot=bot, editable=cmd.message, message_ids=message_ids) - MediaList[f"{str(cmd.from_user.id)}"] = [] - - elif "closeMessage" in cb_data: - await cmd.message.delete(True) - - try: - await cmd.answer() - except QueryIdInvalid: pass - - -Bot.run() + def __init__(self): + super().__init__( + "Filestore", + in_memory=True, + workers=500, + api_id=API_ID, + api_hash=API_HASH, + bot_token=BOT_TOKEN, + plugins=dict(root="plugins") + ) + + async def start(self): + await super().start() + logger.info("Bot Started successfully..😎🀏") + app = web.AppRunner(await web_server()) + await app.setup() + ba = "0.0.0.0" + await web.TCPSite(app, ba, 8080).start() + + async def stop(self, *args): + await super().stop() + logger.info("Bot Stopped") + +if __name__ == '__main__': + Filestore().run() diff --git a/configs.py b/configs.py index ccd03af..80f9f5b 100644 --- a/configs.py +++ b/configs.py @@ -4,18 +4,20 @@ class Config(object): + URL = os.getenv("URL", "") API_ID = int(os.environ.get("API_ID", "0")) API_HASH = os.environ.get("API_HASH") BOT_TOKEN = os.environ.get("BOT_TOKEN") - BOT_USERNAME = os.environ.get("BOT_USERNAME") + BOT_USERNAME = os.environ.get("BOT_USERNAME") DB_CHANNEL = int(os.environ.get("DB_CHANNEL", "-100")) BOT_OWNER = int(os.environ.get("BOT_OWNER", "1445283714")) DATABASE_URL = os.environ.get("DATABASE_URL") - UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", "") + UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", "") + UPDATES_CHANNEL_USERNAME = os.environ.get("UPDATES_CHANNEL_USERNAME", "") LOG_CHANNEL = os.environ.get("LOG_CHANNEL", None) BANNED_USERS = set(int(x) for x in os.environ.get("BANNED_USERS", "1234567890").split()) FORWARD_AS_COPY = bool(os.environ.get("FORWARD_AS_COPY", True)) - BROADCAST_AS_COPY = bool(os.environ.get("BROADCAST_AS_COPY", False)) + BROADCAST_AS_COPY = bool(os.environ.get("BROADCAST_AS_COPY", True)) BANNED_CHAT_IDS = list(set(int(x) for x in os.environ.get("BANNED_CHAT_IDS", "-1001362659779 -1001255795497").split())) OTHER_USERS_CAN_SAVE_FILE = bool(os.environ.get("OTHER_USERS_CAN_SAVE_FILE", True)) ABOUT_BOT_TEXT = f"""This is a Permanent FileStore Bot. @@ -43,8 +45,7 @@ class Config(object): 𝐉𝐨𝐒𝐧 **@MxA_Bots** """ HOME_TEXT = """ -Hello, [{}](tg://user?id={})\n\nThis is a Permanent **FΙͺΚŸα΄‡SᴛᴏʀᴇBᴏᴛ**. -πŸ“’ Send me any File & It will be uploaded in My Database & You will Get the File Link. -⚠️ Benefits: If you have a TeleGram Movie Channel or Any Copyright Channel, Then Its Useful for Daily Usage, You can Send Me Your File & I will Send Permanent Link to You & Channel will be Safe from **CopyRight Infringement** Issue. I support Channel Also You Can Check **About Bot**. -❌ **PORNOGRAPHY CONTENTS** are strictly prohibited & get Permanent Ban. +Hello, [{}](tg://user?id={})\n\nThis is a Permanent **FΙͺΚŸα΄‡SᴛᴏʀᴇBᴏᴛ** Made for @{UPDATES_CHANNEL_USERNAME} """ + + diff --git a/handlers/send_file.py b/handlers/send_file.py index ef3b6db..d8bef4b 100644 --- a/handlers/send_file.py +++ b/handlers/send_file.py @@ -1,5 +1,7 @@ #@MxA_Bots | @iSmartBoi_Ujjwal +import os +from os import environ import asyncio from configs import Config from pyrogram import Client @@ -7,11 +9,13 @@ from pyrogram.errors import FloodWait from handlers.helpers import str_to_b64 +DELETE_TIME = int(environ.get("DELETE_TIME", "3600")) +AUTODELETE_MESSAGE = os.getenv("AUTODELETE_MESSAGE", '''‼️ File will auto delete in few seconds😱\nπŸ’‘Forward it to saved massages or anywhere before downloading.😁\nπŸ˜‡Join @{UPDATES_CHANNEL_USERNAME}''') async def reply_forward(message: Message, file_id: int): try: await message.reply_text( - f"**Files will be Deleted After few seconds ⏰**\n", + f"{AUTODELETE_MESSAGE}", disable_web_page_preview=True, quote=True) except FloodWait as e: await asyncio.sleep(e.value) @@ -23,6 +27,7 @@ async def media_forward(bot: Client, user_id: int, file_id: int): if Config.FORWARD_AS_COPY is True: return await bot.copy_message(chat_id=user_id, from_chat_id=Config.DB_CHANNEL, message_id=file_id) + elif Config.FORWARD_AS_COPY is False: return await bot.forward_messages(chat_id=user_id, from_chat_id=Config.DB_CHANNEL, message_ids=file_id) @@ -31,14 +36,8 @@ async def media_forward(bot: Client, user_id: int, file_id: int): return media_forward(bot, user_id, file_id) -async def delete_file(file_id: int): - await asyncio.sleep(50) # wait for 50 seconds - # Delete the file using the file ID - # Code to delete the file goes here - - async def send_media_and_reply(bot: Client, user_id: int, file_id: int): sent_message = await media_forward(bot, user_id, file_id) - await reply_forward(message=sent_message, file_id=file_id) - asyncio.create_task(delete_file(file_id)) # schedule the file deletion task - await asyncio.sleep(2) + await message.reply_text(f'{AUTODELETE_MESSAGE}') + asyncio.sleep(DELETE_TIME) + await sent_message.delete() diff --git a/plugins/commands.py b/plugins/commands.py new file mode 100644 index 0000000..9135225 --- /dev/null +++ b/plugins/commands.py @@ -0,0 +1,460 @@ +#@MxA_Bots | @iSmartBoi_Ujjwal + +import os +import asyncio +import traceback +from binascii import ( + Error +) +from pyrogram import ( + Client, + enums, + filters +) +from pyrogram.errors import ( + UserNotParticipant, + FloodWait, + QueryIdInvalid +) +from pyrogram.types import ( + InlineKeyboardMarkup, + InlineKeyboardButton, + CallbackQuery, + Message +) +from configs import Config +from handlers.database import db +from handlers.add_user_to_db import add_user_to_database +from handlers.send_file import send_media_and_reply +from handlers.helpers import b64_to_str, str_to_b64 +from handlers.check_user_status import handle_user_status +from handlers.force_sub_handler import ( + handle_force_sub, + get_invite_link +) +from handlers.broadcast_handlers import main_broadcast_handler +from handlers.save_media import ( + save_media_in_channel, + save_batch_media_in_channel +) + +MediaList = {} + + +@Client.on_message(filters.private) +async def _(bot: Client, cmd: Message): + await handle_user_status(bot, cmd) + + +@Client.on_message(filters.command("start") & filters.private) +async def start(bot: Client, cmd: Message): + + if cmd.from_user.id in Config.BANNED_USERS: + await cmd.reply_text("Sorry, You are banned.") + return + if Config.UPDATES_CHANNEL is not None: + back = await handle_force_sub(bot, cmd) + if back == 400: + return + + usr_cmd = cmd.text.split("_", 1)[-1] + if usr_cmd == "/start": + await add_user_to_database(bot, cmd) + await cmd.reply_text( + Config.HOME_TEXT.format(cmd.from_user.first_name, cmd.from_user.id), + disable_web_page_preview=True, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url="https://t.me/movies_X_animes") + ], + [ + InlineKeyboardButton("About Bot", callback_data="aboutbot"), + InlineKeyboardButton("About Dev", callback_data="aboutdevs"), + InlineKeyboardButton("Close πŸšͺ", callback_data="closeMessage") + ], + [ + InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), + InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") + ] + ] + ) + ) + else: + try: + try: + file_id = int(b64_to_str(usr_cmd).split("_")[-1]) + except (Error, UnicodeDecodeError): + file_id = int(usr_cmd.split("_")[-1]) + GetMessage = await bot.get_messages(chat_id=Config.DB_CHANNEL, message_ids=file_id) + message_ids = [] + if GetMessage.text: + message_ids = GetMessage.text.split(" ") + _response_msg = await cmd.reply_text( + text=f"**Total Files:** `{len(message_ids)}`", + quote=True, + disable_web_page_preview=True + ) + else: + message_ids.append(int(GetMessage.id)) + for i in range(len(message_ids)): + await send_media_and_reply(bot, user_id=cmd.from_user.id, file_id=int(message_ids[i])) + except Exception as err: + await cmd.reply_text(f"Something went wrong!\n\n**Error:** `{err}`") + + +@Client.on_message((filters.document | filters.video | filters.audio) & ~filters.chat(Config.DB_CHANNEL)) +async def main(bot: Client, message: Message): + + if message.chat.type == enums.ChatType.PRIVATE: + + await add_user_to_database(bot, message) + + if Config.UPDATES_CHANNEL is not None: + back = await handle_force_sub(bot, message) + if back == 400: + return + + if message.from_user.id in Config.BANNED_USERS: + await message.reply_text("Sorry, You are banned!\n\nContact [Support Group](https://t.me/TeleRoid14)", + disable_web_page_preview=True) + return + + if Config.OTHER_USERS_CAN_SAVE_FILE is False: + return + + await message.reply_text( + text="**Choose an option from below:**", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("Save in Batch", callback_data="addToBatchTrue")], + [InlineKeyboardButton("Get Sharable Link", callback_data="addToBatchFalse")] + ]), + quote=True, + disable_web_page_preview=True + ) + elif message.chat.type == enums.ChatType.CHANNEL: + if (message.chat.id == int(Config.LOG_CHANNEL)) or (message.chat.id == int(Config.UPDATES_CHANNEL)) or message.forward_from_chat or message.forward_from: + return + elif int(message.chat.id) in Config.BANNED_CHAT_IDS: + await bot.leave_chat(message.chat.id) + return + else: + pass + + try: + forwarded_msg = await message.forward(Config.DB_CHANNEL) + file_er_id = str(forwarded_msg.id) + share_link = f"https://t.me/{Config.BOT_USERNAME}?start=PredatorHackerzZ_{str_to_b64(file_er_id)}" + CH_edit = await bot.edit_message_reply_markup(message.chat.id, message.id, + reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton( + "Get Sharable Link", url=share_link)]])) + if message.chat.username: + await forwarded_msg.reply_text( + f"#CHANNEL_BUTTON:\n\n[{message.chat.title}](https://t.me/{message.chat.username}/{CH_edit.id}) Channel's Broadcasted File's Button Added!") + else: + private_ch = str(message.chat.id)[4:] + await forwarded_msg.reply_text( + f"#CHANNEL_BUTTON:\n\n[{message.chat.title}](https://t.me/c/{private_ch}/{CH_edit.id}) Channel's Broadcasted File's Button Added!") + except FloodWait as sl: + await asyncio.sleep(sl.value) + await bot.send_message( + chat_id=int(Config.LOG_CHANNEL), + text=f"#FloodWait:\nGot FloodWait of `{str(sl.value)}s` from `{str(message.chat.id)}` !!", + disable_web_page_preview=True + ) + except Exception as err: + await bot.leave_chat(message.chat.id) + await bot.send_message( + chat_id=int(Config.LOG_CHANNEL), + text=f"#ERROR_TRACEBACK:\nGot Error from `{str(message.chat.id)}` !!\n\n**Traceback:** `{err}`", + disable_web_page_preview=True + ) + + +@Client.on_message(filters.private & filters.command("broadcast") & filters.user(Config.BOT_OWNER) & filters.reply) +async def broadcast_handler_open(_, m: Message): + await main_broadcast_handler(m, db) + + +@Client.on_message(filters.private & filters.command("status") & filters.user(Config.BOT_OWNER)) +async def sts(_, m: Message): + total_users = await db.total_users_count() + await m.reply_text( + text=f"**Total Users in DB:** `{total_users}`", + quote=True + ) + + +@Client.on_message(filters.private & filters.command("ban_user") & filters.user(Config.BOT_OWNER)) +async def ban(c: Client, m: Message): + + if len(m.command) == 1: + await m.reply_text( + f"Use this command to ban any user from the bot.\n\n" + f"Usage:\n\n" + f"`/ban_user user_id ban_duration ban_reason`\n\n" + f"Eg: `/ban_user 1234567 28 You misused me.`\n" + f"This will ban user with id `1234567` for `28` days for the reason `You misused me`.", + quote=True + ) + return + + try: + user_id = int(m.command[1]) + ban_duration = int(m.command[2]) + ban_reason = ' '.join(m.command[3:]) + ban_log_text = f"Banning user {user_id} for {ban_duration} days for the reason {ban_reason}." + try: + await c.send_message( + user_id, + f"You are banned to use this bot for **{ban_duration}** day(s) for the reason __{ban_reason}__ \n\n" + f"**Message from the admin**" + ) + ban_log_text += '\n\nUser notified successfully!' + except: + traceback.print_exc() + ban_log_text += f"\n\nUser notification failed! \n\n`{traceback.format_exc()}`" + + await db.ban_user(user_id, ban_duration, ban_reason) + print(ban_log_text) + await m.reply_text( + ban_log_text, + quote=True + ) + except: + traceback.print_exc() + await m.reply_text( + f"Error occoured! Traceback given below\n\n`{traceback.format_exc()}`", + quote=True + ) + + +@Client.on_message(filters.private & filters.command("unban_user") & filters.user(Config.BOT_OWNER)) +async def unban(c: Client, m: Message): + + if len(m.command) == 1: + await m.reply_text( + f"Use this command to unban any user.\n\n" + f"Usage:\n\n`/unban_user user_id`\n\n" + f"Eg: `/unban_user 1234567`\n" + f"This will unban user with id `1234567`.", + quote=True + ) + return + + try: + user_id = int(m.command[1]) + unban_log_text = f"Unbanning user {user_id}" + try: + await c.send_message( + user_id, + f"Your ban was lifted!" + ) + unban_log_text += '\n\nUser notified successfully!' + except: + traceback.print_exc() + unban_log_text += f"\n\nUser notification failed! \n\n`{traceback.format_exc()}`" + await db.remove_ban(user_id) + print(unban_log_text) + await m.reply_text( + unban_log_text, + quote=True + ) + except: + traceback.print_exc() + await m.reply_text( + f"Error occurred! Traceback given below\n\n`{traceback.format_exc()}`", + quote=True + ) + + +@Client.on_message(filters.private & filters.command("banned_users") & filters.user(Config.BOT_OWNER)) +async def _banned_users(_, m: Message): + + all_banned_users = await db.get_all_banned_users() + banned_usr_count = 0 + text = '' + + async for banned_user in all_banned_users: + user_id = banned_user['id'] + ban_duration = banned_user['ban_status']['ban_duration'] + banned_on = banned_user['ban_status']['banned_on'] + ban_reason = banned_user['ban_status']['ban_reason'] + banned_usr_count += 1 + text += f"> **user_id**: `{user_id}`, **Ban Duration**: `{ban_duration}`, " \ + f"**Banned on**: `{banned_on}`, **Reason**: `{ban_reason}`\n\n" + reply_text = f"Total banned user(s): `{banned_usr_count}`\n\n{text}" + if len(reply_text) > 4096: + with open('banned-users.txt', 'w') as f: + f.write(reply_text) + await m.reply_document('banned-users.txt', True) + os.remove('banned-users.txt') + return + await m.reply_text(reply_text, True) + + +@Client.on_message(filters.private & filters.command("clear_batch")) +async def clear_user_batch(bot: Client, m: Message): + MediaList[f"{str(m.from_user.id)}"] = [] + await m.reply_text("Cleared your batch files successfully!") + + +@Client.on_callback_query() +async def button(bot: Client, cmd: CallbackQuery): + + cb_data = cmd.data + if "aboutbot" in cb_data: + await cmd.message.edit( + Config.ABOUT_BOT_TEXT, + disable_web_page_preview=True, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("Source Codes of Bot", + url="https://te.legra.ph/file/42e9a66c3df08a9c1987a.mp4") + ], + [ + InlineKeyboardButton("Go Home", callback_data="gotohome"), + InlineKeyboardButton("About Dev", callback_data="aboutdevs") + ] + ] + ) + ) + + elif "aboutdevs" in cb_data: + await cmd.message.edit( + Config.ABOUT_DEV_TEXT, + disable_web_page_preview=True, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("Source Codes of Bot", + url="https://te.legra.ph/file/42e9a66c3df08a9c1987a.mp4") + ], + [ + InlineKeyboardButton("About Bot", callback_data="aboutbot"), + InlineKeyboardButton("Go Home", callback_data="gotohome") + ] + ] + ) + ) + + elif "gotohome" in cb_data: + await cmd.message.edit( + Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id), + disable_web_page_preview=True, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url="https://t.me/movies_X_animes") + ], + [ + InlineKeyboardButton("About Bot", callback_data="aboutbot"), + InlineKeyboardButton("About Dev", callback_data="aboutdevs"), + InlineKeyboardButton("Close πŸšͺ", callback_data="closeMessage") + ], + [ + InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), + InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") + ] + ] + ) + ) + + elif "refreshForceSub" in cb_data: + if Config.UPDATES_CHANNEL: + if Config.UPDATES_CHANNEL.startswith("-100"): + channel_chat_id = int(Config.UPDATES_CHANNEL) + else: + channel_chat_id = Config.UPDATES_CHANNEL + try: + user = await bot.get_chat_member(channel_chat_id, cmd.message.chat.id) + if user.status == "kicked": + await cmd.message.edit( + text="Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/TeleRoid14).", + disable_web_page_preview=True + ) + return + except UserNotParticipant: + invite_link = await get_invite_link(channel_chat_id) + await cmd.message.edit( + text="**I like Your Smartness But Don't Be Oversmart! πŸ˜‘**\n\n", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("πŸ˜‡ Join Channel πŸ˜‡", url=invite_link.invite_link) + ], + [ + InlineKeyboardButton("πŸ”„ Refresh πŸ”„", callback_data="refreshmeh") + ] + ] + ) + ) + return + except Exception: + await cmd.message.edit( + text="Something went Wrong. Contact my [Support](https://t.me/iSmartBoiUjjwal_ib_bot).", + disable_web_page_preview=True + ) + return + await cmd.message.edit( + text=Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id), + disable_web_page_preview=True, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("Movies Channel", url="https://t.me/movies_X_animes"), + InlineKeyboardButton("Movies Group", url="https://t.me/Movie_Requestt_Group") + ], + [ + InlineKeyboardButton("About Bot", callback_data="aboutbot"), + InlineKeyboardButton("About Dev", callback_data="aboutdevs") + ] + ] + ) + ) + + elif cb_data.startswith("ban_user_"): + user_id = cb_data.split("_", 2)[-1] + if Config.UPDATES_CHANNEL is None: + await cmd.answer("Sorry Sir, You didn't Set any Updates Channel!", show_alert=True) + return + if not int(cmd.from_user.id) == Config.BOT_OWNER: + await cmd.answer("You are not allowed to do that!", show_alert=True) + return + try: + await bot.kick_chat_member(chat_id=int(Config.UPDATES_CHANNEL), user_id=int(user_id)) + await cmd.answer("User Banned from Updates Channel!", show_alert=True) + except Exception as e: + await cmd.answer(f"Can't Ban Him!\n\nError: {e}", show_alert=True) + + elif "addToBatchTrue" in cb_data: + if MediaList.get(f"{str(cmd.from_user.id)}", None) is None: + MediaList[f"{str(cmd.from_user.id)}"] = [] + file_id = cmd.message.reply_to_message.id + MediaList[f"{str(cmd.from_user.id)}"].append(file_id) + await cmd.message.edit("File Saved in Batch!\n\n" + "Press below button to get batch link.", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("Get Batch Link", callback_data="getBatchLink")], + [InlineKeyboardButton("Close Message", callback_data="closeMessage")] + ])) + + elif "addToBatchFalse" in cb_data: + await save_media_in_channel(bot, editable=cmd.message, message=cmd.message.reply_to_message) + + elif "getBatchLink" in cb_data: + message_ids = MediaList.get(f"{str(cmd.from_user.id)}", None) + if message_ids is None: + await cmd.answer("Batch List Empty!", show_alert=True) + return + await cmd.message.edit("Please wait, generating batch link ...") + await save_batch_media_in_channel(bot=bot, editable=cmd.message, message_ids=message_ids) + MediaList[f"{str(cmd.from_user.id)}"] = [] + + elif "closeMessage" in cb_data: + await cmd.message.delete(True) + + try: + await cmd.answer() + except QueryIdInvalid: pass diff --git a/requirements.txt b/requirements.txt index 14f35df..f717d22 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ -Pyrogram==2.0.30 +Pyrogram==2.0.106 TgCrypto motor aiofiles dnspython psutil -aiohttp \ No newline at end of file +aiohttp diff --git a/server.py b/server.py new file mode 100644 index 0000000..2945e29 --- /dev/null +++ b/server.py @@ -0,0 +1,30 @@ +from aiohttp import web +import asyncio, logging, aiohttp, traceback +#from configs import URL + +URL = "" + +r = web.RouteTableDef() + +@r.get("/", allow_head=True) +async def root_route_handler(request): + return web.json_response("I am Alive") + +async def web_server(): + wap = web.Application(client_max_size=30000000) + wap.add_routes(r) + return wap + +async def ping_server(): + while True: + await asyncio.sleep(600) + try: + async with aiohttp.ClientSession( + timeout=aiohttp.ClientTimeout(total=10) + ) as session: + async with session.get(URL) as resp: + logging.info("Pinged server with response: {}".format(resp.status)) + except TimeoutError: + logging.warning("Couldn't connect to the site URL..!") + except Exception: + traceback.print_exc()