├── docs ├── __init__.py └── docs.py ├── utils ├── __int__.py ├── typing.py ├── guess.py ├── menus.py ├── handlers.py └── dbmanager.py ├── plugins ├── __init__.py ├── start │ └── start.py ├── sendfile │ └── sendfile.py ├── remove │ └── remove.py ├── details │ └── details.py ├── filet │ └── filet.py ├── files │ └── files.py ├── uploads │ └── uploads.py ├── getfromlink │ └── getfromlink.py ├── callbacks │ └── callbacks.py └── inlines │ └── inline.py ├── runtime.txt ├── Procfile ├── _config.yml ├── requirements.txt ├── .gitignore ├── start.sh ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── app.json ├── bot.py ├── README.md └── index.md /docs/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/__int__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /plugins/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.7.3 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: python3 bot.py -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyrogram[fast] 2 | requests 3 | TgCrypto 4 | bs4 5 | clint 6 | python-magic 7 | timeago 8 | python-telegram-bot==12.0.0b1 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /DOWNLOADS 2 | /Downloads 3 | *.session 4 | shrinkwrap.yaml 5 | installReqsAndStart.sh 6 | package.json 7 | watch.json 8 | plugins/cool-file.js 9 | plugins/speed/speed.p 10 | unknown_errors.txt 11 | ignore 12 | logfile.txt 13 | trigger 14 | welcome 15 | plugins/welcome/welcome.py -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | MD5=$(md5sum requirements.txt | cut -f1 -d' ') 4 | if ! [ -d ".data/$MD5-site-packages" ]; then 5 | rm -rf .data/*-site-packages 6 | pip3 install -U -r requirements.txt -t ".data/$MD5-site-packages" 7 | pip3 install -U pip -t ".data/$MD5-site-packages" 8 | fi 9 | exec env PYTHONPATH="$PWD/.data/$MD5-site-packages" python3 bot.py 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /plugins/start/start.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | import random 3 | import time, datetime, os, re, sys, sqlite3, json, io 4 | import requests 5 | from pyrogram import Client, Filters, ReplyKeyboardRemove 6 | dbs = DBHelper() 7 | sms = "Hello! [{}](tg://user?id={})! I can or may be able to download any downloadable file link you send to me and upload for you if and only if its a valid link. \n\n Send /faq to learn more about the usage and other useful tips" 8 | 9 | @Client.on_message(Filters.command("start")) 10 | def start(bot, m): 11 | user=m.from_user.first_name 12 | #print(bot.get_users(197005208)) 13 | id = "" 14 | if m.chat.type == 'private': 15 | smsg = sms 16 | id=m.from_user.id 17 | else: 18 | smsg = "start_msg" 19 | id=m.chat.id 20 | sent = m.reply(smsg.format(user, id), quote=True) 21 | 22 | BASE = "https://haste.thevillage.chat" 23 | 24 | logger.info('Plugin haste was imported') 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /plugins/sendfile/sendfile.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | import utils.menus 3 | import traceback 4 | 5 | @Client.on_message(Filters.regex("dl_")) 6 | def my_handler(bot, m, *args, **kwargs): 7 | chat_id = m.chat.id 8 | user = m.from_user.id 9 | h = m.text 10 | if "/start" in h: 11 | g = h[10:] 12 | else: 13 | g = h[4:] 14 | tnews = db.fileid(g) 15 | file = tnews 16 | #m.reply(tnews) 17 | apk_string = "{}".format("apks") 18 | if tnews: 19 | try: 20 | 21 | bot.send_chat_action(chat_id,'UPLOAD_DOCUMENT') 22 | time.sleep(1) 23 | m.reply_cached_media(tnews, caption="Powered with ❤️ - @Bfas237Bots") 24 | except FileIdInvalid: 25 | bot.send_chat_action(chat_id,'TYPING') 26 | time.sleep(1.5) 27 | m.reply("😔 `404` **Invalid FILE_ID**.\n\n Send /files to see your saved files") 28 | 29 | pass 30 | else: 31 | 32 | bot.send_chat_action(chat_id,'TYPING') 33 | time.sleep(1.5) 34 | m.reply("😔 `404` **Invalid FILE_ID**.\n\n Send /files to see your saved files") 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "TeleMultiStoreBot", 3 | "description": "Telegram's advanced media sharing platform. Create your Fork now.", 4 | "keywords": [ 5 | "telegram", 6 | "advanced", 7 | "media", 8 | "downloader", 9 | "3" 10 | ], 11 | "repository": "https://github.com/Bfaschat/TeleMultiStorebot", 12 | "env": { 13 | "WEBHOOK": { 14 | "description": "Setting this to ANYTHING will enable webhooks when in env mode", 15 | "value": "ANYTHING" 16 | }, 17 | "TOKEN": { 18 | "description": "Your bot token, as a string.", 19 | "value": "", 20 | "required": true 21 | }, 22 | "APP_ID": { 23 | "description": "Get this value from https://my.telegram.org", 24 | "value": "", 25 | "required": true 26 | }, 27 | "API_HASH": { 28 | "description": "Get this value from https://my.telegram.org", 29 | "value": "", 30 | "required": true 31 | }, 32 | "AUTH_USERS": { 33 | "description": "allow only pre-defined users to use this bot", 34 | "value": "197005208", 35 | "required": false 36 | }, 37 | "CHUNK_SIZE": { 38 | "description": "chunk size that should be used with requests", 39 | "value": "", 40 | "required": false 41 | } 42 | }, 43 | "addons": [ 44 | ], 45 | "buildpacks": [{ 46 | "url": "heroku/python" 47 | }] 48 | } 49 | -------------------------------------------------------------------------------- /bot.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Client, Filters 2 | import logging, os 3 | from telegram import InlineQueryResultArticle, ParseMode, \ 4 | InputTextMessageContent 5 | from telegram.ext import Updater, InlineQueryHandler, CommandHandler 6 | from telegram.utils.helpers import escape_markdown 7 | 8 | logging.basicConfig(level=logging.DEBUG, 9 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 10 | logger = logging.getLogger(__name__) 11 | logging.getLogger("telegram").setLevel(logging.INFO) 12 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 13 | plugins = dict( 14 | root="plugins" 15 | ) 16 | from plugins.inlines.inline import * 17 | def error(update, context): 18 | """Log Errors caused by Updates.""" 19 | logger.warning('"%s" %s"', update, context.error) 20 | 21 | def main(): 22 | # Create the Updater and pass it your bot's token. 23 | # Make sure to set use_context=True to use the new context based callbacks 24 | # Post version 12 this will no longer be necessary 25 | updater = Updater(os.environ.get("TOKEN"), use_context=True) 26 | 27 | # Get the dispatcher to register handlers 28 | dp = updater.dispatcher 29 | 30 | # on different commands - answer in Telegram 31 | # on noncommand i.e message - echo the message on Telegram 32 | dp.add_handler(InlineQueryHandler(answer_inline)) 33 | 34 | # log all errors 35 | dp.add_error_handler(error) 36 | 37 | # Start the Bot 38 | updater.start_polling() 39 | Client("mybots", bot_token=os.environ.get("TOKEN"), api_id=os.environ.get("api_id"), api_hash=os.environ.get("api_hash"), plugins=plugins).run() 40 | updater.idle() 41 | 42 | 43 | if __name__ == "__main__" : 44 | main() 45 | 46 | 47 | -------------------------------------------------------------------------------- /plugins/remove/remove.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | class DBHelper: 3 | def __init__(self, dbname="inshorts.db"): 4 | self.dbname = dbname 5 | self.conn = sqlite3.connect(dbname, check_same_thread=False) 6 | self.c = self.conn.cursor() 7 | 8 | def checkifexist(self, item_text, owner): 9 | likeDate = "%" + str(item_text) + "%" 10 | self.c.execute("SELECT DownloadId, User FROM files WHERE User= (?) AND DownloadId LIKE ?", (owner, likeDate, )) 11 | user = self.c.fetchone() 12 | if user is not None: 13 | return user[1] 14 | else: 15 | return None 16 | 17 | 18 | def delete_item(self, item_text,owner): 19 | stmt="DELETE FROM files WHERE DownloadId= (?) AND User= (?)" 20 | args=(item_text,owner ) 21 | self.conn.execute(stmt,args) 22 | self.conn.commit() 23 | 24 | db= DBHelper() 25 | 26 | @Client.on_message(Filters.regex("rem_")) 27 | def my_handler(bot, m): 28 | chat_id = m.chat.id 29 | user = m.from_user.id 30 | h = m.text 31 | tnews = h[5:] 32 | apk_string = "{}".format("apks") 33 | 34 | conn = sqlite3.connect('inshorts.db') 35 | try: 36 | if tnews: 37 | chat_id = str(user) 38 | report = "**❗Report:**\n\n✅ File successfully deleted from your storage:\n\nSend /files to see your download history" 39 | err = "\n**❌ Invalid file token:**\n\nUse /help to learn more about me" 40 | nauth = "\n**⚠️ 506 Unknown Error:**\n\n You are not authorised to delete this file because are not the owner\n\n Your uploaded file can be accessed using /files" 41 | unknown = "\n**⚠️ 309 UnkTraced Error:**\n\n This file could not be deleted for some technical fault. It will be rectified as soon as possible" 42 | snews = fileid(tnews) 43 | ver = db.checkifexist(tnews, chat_id) 44 | if snews: 45 | if (ver == chat_id): 46 | ok = db.delete_item(tnews, chat_id) 47 | send = m.reply(report) if ok[1] is not 1 else m.reply(unknown) 48 | else: 49 | m.reply(nauth) 50 | else: 51 | m.reply(err) 52 | else: 53 | bot.send_chat_action(chat_id,'TYPING') 54 | time.sleep(1.5) 55 | m.reply("Syntax error. Press /help for more info") 56 | 57 | except Exception as e: 58 | m.reply(str(e)) 59 | 60 | -------------------------------------------------------------------------------- /utils/typing.py: -------------------------------------------------------------------------------- 1 | 2 | from os import path 3 | import logging, urllib, os, re, sys, sqlite3, json, io, requests, datetime, requests, shutil, traceback, os.path, urllib.request, time, fnmatch, glob 4 | #shutil.rmtree('/screenshots/') 5 | from mimetypes import guess_extension 6 | import concurrent.futures 7 | import cgi 8 | import importlib 9 | import os 10 | import tempfile 11 | import shutil 12 | import sys 13 | from six.moves.urllib.parse import urlparse, urljoin 14 | from itertools import islice 15 | 16 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 17 | from telegram.ext import Updater, CommandHandler, CallbackQueryHandler 18 | 19 | import atexit 20 | 21 | import warnings, random 22 | from random import randint 23 | from pyrogram import Client, Filters, ContinuePropagation, api, Emoji 24 | 25 | logging.basicConfig(filename='logfile.txt', level=logging.DEBUG, 26 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 27 | logger = logging.getLogger(__name__) 28 | import pyrogram 29 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 30 | from uuid import uuid4 31 | 32 | from pyrogram.errors import UserIsBlocked, FloodWait, FileIdInvalid, BadRequest, Flood, InternalServerError, SeeOther, Unauthorized, UnknownError, MessageNotModified 33 | from pyrogram.api.types import UserProfilePhoto, ChatPhoto, MessageMediaPhoto, MessageMediaDocument, InputBotInlineMessageID, InputBotInlineMessageMediaAuto 34 | import random as r 35 | from requests import get 36 | import sqlite3 as lite 37 | from utils.guess import * 38 | try: 39 | from urllib.parse import quote_plus 40 | import urllib.request 41 | python3 = True 42 | except ImportError: 43 | from urllib import quote_plus 44 | import urllib2 45 | python3 = False 46 | 47 | def random_with_N_digits(n): 48 | range_start = 10**(n-1) 49 | range_end = (10**n)-1 50 | return randint(range_start, range_end) 51 | 52 | from urllib.request import urlopen 53 | 54 | from clint.textui import progress 55 | from bs4 import BeautifulSoup 56 | from datetime import datetime, timezone, date, timedelta 57 | from urllib.parse import unquote, urlparse 58 | from os.path import splitext, basename 59 | 60 | options={} 61 | base_headers = { 62 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.5 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.5', 63 | 'Accept-Encoding': 'gzip, deflate, sdch', 64 | 'Accept-Language': 'zh-CN,zh;q=0.8' 65 | } 66 | headers = dict(base_headers, **options) 67 | from utils.dbmanager import * 68 | from utils.handlers import * 69 | 70 | -------------------------------------------------------------------------------- /docs/docs.py: -------------------------------------------------------------------------------- 1 | from pyrogram import Emoji 2 | from telegram import InlineQueryResultArticle, InlineQueryResultCachedDocument, InlineQueryResultCachedVideo, InlineQueryResultCachedAudio, InlineQueryResultCachedVoice, InlineQueryResultCachedPhoto, ParseMode, \ 3 | InputTextMessageContent 4 | from telegram.ext import Updater, InlineQueryHandler, CommandHandler 5 | from telegram.utils.helpers import escape_markdown 6 | NEXT_OFFSET = 25 7 | CACHE_TIME = 5 8 | DOC_THUMB = "https://i.imgur.com/AggHpo9.png" 9 | SOFTWARE_THUMB = "https://i.imgur.com/6YVH0cr.png" 10 | IMG_THUMB = "https://i.imgur.com/fSSxJkv.png" 11 | APK_THUMB = "https://i.imgur.com/hOcYDWZ.png" 12 | MEDIA_THUMB = "https://i.imgur.com/BduvHoV.png" 13 | GLOBAL_THUMB = "https://i.imgur.com/HQs8dvW.png" 14 | FILES_THUMB = "https://i.imgur.com/zL4AJqh.png" 15 | MP3_THUMB = "https://i.imgur.com/D7ILLy6.png" 16 | HELP_THUMB = "https://i.imgur.com/6jZsMYG.png" 17 | CONTRIBUTE_THUMB = "https://i.ibb.co/cx4yGKr/icon-donate-9875400d4f44e8de9c0b5dbc812ce66c.png" 18 | 19 | APK_SEARCH_THUMB = "https://i.imgur.com/HYX5seP.png" 20 | MISC_SEARCH_THUMB = "https://i.imgur.com/UVoYOYm.png" 21 | GLOBAL_SEARCH_THUMB = "https://i.imgur.com/8FJuWCr.png" 22 | 23 | OTHER_THUMB = "https://i.imgur.com/d1tf976.png" 24 | NOT_FOUND = "https://i.imgur.com/nMQD6QN.png" 25 | ABOUT_BOT_THUMB = "https://i.imgur.com/zRglRz3.png" 26 | 27 | INLINE_HELP_SOFTWARE_THUMB = "https://i.imgur.com/lOZy5Db.png" 28 | INLINE_HELP_MOBILE_THUMB = "https://i.imgur.com/gq3baOK.png" 29 | 30 | HELP = ( 31 | "{} *TELE MULTISTORE BOT*\n\n" 32 | "Use this bot inline to search for Uploaded, files, videos, games, apps and other misc files\n\n" 33 | 34 | "*Search Examples*\n" 35 | "`@TeleMultiStoreBot ` – Global Search\n" 36 | "`@TeleMultiStoreBot !soft ` – Privately Search your storage\n" 37 | "`@TeleMultiStoreBot !store ` – Search apps and games\n\n" 38 | 39 | "*List*\n" 40 | "`@TeleMultiStoreBot !pic` – Search Pictures\n" 41 | "`@TeleMultiStoreBot !zip` – Search Archive files\n" 42 | "`@TeleMultiStoreBot !store` – Search apps and games\n" 43 | "`@TeleMultiStoreBot !vid` – Search movies and series\n" 44 | "`@TeleMultiStoreBot !mp3` – Search songs\n" 45 | "`@TeleMultiStoreBot !doc` – Search Pdfs, docs, epub\n\n".format(Emoji.ROBOT_FACE) 46 | ) 47 | HELP_INLINE = ( 48 | "{} *TELE MULTISTORE BOT*\n\n" 49 | "To better understand how it works, lets go inline\n\n".format(Emoji.ROBOT_FACE) 50 | ) 51 | CONTRIBUTE = ( 52 | "❤️ *CONTRIBUTIONS*\n\n" 53 | "🌐 The main purpose of this bot is to make available thousands " 54 | "of files to millions of telegram users which we take it " 55 | "as a sole responsibility to do. \n\n" 56 | 57 | "🌐 For your own part, all you have to do is forward any file to this bot " 58 | "and it will be saved and made available for anyone who may search for it \n\n" 59 | 60 | "🆘 Feel free to report any bug in our support group for by doing so " 61 | "You are helping us to help others. \n\n" 62 | 63 | "@Bfas237Bots `at your service`" 64 | ) 65 | -------------------------------------------------------------------------------- /plugins/details/details.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from utils.menus import * 3 | 4 | 5 | state = {} 6 | 7 | 8 | @Client.on_message(Filters.regex("de_")) 9 | def my_handler(bot, m): 10 | chat_id = m.chat.id 11 | userd = m.from_user.id 12 | ids = [] 13 | 14 | ids.append(userd) 15 | h = m.text 16 | if "/start" in h: 17 | g = h[10:] 18 | else: 19 | g = h[4:] 20 | row = "" 21 | admin = False 22 | private = 0 23 | try: 24 | snews = db.fileid(g) 25 | if snews: 26 | num, row, fid, dat, tim, siz, did = db.vfileid(g) 27 | nums = db.checkd(str(userd), g) 28 | else: 29 | row = None 30 | if row: 31 | user = db.ufil(did, str(userd)) 32 | ids.append(user) 33 | yr, mm, day, hr, mte, sec = db.cdate(did) 34 | ds = datetime(yr, mm, day, hr, mte, sec ) 35 | usr = db.getuser(did, str(userd)) 36 | idss = [str(userd), usr] 37 | if(user != 0): 38 | item = ( 39 | "🆔 : #{} \n\n" 40 | "ℹ️ : {}\n\n" 41 | "⌛️ : {} | 🕰 {}\n\n" 42 | "⚖️ : {}\n" 43 | "-----------------------------------------------------------------------------------------------------""".format(str(nums), str(row[:50]), dat, timedate(ds), pretty_size(int(siz)))) 44 | 45 | bot.send_chat_action(chat_id,'TYPING') 46 | time.sleep(1) 47 | admin = True 48 | private = 1 49 | else: 50 | item = ( 51 | "🆔 : #{} \n\n" 52 | "ℹ️ : {}\n\n" 53 | "⌛️ : {} | 🕰 {}\n\n" 54 | "⚖️ : {}\n" 55 | "-----------------------------------------------------------------------------------------------------""".format(str(nums), str(row), dat, timedate(ds), pretty_size(int(siz)))) 56 | 57 | bot.send_chat_action(chat_id,'TYPING') 58 | time.sleep(1) 59 | admin = False 60 | private = 0 61 | 62 | kb = reg_keyboard(id=did, admin=usr in idss if usr else False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=private, auth=[]) 63 | reply_markup = InlineKeyboardMarkup(kb) 64 | 65 | m.reply("{}\n\nPowered with ❤️ - @Bfas237Bots".format(item), parse_mode="html", reply_markup=reply_markup) 66 | # + b"%" + str(dat).encode('UTF-8') + b"%" + str(tim).encode('UTF-8') + b"%" + str(siz).encode('UTF-8') + b"%" + str(did.encode('UTF-8') 67 | else: 68 | 69 | bot.send_chat_action(chat_id,'TYPING') 70 | time.sleep(1.5) 71 | m.reply("😔 `404` **Invalid FILE_ID**.\n\n Send /files to see your saved files") 72 | 73 | except: 74 | traceback.print_exc() 75 | 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Tele MultiStore Bot 3 | [![LIBRARY](https://img.shields.io/badge/Advanced%20Multipurpose%20Telegram%20Store%20Bot-V0.05-red.svg)](https://docs.pyrogram.org) 4 | ![PYTHON](https://img.shields.io/badge/Python-%3E%3D3.5-8892bf.svg) [![LIBRARY](https://img.shields.io/badge/Telegram-Group-blue.svg)](https://telegram.me/bfas237botdevs) [![LIBRARY](https://img.shields.io/badge/IRC-Channel-36ade1.svg)](https://telegram.me/https://webchat.freenode.net/?channels=##bfas237bots) 5 | 6 | 7 | 8 | > An advanced Multipurpose [Telegram Bot](http://t.me/TeleMultiStoreBot) for uploading and sharing media files across chats. 9 | > Supports Inline Mode for quciker and better compatibility 10 | > (Almost) Complete but for now its still in BETA stage. 11 | 12 | Requirements 13 | --------- 14 | 15 | * Python >=3.6 16 | * Telegram account. 17 | * Telegram API key, you can get one simply with [@BotFather](https://core.telegram.org/bots#botfather) with simple commands right after creating your bot. 18 | * Your own `API_ID` and `API_HASH` [HOW TO GET MY API CREDENTIALS](https://docs.pyrogram.org) 19 | 20 | 21 | Dependencies 22 | --------- 23 | - Pyrogram 24 | - requests 25 | - TgCrypto 26 | - bs4 27 | - clint 28 | - python-magic 29 | - timeago 30 | - `Python-telegram-bot` For current inline support 31 | 32 | 33 | Normal Installation 34 | --------- 35 | 36 | Create env variables as the one below. 37 | 38 | ##### ENV Configuration 39 | 40 | * Replace the values as specified [HERE](https://docs.pyrogram.org). 41 | 42 | > If you use Heroku then this will be very easy to understand 43 | 44 | ``` 45 | TOKEN="123456789:hdhdhdbhfjfkrp889g8g889" 46 | APP_ID=12345 47 | API_HASH="0123456789abcdef0123456789abcdef" 48 | 49 | ``` 50 | 51 | * Learn more about how to create and [deploy apps to Heroku](https://devcenter.heroku.com/articles/git#for-a-new-heroku-app) 52 | 53 | 54 | The Hard Way (Advanced users only) 55 | --------- 56 | 57 | ```sh 58 | virtualenv -p python3 VENV 59 | . ./VENV/bin/activate 60 | pip3 install -r requirements.txt 61 | ``` 62 | 63 | 64 | ### Run Bot 65 | 66 | ``` 67 | python3 bot.py 68 | 69 | ``` 70 | 71 | 72 | Easy Installation and Deploy 73 | --------- 74 | 75 | > This section covers the case where someone is unfamiliar with python in deeper sense. If you are that type then this section has been made purposely for you. 76 | 77 | > We are not spoonfeeding you but just making things easier. Read this carefully 78 | 79 | 80 | If you don't want to go through all those hard process then just click the button below and fill the fields as specified. 81 | 82 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/Bfaschat/TeleMultiStorebot/tree/glitch) 83 | 84 | 85 | ## Supported Features 86 | 87 | 88 | - [x] Search using inline mode for any uploaded file 89 | - [x] search your storage through Inline Mode 90 | - [x] Asynchronous File Storage 91 | - [x] Lock and unlock Files 92 | - [x] Download and upload with progress bar 93 | - [x] Sort Files according to Media Types 94 | 95 | ## Features to be Added: 96 | 97 | - [ ] Cancel a particular Download 98 | - [ ] Decrypt and encrypt files with passwords 99 | - [ ] Unarchive archivable files 100 | - [ ] Download torrens 101 | 102 | 103 | 104 | ## Screenshots 105 | 106 | > To be updated..... 107 | 108 | 109 | Contact me 110 | ------------ 111 | You can contact me [via Telegram](https://telegram.me/bfaschat) but if you have an issue please [open](https://github.com/Bfaschat/TeleMultiStorebot/issues) one. 112 | 113 | 114 | Contributing 115 | ------------ 116 | 117 | Tele MultiStore is brand new, and *you are welcome to try it and help make it even better* by either submitting pull requests or reporting issues/bugs as well as suggesting best practices, ideas, enhancements on both code and documentation. Any help is appreciated! 118 | 119 | 120 | 121 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 122 | [![forthebadge](https://forthebadge.com/images/badges/for-you.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 123 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 124 | 125 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | 2 | # Tele MultiStore Bot 3 | [![LIBRARY](https://img.shields.io/badge/Advanced%20Multipurpose%20Telegram%20Store%20Bot-V0.05-red.svg)](https://docs.pyrogram.ml) 4 | ![PYTHON](https://img.shields.io/badge/Python-%3E%3D3.5-8892bf.svg) [![LIBRARY](https://img.shields.io/badge/Telegram-Group-blue.svg)](https://telegram.me/bfas237botdevs) [![LIBRARY](https://img.shields.io/badge/IRC-Channel-36ade1.svg)](https://telegram.me/https://webchat.freenode.net/?channels=##bfas237bots) 5 | 6 | 7 | 8 | > An advanced Multipurpose [Telegram Bot](http://t.me/TeleMultiStoreBot) for uploading and sharing mdeia files across chats. 9 | > Supports Inline Mode for quciker and better compatibility 10 | > (Almost) Complete but for now its still in BETA stage. 11 | 12 | Requirements 13 | --------- 14 | 15 | * Python >=3.5 16 | * Telegram account. 17 | * Telegram API key, you can get one simply with [@BotFather](https://core.telegram.org/bots#botfather) with simple commands right after creating your bot. 18 | * Your own `API_ID` and `API_HASH` [HOW TO GET MY API CREDENTIALS](https://docs.pyrogram.ml/start/Setup.html#api-keys) 19 | 20 | 21 | Dependencies 22 | --------- 23 | - Pyrogram 24 | - requests 25 | - TgCrypto 26 | - bs4 27 | - clint 28 | - python-magic 29 | - timeago 30 | - `Python-telegram-bot` For current inline support 31 | 32 | 33 | Normal Installation 34 | --------- 35 | 36 | Create env variables as the one below. 37 | 38 | ##### ENV Configuration 39 | 40 | * Replace the values as specified [HERE](https://docs.pyrogram.ml/start/Setup#api-keys). 41 | 42 | > If you use Heroku then this will be very easy to understand 43 | 44 | ``` 45 | TOKEN="123456789:hdhdhdbhfjfkrp889g8g889" 46 | APP_ID=12345 47 | API_HASH="0123456789abcdef0123456789abcdef" 48 | 49 | ``` 50 | 51 | * Learn more about how to create and [deploy apps to Heroku](https://devcenter.heroku.com/articles/git#for-a-new-heroku-app) 52 | 53 | 54 | The Hard Way (Advanced users only) 55 | --------- 56 | 57 | ```sh 58 | virtualenv -p python3 VENV 59 | . ./VENV/bin/activate 60 | pip3 install -r requirements.txt 61 | ``` 62 | 63 | 64 | ### Run Bot 65 | 66 | ``` 67 | python3 bot.py 68 | 69 | ``` 70 | 71 | 72 | Easy Installation and Deploy 73 | --------- 74 | 75 | > This section covers the case where someone is unfamiliar with python in deeper sense. If you are that type then this section has been made purposely for you. 76 | 77 | > We are not spoonfeeding you but just making things easier. Read this carefully 78 | 79 | 80 | If you don't want to go through all those hard process then just click the button below and fill the fields as specified. 81 | 82 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/Bfaschat/TeleMultiStorebot/tree/glitch) 83 | 84 | 85 | ## Supported Features 86 | 87 | 88 | - [x] Search using inline mode for any uploaded file 89 | - [x] search your storage through Inline Mode 90 | - [x] Asynchronous File Storage 91 | - [x] Lock and unlock Files 92 | - [x] Download and upload with progress bar 93 | - [x] Sort Files according to Media Types 94 | 95 | ## Features to be Added: 96 | 97 | - [ ] Cancel a particular Download 98 | - [ ] Decrypt and encrypt files with passwords 99 | - [ ] Unarchive archivable files 100 | - [ ] Download torrens 101 | 102 | 103 | 104 | ## Screenshots 105 | 106 | > To be updated..... 107 | 108 | 109 | Contact me 110 | ------------ 111 | You can contact me [via Telegram](https://telegram.me/bfaschat) but if you have an issue please [open](https://github.com/Bfaschat/TeleMultiStorebot/issues) one. 112 | 113 | 114 | Contributing 115 | ------------ 116 | 117 | Tele MultiStore is brand new, and *you are welcome to try it and help make it even better* by either submitting pull requests or reporting issues/bugs as well as suggesting best practices, ideas, enhancements on both code and documentation. Any help is appreciated! 118 | 119 | 120 | 121 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 122 | [![forthebadge](https://forthebadge.com/images/badges/for-you.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 123 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://github.com/Bfaschat/TeleMultiStorebot) 124 | 125 | -------------------------------------------------------------------------------- /plugins/filet/filet.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from utils.menus import * 3 | import subprocess 4 | 5 | class Translation(object): 6 | START_TEXT = "Welcome to our bot. I am capable of downloading your best apps within seconds. \n\nI can do some basic functions for now which you can discover by navigating by yourself. Hope you find me useful 😊\n\nFor more help use the help button or just send /help\n\n" 7 | ABS_TEXT = " Please don't be selfish." 8 | UPGRADE_TEXT = "No upgrades!" 9 | NOT_AUTH_USER_TEXT = "The bot developer is a selfish dude. for now you can\'t download anything for this is just the beta bot. try the main bot at @gmotherbot" 10 | CUSTOM_CAPTION_UL_FILE = " © @Bfas237Bots" 11 | 12 | SAVED_RECVD_DOC_FILE = "Document Downloaded Successfully." 13 | REPLY_TO_DOC_GET_LINK = "Reply to a Telegram media to get High Speed Direct Download Link" 14 | FILETRANSFER_GET_DL_LINK = "Filetransfer.sh Direct Link Generated valid for {} days.\n\nFile.io Direct Link Generated valid for {} days.\n\nanonfile.com Direct Link Generated valid for ^^ days.\n\n© @bfas237bots" 15 | 16 | DOWNLOAD_START = "**⏳ Initializing Your request**..." 17 | UPLOAD_START = "**⬆️ Uploading to external file hosting**" 18 | SERVICES = "Services Used by @APKFetcherBot\n\n🔋 Pyrogram - For Ultra fast download speed\n\n🔋 Transfer.sh - For External File Hosting\n\n🔋 File.io - For External File Hosting\n\n🔋 bsbe.cf - Trimming your long links" 19 | active_chats = {} 20 | @Client.on_message(Filters.command("link")) 21 | def ft(bot, update): 22 | global active_chats 23 | start = time.time() 24 | if update.from_user.id not in active_chats: 25 | active_chats[update.from_user.id] = {'actions': []} 26 | active_chats[update.from_user.id]['actions'].append('filetransfer') 27 | if update.reply_to_message is not None: 28 | logger.warning('Downloading with filetransfer') 29 | reply_message = update.reply_to_message 30 | required_file_name = "{}/.data".format(os.getcwd()) 31 | download_location = required_file_name + "/" 32 | a = update.reply(Translation.DOWNLOAD_START, 33 | quote=True 34 | ) 35 | after_download_file_name = bot.download_media( 36 | message=reply_message, 37 | file_name=download_location, progress = DFromUToTelegramProgress, progress_args = (a, update.chat.id, start, "**📥 Downloading:**") 38 | ) 39 | filename_w_ext = os.path.basename(after_download_file_name) 40 | filename, download_extension = os.path.splitext(filename_w_ext) 41 | filename = filename.strip('\n').replace(' ','_') 42 | bot.edit_message_text( 43 | text=Translation.SAVED_RECVD_DOC_FILE, 44 | chat_id=update.from_user.id, 45 | message_id=a.message_id 46 | ) 47 | url = "https://transfer.sh/{}{}".format(str(filename), str(download_extension)) 48 | max_days = "7" 49 | command_to_exec = [ 50 | "curl", 51 | # "-H", 'Max-Downloads: 1', 52 | "-H", 'Max-Days: 7', # + max_days + '', 53 | "--upload-file", after_download_file_name, 54 | url 55 | ] 56 | a.edit(Translation.UPLOAD_START 57 | ) 58 | expires = "1w" 59 | 60 | url = "https://file.io/?expires={expires}" 61 | fin = open(after_download_file_name, 'rb') 62 | files = {'file': fin} 63 | try: 64 | max_days = "7" 65 | r = requests.post(url, files=files).json() 66 | print(r['link']) 67 | urls = " https://anonfile.com/api/upload" 68 | rs = requests.post(urls, files=files).json() 69 | print(rs['data']['file']['url']['short']) 70 | logger.info(command_to_exec) 71 | t_response = subprocess.check_output(command_to_exec, stderr=subprocess.STDOUT) 72 | except subprocess.CalledProcessError as exc: 73 | logger.info("Status : FAIL", exc.returncode, exc.output) 74 | bot.edit_message_text( 75 | chat_id=update.from_user.id, 76 | text=exc.output.decode("UTF-8"), 77 | message_id=a.message_id 78 | ) 79 | except: 80 | bot.edit_message_text( 81 | chat_id=update.from_user.id, 82 | text="Error uploading file", 83 | message_id=a.message_id 84 | ) 85 | os.remove(after_download_file_name) 86 | pass 87 | 88 | else: 89 | 90 | t_response_arry = t_response.decode("UTF-8").split("\n")[-1].strip() 91 | bot.edit_message_text( 92 | chat_id=update.from_user.id, 93 | text=Translation.FILETRANSFER_GET_DL_LINK.format(t_response_arry, max_days,r['link'], max_days, rs['data']['file']['url']['short']), 94 | parse_mode="HTML", 95 | message_id=a.message_id, 96 | disable_web_page_preview=True 97 | ) 98 | 99 | 100 | finally: 101 | os.remove(after_download_file_name) 102 | fin.close() 103 | pass 104 | else: 105 | bot.send_message( 106 | chat_id=update.from_user.id, 107 | text=Translation.REPLY_TO_DOC_GET_LINK, 108 | reply_to_message_id=update.message_id 109 | ) 110 | -------------------------------------------------------------------------------- /plugins/files/files.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from utils.menus import * 3 | 4 | 5 | state = {} 6 | @Client.on_message(Filters.command("files")) 7 | def sendServerStartedMessage(bot, m): 8 | global state 9 | link = " ".join(m.command[1:]) 10 | logger.info(m.text) 11 | msg = m.text 12 | chat_id = m.chat.id 13 | bot.send_chat_action(chat_id,'TYPING') 14 | # Connecting to the SQL database 15 | conn = sqlite3.connect('inshorts.db') 16 | c = conn.cursor() 17 | con = conn.cursor() 18 | dd = m.from_user.id 19 | 20 | try: 21 | t = int(re.search(r'\d+', link).group()) 22 | off = int(t) 23 | except: 24 | off = 0 25 | if m.from_user.id not in state: 26 | state[m.from_user.id] = {'actions': []} 27 | state[m.from_user.id]['actions'].append('files') 28 | logger.warning(state) 29 | chat_id = str(dd) 30 | likeDate = "%" + str(link) + "%" 31 | c.execute("SELECT ID, Fname, DownloadId, Size, Media FROM files WHERE Fname LIKE ? OR DownloadId LIKE ? OR Media LIKE ? ORDER BY ID DESC LIMIT 1000 OFFSET ?", (likeDate, likeDate, likeDate, off, )) 32 | con.execute("SELECT COUNT (*) FROM files WHERE User = ?", (chat_id, )) 33 | last = 0 34 | su = [] 35 | med = "" 36 | if "Software" in su: 37 | med = "🗳" 38 | elif "Music" in su: 39 | med = "📮" 40 | elif "Video" in su: 41 | med = "💽" 42 | elif "Documents" in su: 43 | med = "📑" 44 | elif "Archives" in su: 45 | med = "🗃" 46 | elif "Apps" in su: 47 | med = "🗂" 48 | elif "Pictures" in su: 49 | med = "🖼" 50 | else: 51 | med = "📦" 52 | rowcount = con.fetchone()[0] 53 | rows = c.fetchall() 54 | things = [list(i) for i in rows] 55 | for ft in things[0:49]: 56 | su.append(str(ft[4])) 57 | try: 58 | if things: 59 | items = "" 60 | lens = len(rows) 61 | for num, row in enumerate(things[0:5]): 62 | items += ( 63 | "#{} " 64 | " {}" 65 | "\n\n📥 Download | 📍 Details | 🗳 {} | {}\n" 66 | "\n" 67 | "-------------------------\n" 68 | "\n".format(str(num), (row[1][:70] + '..') if len(row[1]) > 75 else row[1], row[2], row[2], pretty_size(int(row[3])), med, row[4])) 69 | 70 | kb = search_keyboard(query=link, offset=0 if off <= 5 else off, rows=rowcount, last=last, show_download=True) 71 | reply_markup = InlineKeyboardMarkup(kb) 72 | username = m.from_user.username 73 | src = m.reply("📄 {}'s files Library: Page {} out of {} \n\n {}".format(username, 0 if off <= 5 else off, len(things), items),reply_markup = reply_markup, parse_mode="html") 74 | user_chat = state.get(m.from_user.id, None) 75 | user_chat['msg'] = None 76 | user_chat['msgid'] = src 77 | user_chat['off'] = off 78 | 79 | else: 80 | m.reply("No items in your list") 81 | except: 82 | traceback.print_exc() 83 | 84 | 85 | 86 | @Client.on_message(Filters.regex("files@")) 87 | def my_handler(bot, m): 88 | global state 89 | chat_id = m.chat.id 90 | user = m.from_user.id 91 | h = m.text 92 | if "/start" in h: 93 | g = h[10:] 94 | else: 95 | g = h[:6] 96 | #m.reply(tnews) 97 | #us = Client.resolve_peer("self", peer_id="Bfaschat") 98 | #print(us) 99 | bot.send_chat_action(chat_id,'TYPING') 100 | # Connecting to the SQL database 101 | conn = sqlite3.connect('inshorts.db') 102 | c = conn.cursor() 103 | con = conn.cursor() 104 | dd = m.from_user.id 105 | off = 0 106 | if m.from_user.id not in state: 107 | state[m.from_user.id] = {'actions': []} 108 | state[m.from_user.id]['actions'].append('files') 109 | logger.warning(state) 110 | chat_id = str(user) 111 | c.execute("SELECT ID, Fname, DownloadId, Size FROM files WHERE User = ? ORDER BY ID DESC LIMIT 5 OFFSET ?", (chat_id, off, )) 112 | con.execute("SELECT COUNT (*) FROM files WHERE User = ?", (chat_id, )) 113 | last = 0 114 | rowcount = con.fetchone()[0] 115 | rows = c.fetchall() 116 | conn.close() 117 | try: 118 | if len(rows) > 0: 119 | items = "" 120 | lens = len(rows) 121 | for row in rows: 122 | items += ( 123 | "#{} " 124 | " {}" 125 | "\n📥 Download | 📍 Details\n" 126 | "{}\n" 127 | "------\n" 128 | "".format(str(row[0]), row[1][:50], row[2], row[2], pretty_size(int(row[3])))) 129 | 130 | kb = search_keyboard(offset=0, rows=rowcount, last=last, show_download=True) 131 | reply_markup = InlineKeyboardMarkup(kb) 132 | username = m.from_user.username 133 | src = m.reply("📄 {}'s files Library: {} out of {} \n\n {}".format(username, lens, rowcount, items),reply_markup = reply_markup, parse_mode="html") 134 | user_chat = state.get(m.from_user.id, None) 135 | user_chat['msg'] = None 136 | user_chat['msgid'] = src 137 | user_chat['off'] = off 138 | 139 | else: 140 | m.reply("No items in your list") 141 | except: 142 | traceback.print_exc() 143 | apk_string = "{}".format("apks") 144 | 145 | -------------------------------------------------------------------------------- /plugins/uploads/uploads.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from utils.menus import * 3 | import traceback 4 | DOWNLOAD_LOCATION = "./DOWNLOADS" 5 | 6 | 7 | @Client.on_message(Filters.media & Filters.incoming) 8 | def my_handler(bot, m): 9 | data = list() 10 | 11 | ids = [] 12 | chat_id = m.chat.id 13 | user = m.from_user.id 14 | ids.append(user) 15 | file = m 16 | file_name = "" 17 | file_size = "" 18 | extension = "" 19 | media = "" 20 | #print(m) 21 | download_id = generate_uuid() 22 | nauth = "\n**⚠️ 541 Unknown Media Type:**\n\n Media type not allowed\n\n To see supported media types, send /media_types" 23 | invalid_media_type = "\n**⚠️ 614 Unsupported Media Type:**\n\n Media type not Supported\n\n To see supported media types, send /media_types" 24 | if file.document: 25 | file_size = file.document.file_size 26 | file_name = file.document.file_name 27 | file_id = file.document.file_id 28 | extension = guess_extension(file.document.mime_type) 29 | media = check_media(file_name) 30 | elif file.video: 31 | file_size = file.video.file_size 32 | file_name = file.video.file_name 33 | file_id = file.video.file_id 34 | mime = file.video.mime_type 35 | extension = guess_extension(file.video.mime_type) 36 | media = "Video" 37 | elif file.audio: 38 | file_size = file.audio.file_size 39 | file_name = file.audio.file_name 40 | file_id = file.audio.file_id 41 | extension = guess_extension(file.audio.mime_type) 42 | media = "Music" 43 | elif file.photo: 44 | file_size = file.photo.sizes[-1]["file_size"] 45 | file_id = file.photo.sizes[-1]["file_id"] 46 | download_id = generate_uuid() 47 | file_name = file.photo.id + ".jpg" 48 | extension = get_extension(file) 49 | media = "Pictures" 50 | elif file.voice: 51 | file_size = file.voice.file_size 52 | file_name = "voice_"+str(file.voice.date) 53 | file_id = file.voice.file_id 54 | extension = guess_extension(file.voice.mime_type) 55 | media = "Voice" 56 | 57 | elif file.video_note: 58 | if m.chat.type == 'private': 59 | m.reply(nauth) 60 | elif file.sticker: 61 | if m.chat.type == 'private': 62 | m.reply(nauth) 63 | return 64 | elif file.animation: 65 | if m.chat.type == 'private': 66 | m.reply(nauth) 67 | return 68 | else: 69 | pass 70 | if not media: 71 | m.reply(invalid_media_type) 72 | return 73 | logger.warning('You just uploaded an: "%s"', media) 74 | admin = '' 75 | message = m 76 | try: 77 | 78 | chat_id = message.chat.id 79 | uploader = user 80 | url = "https://t.me/jhbjh14514jjhbot" 81 | if file.photo: 82 | chk, ext = splitext(file_name) 83 | logger.info(chk) 84 | 85 | chk = doc(file_name) 86 | item = "" 87 | private = 0 88 | if (chk != 0): 89 | num, row, fid, dat, tim, siz, did = vfileid(chk) 90 | if row: 91 | user = ufil(did, str(uploader)) 92 | ids.append(user) 93 | usr = getuser(did, str(uploader)) 94 | idss = [str(uploader), usr] 95 | d, df, ff, h, m, s = cdate(did) 96 | 97 | ds = datetime(d, df, ff, h, m, s) 98 | 99 | logger.info(ids) 100 | if(user != 0): 101 | item = ( 102 | "🆔 : #{} \n\n" 103 | "ℹ️ : {}\n\n" 104 | "⌛️ : {} | 🕰 {}\n\n" 105 | "⚖️ {}\n" 106 | "------------------------------""".format(str(num), str(row[:50]), dat, timedate(ds), pretty_size(int(siz)))) 107 | 108 | bot.send_chat_action(chat_id,'TYPING') 109 | time.sleep(1) 110 | private = 1 111 | else: 112 | item = ( 113 | "🆔 : #{} \n\n" 114 | "ℹ️ : {}\n\n" 115 | "⌛️ : {} | 🕰 {}\n\n" 116 | "⚖️ {}\n" 117 | "------------------------------""".format(str(num), str(row[:50]), dat, timedate(ds), pretty_size(int(siz)))) 118 | 119 | 120 | kb = doc_keyboard(id=did, admin=usr in idss if usr else False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=private, auth=[]) 121 | reply_markup = InlineKeyboardMarkup(kb) 122 | 123 | 124 | else: 125 | download_id = generate_uuid() 126 | now = datetime.now() 127 | year = int(now.strftime("%Y")) 128 | month = int(now.strftime("%m")) 129 | day = int(now.strftime("%d")) 130 | h = int(now.strftime("%H")) 131 | m = int(now.strftime("%M")) 132 | s = int(now.strftime("%S")) 133 | times = datetime.now().strftime("%I:%M%p") 134 | dates = datetime.now().strftime("%B %d, %Y") 135 | 136 | addtoDb(file_name, file_size, file_id, download_id, times, dates, str(uploader), url, year, month, day, h, m, s, 0, media) 137 | 138 | 139 | chk = doc(file_name) 140 | item = "" 141 | row = "" 142 | private = 0 143 | if (chk != 0): 144 | num, row, fid, dat, tim, siz, did = vfileid(chk) 145 | if row: 146 | user = ufil(did, str(uploader)) 147 | ids.append(user) 148 | usr = getuser(did, str(uploader)) 149 | idss = [str(uploader), usr] 150 | d, df, ff, h, m, s = cdate(did) 151 | 152 | ds = datetime(d, df, ff, h, m, s) 153 | 154 | logger.info(ids) 155 | if(user != 0): 156 | item = ( 157 | "🆔 : #{} \n\n" 158 | "ℹ️ : {}\n\n" 159 | "⌛️ : {} | 🕰 {}\n\n" 160 | "⚖️ {}\n" 161 | "------------------------------""".format(str(num), str(row[:50]), dat, timedate(ds), pretty_size(int(siz)))) 162 | 163 | bot.send_chat_action(chat_id,'TYPING') 164 | time.sleep(1) 165 | private = 1 166 | else: 167 | item = ( 168 | "🆔 : #{} \n\n" 169 | "ℹ️ : {}\n\n" 170 | "⌛️ : {} | 🕰 {}\n\n" 171 | "⚖️ {}\n" 172 | "------------------------------""".format(str(num), str(row[:50]), dat, timedate(ds), pretty_size(int(siz)))) 173 | 174 | bot.send_chat_action(chat_id,'TYPING') 175 | time.sleep(1) 176 | 177 | kb = doc_keyboard(id=did, admin=usr in idss if usr else False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=private, auth=[]) 178 | reply_markup = InlineKeyboardMarkup(kb) 179 | except sqlite3.ProgrammingError as e: 180 | logger.debug(e) 181 | message.reply("Hold on! {}, you are spamming take it easy. 🙄:(".format(message.from_user.first_name)) 182 | return 183 | except FileIdInvalid as e: 184 | logger.debug(e) 185 | 186 | message.reply("⚠️ **401 Fatal Error:** \n\nI have notifed my master. He should be fixing it by now") 187 | 188 | return 189 | 190 | -------------------------------------------------------------------------------- /plugins/getfromlink/getfromlink.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | import utils.menus 3 | import traceback 4 | DOWNLOAD_LOCATION = "./DOWNLOADS" 5 | 6 | @Client.on_message(Filters.command("get")) 7 | def dl(client, message, **current): 8 | try: 9 | url = " ".join(message.command[1:]) 10 | logger.info(message.from_user) 11 | required_file_name = "" 12 | media = "" 13 | file_name = "" 14 | file_size = "" 15 | extension = "" 16 | fnames = "" 17 | download_path = "{}/.data".format(os.getcwd()) 18 | m = message 19 | invalid_media_type = "\n**⚠️ 614 Unsupported Media Type:**\n\n Media type not Supported\n\n To see supported media types, send /media_types" 20 | if not "http" in message.text: 21 | message.reply("That is not a valid link. Use /help for more info") 22 | return True 23 | else: 24 | ctype = get_filename(url) 25 | if ctype: 26 | if ctype[0] is None: 27 | err = "`The link you submitted is invalid.`\n\ Kindly check your link and try again for I am in no mood to tell you the exact reason 😒" 28 | message.reply(str(err), quote=True) 29 | logger.warning(str(err)) 30 | return 31 | required_file_name = ctype[0] 32 | fnames = ctype[1] 33 | sent = message.reply("**Checking:** `{}`\n\n if it exist on my server..".format(required_file_name), quote=True, reply_to_message_id=message.message_id) 34 | time.sleep(2) 35 | tnews, size = db.sfileid(url) 36 | if(tnews != 0): 37 | time.sleep(2) 38 | message.reply_cached_media(tnews, caption="Powered with ❤️ - @Bfas237Bots") 39 | 40 | sent.delete() 41 | elif(size == 0): 42 | rd = 1 43 | sent.delete() 44 | start = time.time() 45 | sent = message.reply("**Downloading...**", quote=True, reply_to_message_id=message.message_id) 46 | time.sleep(3) 47 | 48 | downl = DownLoadFile(url, required_file_name, fnames, client, sent, message.chat.id) 49 | 50 | if downl: 51 | if (downl != 0): 52 | sent.edit("Done ✅.. Now uploading..") 53 | time.sleep(3) 54 | chat_id = message.from_user.id 55 | required_file_name = download_path+"/"+required_file_name 56 | logger.warning('"%s" Just downloaded: "%s"', message.from_user.id, required_file_name) 57 | mediaq = check_media(required_file_name) 58 | file = "" 59 | if mediaq == 'Pictures': 60 | file = client.send_photo(message.chat.id, required_file_name, progress = DFromUToTelegramProgress, progress_args = (sent, message.chat.id, start, "**📤 Uploading:**")) 61 | elif mediaq == 'Video': 62 | file = client.send_video(message.chat.id, required_file_name, progress = DFromUToTelegramProgress, progress_args = (sent, message.chat.id, start, "**📤 Uploading:**")) 63 | elif mediaq == 'Music': 64 | file = client.send_audio(message.chat.id, required_file_name, progress = DFromUToTelegramProgress, progress_args = (sent, message.chat.id, start, "**📤 Uploading:**")) 65 | else: 66 | file = client.send_document(message.chat.id, required_file_name, progress = DFromUToTelegramProgress, progress_args = (sent, message.chat.id, start, "**📤 Uploading:**")) 67 | logs = -1001249303594 68 | 69 | #client.send_message(chat_id="bfaslogs", text="**Download Logs**\n\n{}".format(log), disable_web_page_preview=True) 70 | os.remove(required_file_name) 71 | download_id = generate_uuid() 72 | if file.document: 73 | file_size = file.document.file_size 74 | file_name = file.document.file_name 75 | file_id = file.document.file_id 76 | extension = guess_extension(file.document.mime_type) 77 | elif file.video: 78 | file_size = file.video.file_size 79 | file_name = file.video.file_name 80 | file_id = file.video.file_id 81 | extension = guess_extension(file.video.mime_type) 82 | elif file.audio: 83 | file_size = file.audio.file_size 84 | file_name = file.audio.file_name 85 | file_id = file.audio.file_id 86 | extension = guess_extension(file.audio.mime_type) 87 | elif file.photo: 88 | file_size = file.photo.sizes[-1]["file_size"] 89 | file_id = file.photo.sizes[-1]["file_id"] 90 | nowq = datetime.now() 91 | current_date_time = str(nowq).split(" ")[0] + " " + str(nowq.hour) + ":" + str(nowq.minute) + ":" + str(nowq.second) 92 | file_name = fnames +"_"+ current_date_time + ".jpg" 93 | extension = get_extension(file) 94 | elif file.sticker: 95 | if m.chat.type == 'private': 96 | m.reply(nauth) 97 | return 98 | elif file.voice: 99 | if m.chat.type == 'private': 100 | m.reply(nauth) 101 | return 102 | elif file.animation: 103 | if m.chat.type == 'private': 104 | m.reply(nauth) 105 | return 106 | elif file.videonote: 107 | if m.chat.type == 'private': 108 | m.reply(nauth) 109 | return 110 | else: 111 | pass 112 | uploader = message.from_user.id 113 | 114 | chk = db.filen(file_name) 115 | if(chk == required_file_name): 116 | rnd = random_with_N_digits(2) 117 | file_name = file.document.file_name+"_"+str(rnd) 118 | times = datetime.now().strftime("%I:%M%p") 119 | dates = datetime.now().strftime("%B %d, %Y") 120 | now = datetime.now() 121 | year = int(now.strftime("%Y")) 122 | month = int(now.strftime("%m")) 123 | day = int(now.strftime("%d")) 124 | h = int(now.strftime("%H")) 125 | m = int(now.strftime("%M")) 126 | s = int(now.strftime("%S")) 127 | 128 | media = check_media(required_file_name) 129 | if not media: 130 | message.reply(invalid_media_type) 131 | return 132 | db.fetchNews(file_name, file_size, file_id, download_id, times, dates, str(uploader), url, year, month, day, h, m, s, 0, media) 133 | logger.warning('You just uploaded an: "%s"', media) 134 | LastReadNewsID = db.checkUserLastNews(chat_id) 135 | TodayFirstNewsID = db.checkTodayFirstNewsID() 136 | news = "No news" 137 | 138 | 139 | tfiles = None 140 | if(TodayFirstNewsID == 0): 141 | news = "Oh i encountered an error while saving." 142 | elif(LastReadNewsID < TodayFirstNewsID): 143 | LastReadNewsID = TodayFirstNewsID 144 | if(TodayFirstNewsID != 0): 145 | news = db.getNews(LastReadNewsID, chat_id) 146 | 147 | message.reply(news) 148 | else: 149 | try: 150 | os.remove(required_file_name) 151 | except: 152 | pass 153 | er = "An error occured while downloading...." 154 | sent.edit(er) 155 | logger.info(er) 156 | 157 | else: 158 | err = "`Your link doesn't look like a downloadable link...... Kindly try again`" 159 | message.reply(str(err), quote=True) 160 | logger.debug(str(err)) 161 | 162 | except: 163 | traceback.print_exc() 164 | -------------------------------------------------------------------------------- /utils/guess.py: -------------------------------------------------------------------------------- 1 | """Guess the MIME type of a file. 2 | This module defines two useful functions: 3 | guess_type(url, strict=True) -- guess the MIME type and encoding of a URL. 4 | guess_extension(type, strict=True) -- guess the extension for a given MIME type. 5 | It also contains the following, for tuning the behavior: 6 | Data: 7 | knownfiles -- list of files to parse 8 | inited -- flag set when init() has been called 9 | suffix_map -- dictionary mapping suffixes to suffixes 10 | encodings_map -- dictionary mapping suffixes to encodings 11 | types_map -- dictionary mapping suffixes to types 12 | Functions: 13 | init([files]) -- parse a list of files, default knownfiles (on Windows, the 14 | default values are taken from the registry) 15 | read_mime_types(file) -- parse one file, return a dictionary or None 16 | """ 17 | 18 | import os 19 | import sys 20 | 21 | 22 | def default_mime_types(): 23 | global suffix_map 24 | global encodings_map 25 | global types_map 26 | global common_types 27 | 28 | suffix_map = { 29 | '.svgz': '. izahzjkghbb n bnbb .gz', 30 | '.tgz': '.tar.gz', 31 | '.taz': '.tar.gz', 32 | '.tz': '.tar.gz', 33 | '.tbz2': '.tar.bz2', 34 | '.txz': '.tar.xz', 35 | } 36 | 37 | encodings_map = { 38 | '.gz': 'gzip', 39 | '.Z': 'compress', 40 | '.bz2': 'bzip2', 41 | '.xz': 'xz', 42 | '.7z': '7z', 43 | } 44 | 45 | # Before adding new types, make sure they are either registered with IANA, 46 | # at http://www.iana.org/assignments/media-types 47 | # or extensions, i.e. using the x- prefix 48 | 49 | # If you add to these, please keep them sorted! 50 | types_map = { 51 | '.a' : 'application/octet-stream', 52 | '.ai' : 'application/postscript', 53 | '.aif' : 'audio/x-aiff', 54 | '.aifc' : 'audio/x-aiff', 55 | '.aiff' : 'audio/x-aiff', 56 | '.apk' : 'application/vnd.android.package-archive', 57 | '.au' : 'audio/basic', 58 | '.avi' : 'video/x-msvideo', 59 | '.bat' : 'text/plain', 60 | '.bcpio' : 'application/x-bcpio', 61 | '.bin' : 'application/octet-stream', 62 | '.bmp' : 'image/bmp', 63 | '.c' : 'text/plain', 64 | '.cdf' : 'application/x-netcdf', 65 | '.cpio' : 'application/x-cpio', 66 | '.csh' : 'application/x-csh', 67 | '.css' : 'text/css', 68 | '.csv' : 'text/csv', 69 | '.dll' : 'application/octet-stream', 70 | '.doc' : 'application/msword', 71 | '.dot' : 'application/msword', 72 | '.dvi' : 'application/x-dvi', 73 | '.eml' : 'message/rfc822', 74 | '.eps' : 'application/postscript', 75 | '.epub' : 'application/epub+zip', 76 | '.etx' : 'text/x-setext', 77 | '.exe' : 'application/octet-stream', 78 | '.gif' : 'image/gif', 79 | '.gtar' : 'application/x-gtar', 80 | '.h' : 'text/plain', 81 | '.hdf' : 'application/x-hdf', 82 | '.htm' : 'text/html', 83 | '.html' : 'text/html', 84 | '.ico' : 'image/vnd.microsoft.icon', 85 | '.ief' : 'image/ief', 86 | '.jpe' : 'image/jpeg', 87 | '.jpeg' : 'image/jpeg', 88 | '.jpg' : 'image/jpeg', 89 | '.js' : 'application/javascript', 90 | '.json' : 'application/json', 91 | '.ksh' : 'text/plain', 92 | '.latex' : 'application/x-latex', 93 | '.m1v' : 'video/mpeg', 94 | '.m3u' : 'application/vnd.apple.mpegurl', 95 | '.m3u8' : 'application/vnd.apple.mpegurl', 96 | '.man' : 'application/x-troff-man', 97 | '.me' : 'application/x-troff-me', 98 | '.mht' : 'message/rfc822', 99 | '.mhtml' : 'message/rfc822', 100 | '.mif' : 'application/x-mif', 101 | '.mjs' : 'application/javascript', 102 | '.mov' : 'video/quicktime', 103 | '.movie' : 'video/x-sgi-movie', 104 | '.mp2' : 'audio/mpeg', 105 | '.mp3' : 'audio/mpeg', 106 | '.mp4' : 'video/mp4', 107 | '.mpa' : 'video/mpeg', 108 | '.mpe' : 'video/mpeg', 109 | '.mpeg' : 'video/mpeg', 110 | '.mpg' : 'video/mpeg', 111 | '.ms' : 'application/x-troff-ms', 112 | '.nc' : 'application/x-netcdf', 113 | '.nws' : 'message/rfc822', 114 | '.o' : 'application/octet-stream', 115 | '.obj' : 'application/octet-stream', 116 | '.oda' : 'application/oda', 117 | '.p12' : 'application/x-pkcs12', 118 | '.p7c' : 'application/pkcs7-mime', 119 | '.pbm' : 'image/x-portable-bitmap', 120 | '.pdf' : 'application/pdf', 121 | '.pfx' : 'application/x-pkcs12', 122 | '.pgm' : 'image/x-portable-graymap', 123 | '.pl' : 'text/plain', 124 | '.png' : 'image/png', 125 | '.pnm' : 'image/x-portable-anymap', 126 | '.pot' : 'application/vnd.ms-powerpoint', 127 | '.ppa' : 'application/vnd.ms-powerpoint', 128 | '.ppm' : 'image/x-portable-pixmap', 129 | '.pps' : 'application/vnd.ms-powerpoint', 130 | '.ppt' : 'application/vnd.ms-powerpoint', 131 | '.ps' : 'application/postscript', 132 | '.pwz' : 'application/vnd.ms-powerpoint', 133 | '.py' : 'text/x-python', 134 | '.pyc' : 'application/x-python-code', 135 | '.pyo' : 'application/x-python-code', 136 | '.qt' : 'video/quicktime', 137 | '.ra' : 'audio/x-pn-realaudio', 138 | '.ram' : 'application/x-pn-realaudio', 139 | '.ras' : 'image/x-cmu-raster', 140 | '.rdf' : 'application/xml', 141 | '.rgb' : 'image/x-rgb', 142 | '.roff' : 'application/x-troff', 143 | '.rtx' : 'text/richtext', 144 | '.sgm' : 'text/x-sgml', 145 | '.sgml' : 'text/x-sgml', 146 | '.sh' : 'application/x-sh', 147 | '.shar' : 'application/x-shar', 148 | '.snd' : 'audio/basic', 149 | '.sqlite3': 'application/x-sqlite3', 150 | '.so' : 'application/octet-stream', 151 | '.src' : 'application/x-wais-source', 152 | '.sv4cpio': 'application/x-sv4cpio', 153 | '.sv4crc' : 'application/x-sv4crc', 154 | '.svg' : 'image/svg+xml', 155 | '.swf' : 'application/x-shockwave-flash', 156 | '.t' : 'application/x-troff', 157 | '.tar' : 'application/x-tar', 158 | '.tcl' : 'application/x-tcl', 159 | '.tex' : 'application/x-tex', 160 | '.texi' : 'application/x-texinfo', 161 | '.texinfo': 'application/x-texinfo', 162 | '.tif' : 'image/tiff', 163 | '.tiff' : 'image/tiff', 164 | '.tr' : 'application/x-troff', 165 | '.tsv' : 'text/tab-separated-values', 166 | '.txt' : 'text/plain', 167 | '.ustar' : 'application/x-ustar', 168 | '.vcf' : 'text/x-vcard', 169 | '.wasm' : 'application/wasm', 170 | '.wav' : 'audio/x-wav', 171 | '.webm' : 'video/webm', 172 | '.wiz' : 'application/msword', 173 | '.wsdl' : 'application/xml', 174 | '.xbm' : 'image/x-xbitmap', 175 | '.xlb' : 'application/vnd.ms-excel', 176 | '.xls' : 'application/vnd.ms-excel', 177 | '.xml' : 'text/xml', 178 | '.xpdl' : 'application/xml', 179 | '.xpm' : 'image/x-xpixmap', 180 | '.xsl' : 'application/xml', 181 | '.xwd' : 'image/x-xwindowdump', 182 | '.zip' : 'application/zip', 183 | } 184 | 185 | # These are non-standard types, commonly found in the wild. They will 186 | # only match if strict=0 flag is given to the API methods. 187 | 188 | # Please sort these too 189 | common_types = { 190 | '.jpg' : 'image/jpg', 191 | '.jpeg' : 'image/jpeg', 192 | '.jpe' : 'image/jpeg', 193 | '.jpx' : 'image/jpx', 194 | '.mid' : 'audio/midi', 195 | '.midi': 'audio/midi', 196 | '.pct' : 'image/pict', 197 | '.pic' : 'image/pict', 198 | '.pict': 'image/pict', 199 | '.rtf' : 'application/rtf', 200 | '.xul' : 'text/xul' 201 | } 202 | 203 | default_mime_types() 204 | -------------------------------------------------------------------------------- /utils/menus.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from pyrogram import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove, ForceReply 3 | 4 | MAIN_MENU = [ 5 | [ 6 | InlineKeyboardButton('📁 File Manager', callback_data=b'files'), 7 | InlineKeyboardButton('⚙️ Settings', callback_data=b'settings'), 8 | ],[ 9 | InlineKeyboardButton('📝 Faqs', callback_data=b'faqs') 10 | ], 11 | ] 12 | 13 | SETTINGS_MENU = [ 14 | [ 15 | InlineKeyboardButton('💡 About', callback_data=b'lang'), 16 | InlineKeyboardButton('🛂 Preferences', callback_data=b'prefe'), 17 | ],[ 18 | InlineKeyboardButton('🧰 Upgrade Plan', callback_data=b'plan'), 19 | InlineKeyboardButton('👤 Contribute', callback_data=b'plan') 20 | ],[ 21 | InlineKeyboardButton('🔙 Back', callback_data=b'setupdate') 22 | ], 23 | ] 24 | 25 | FILES_MENU = [ 26 | [ 27 | InlineKeyboardButton('⬅️ Previous', callback_data=b'files:previous'), 28 | InlineKeyboardButton('➡️ Next', callback_data=b'files:next'), 29 | ], 30 | [ 31 | InlineKeyboardButton('🔙 Back', callback_data=b'main'), 32 | ], 33 | ] 34 | 35 | def doc_keyboard(id, admin, confirmed, ids, chat_id, private, auth): 36 | data = list() 37 | data.append('cnf=' + str(int(confirmed))) 38 | data.append('auth=' + '='.join(str(da) for da in auth)) 39 | data.append('hide=' + str(int(ids))) 40 | data.append('prv=' + str(int(private))) 41 | data.append('owner=' + str(int(admin))) 42 | data.append('qry=' + str(id)) 43 | data = '%'.join(data) 44 | logger.warning(data) 45 | kb = [[ 46 | InlineKeyboardButton( 47 | text=('💾' + ' Save this file') if not confirmed else ('🗑' + ' Remove from Storage'), 48 | callback_data=b'act=copy%' + data.encode('UTF-8') 49 | ) 50 | ], [ 51 | InlineKeyboardButton( 52 | text=('🗳' + ' View all Saved Files') if not confirmed else ('📦' + ' Access Your File Storage'), 53 | callback_data=b'act=first%' + data.encode('UTF-8') 54 | ) 55 | ], list()] 56 | if (private == 1): 57 | kb[1].append( 58 | InlineKeyboardButton( 59 | text= ('🔐' + ' Make this file private') if not admin else ('🔓' + ' Unlock this file '), 60 | callback_data=b'act=auth%' + data.encode('UTF-8') 61 | ) 62 | ) 63 | return kb 64 | 65 | 66 | 67 | 68 | def reg_keyboard(id, admin, confirmed, ids, chat_id, private, auth): 69 | data = list() 70 | data.append('cnf=' + str(int(confirmed))) 71 | data.append('auth=' + '='.join(str(da) for da in auth)) 72 | data.append('hide=' + str(int(ids))) 73 | data.append('prv=' + str(int(private))) 74 | data.append('owner=' + str(int(admin))) 75 | data.append('qry=' + str(id)) 76 | data = '%'.join(data) 77 | logger.warning(data) 78 | 79 | if (private == 1): 80 | kb = [[ 81 | InlineKeyboardButton( 82 | text=('💾' + ' Save this file') if not confirmed else ('🗑' + ' Remove from Storage'), 83 | callback_data=b'act=copy%' + data.encode('UTF-8') 84 | ) 85 | ], [ 86 | 87 | InlineKeyboardButton( 88 | text= ('🔐' + ' Make this file private') if not admin else ('🔓' + ' Unlock this file '), 89 | callback_data=b'act=auth%' + data.encode('UTF-8') 90 | ) 91 | ], list()] 92 | kb[1].append( 93 | InlineKeyboardButton( 94 | text='📥 Download', 95 | callback_data=b'act=dl%' + data.encode('UTF-8') 96 | ) 97 | ) 98 | elif (private == 0): 99 | kb = [[ 100 | 101 | InlineKeyboardButton( 102 | text='📥 Download', 103 | callback_data=b'act=dl%' + data.encode('UTF-8') 104 | ) 105 | ]] 106 | 107 | return kb 108 | 109 | def search_keyboard(query, offset, rows, last, show_download): 110 | data = list() 111 | 112 | data.append('qry=' + str(query)) 113 | data.append('off=' + str(int(offset))) 114 | data.append('next=' + str(int(rows))) 115 | data.append('dl=' + str(int(show_download))) 116 | data = '%'.join(data) 117 | #logger.warning(data) 118 | last = last + offset + 5 119 | if not last > rows: 120 | new_offset = last 121 | elif offset <= 0: 122 | offset = 0 123 | else: 124 | new_offset = rows - 1 125 | kb = [] 126 | if offset == 0 and not rows < offset: 127 | kb.append(( 128 | InlineKeyboardButton( 129 | text='⬇️' + ' Goto Last Page', 130 | callback_data=b'act=last%' + data.encode('UTF-8')), 131 | 132 | InlineKeyboardButton( 133 | text='Older ➡️', 134 | callback_data=b'act=old%' + data.encode('UTF-8') 135 | ))) 136 | elif (offset == new_offset): 137 | kb.append(( 138 | InlineKeyboardButton( 139 | text='⬅️ Newer', 140 | callback_data=b'act=new%' + data.encode('UTF-8') 141 | ), 142 | InlineKeyboardButton( 143 | text='⬆️' + ' Goto First Page', 144 | callback_data=b'act=first%' + data.encode('UTF-8') 145 | ) 146 | )) 147 | 148 | 149 | elif offset > 0 and not rows < 0 and not offset < 0: 150 | kb.append(( 151 | InlineKeyboardButton( 152 | text='⬅️ Newer', 153 | callback_data=b'act=new%' + data.encode('UTF-8') 154 | ), 155 | InlineKeyboardButton( 156 | text='Older ➡️', 157 | callback_data=b'act=old%' + data.encode('UTF-8') 158 | ))) 159 | return kb 160 | 161 | def private_keyboard(id, admin, confirmed, ids, chat_id): 162 | data = list() 163 | data.append('cnf=' + str(int(confirmed))) 164 | data.append('hide=' + str(int(ids))) 165 | data.append('qry=' + str(id)) 166 | data = '%'.join(data) 167 | logger.warning(data) 168 | kb = [[ 169 | InlineKeyboardButton( 170 | text=('🗳' + ' View all Saved Files') if not confirmed else ('📦' + ' Access Your Storage'), 171 | callback_data=b'act=first%' + data.encode('UTF-8') 172 | ) 173 | ]] 174 | return kb 175 | 176 | 177 | 178 | def dl_keyboard(id, admin, confirmed, ids, chat_id): 179 | data = list() 180 | data.append('cnf=' + str(int(confirmed))) 181 | data.append('hide=' + str(int(ids))) 182 | data.append('qry=' + str(id)) 183 | data = '%'.join(data) 184 | logger.warning(data) 185 | kb = [[ 186 | InlineKeyboardButton( 187 | text=('💾' + ' Save this file') if not confirmed else ('🗑' + ' Remove from Storage'), 188 | callback_data=b'act=copy%' + data.encode('UTF-8') 189 | ) 190 | ], [ 191 | InlineKeyboardButton( 192 | text=('🗳' + ' View all Saved Files') if not confirmed else ('📦' + ' Access Your File Storage'), 193 | callback_data=b'act=first%' + data.encode('UTF-8') 194 | ) 195 | ]] 196 | return kb 197 | 198 | 199 | def regs_keyboard(id, admin, confirmed, ids, chat_id): 200 | data = list() 201 | data.append('cnf=' + str(int(confirmed))) 202 | data.append('hide=' + str(int(ids))) 203 | data.append('qry=' + str(id)) 204 | data = '%'.join(data) 205 | logger.warning(data) 206 | kb = [[ 207 | InlineKeyboardButton( 208 | text=('🗳' + ' View all Saved Files') if not confirmed else ('📦' + ' Access Your Storage'), 209 | callback_data=b'act=first%' + data.encode('UTF-8') 210 | ) 211 | ]] 212 | return kb 213 | 214 | 215 | def copy_keyboard(id, admin, confirmed, ids, chat_id, private, auth): 216 | data = list() 217 | data.append('cnf=' + str(int(confirmed))) 218 | data.append('auth=' + '='.join(str(da) for da in auth)) 219 | data.append('hide=' + str(int(ids))) 220 | data.append('prv=' + str(int(private))) 221 | data.append('qry=' + str(id)) 222 | data = '%'.join(data) 223 | logger.warning(data) 224 | kb = [[ 225 | InlineKeyboardButton( text=('💾' + ' Save this file') if not confirmed else ('🗑' + ' Remove from Storage'), callback_data=b'act=copy%' + data.encode('UTF-8') ), 226 | 227 | InlineKeyboardButton( 228 | text=('🗳' + ' View all Saved Files') if not confirmed else ('📦' + ' Access Your File Storage'), callback_data=b'act=first%' + data.encode('UTF-8')) 229 | ], 230 | [InlineKeyboardButton( 231 | text='📥 Download', 232 | callback_data=b'act=dl%' + data.encode('UTF-8') 233 | )], list()] 234 | 235 | if (private == 1): 236 | kb[1].append( 237 | InlineKeyboardButton( 238 | text=('🔓' + ' Unlock this file ') if not admin else ('🔐' + ' Make this file private'), 239 | callback_data=b'act=auth%' + data.encode('UTF-8') 240 | ) 241 | ) 242 | return kb 243 | 244 | -------------------------------------------------------------------------------- /utils/handlers.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | import mimetypes 3 | import mimetypes, magic, math 4 | from utils.guess import * 5 | import time 6 | download_path = "{}/.data/".format(os.getcwd()) 7 | if not os.path.isdir(download_path): 8 | os.makedirs(download_path) 9 | options={} 10 | base_headers = { 11 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.5 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.5', 12 | 'Accept-Encoding': 'gzip, deflate, sdch', 13 | 'Accept-Language': 'zh-CN,zh;q=0.8' 14 | } 15 | headers = dict(base_headers, **options) 16 | known_sessions_file = os.path.join(os.path.dirname(__file__), 'known_sessions') 17 | def timedate(dat): 18 | import timeago, datetime 19 | now = datetime.datetime.now() + datetime.timedelta(seconds = 1) 20 | date = datetime.datetime.now() 21 | return timeago.format(dat, now) 22 | 23 | 24 | 25 | def read_known_sessions(): 26 | if not os.path.isfile(known_sessions_file): 27 | return set() 28 | with open(known_sessions_file, 'rb') as f: 29 | return set(int(s.strip()) for s in f.readlines()) 30 | 31 | def write_known_sessions(data): 32 | with open(known_sessions_file, 'wb') as f: 33 | f.write('\n'.join(str(s) for s in sorted(data))) 34 | def get_extension(media): 35 | """Gets the corresponding extension for any Telegram media""" 36 | 37 | # Photos are always compressed as .jpg by Telegram 38 | if isinstance(media, (UserProfilePhoto, ChatPhoto, MessageMediaPhoto)): 39 | return '.jpg' 40 | 41 | # Documents will come with a mime type 42 | if isinstance(media, MessageMediaDocument): 43 | if isinstance(media.document, Document): 44 | if media.document.mime_type == 'application/octet-stream': 45 | # Octet stream are just bytes, which have no default extension 46 | return '' 47 | else: 48 | extension = guess_extension(media.document.mime_type) 49 | return extension if extension else '' 50 | 51 | return '' 52 | def check_media(chk): 53 | extensionsToCheck = ['.exe', '.msi', '.Exe','.Msi', '.mp3', '.AAC','.M4A', '.doc', '.docx','.txt','.pdf','.epub','.bat','.py','.js','.html','.css','.go','.xlb','.xls', '.zip', '.rar','.7z','.gz', '.avi', '.mkv','.webm', '.mp4', '.m1v', '.movie', '.mpeg', '.mov', '.png'] 54 | hou = [extension for extension in extensionsToCheck if(extension in chk.lower())] 55 | media = "" 56 | if hou is not None: 57 | if chk.lower().endswith(('.apk', '.xapk', '.jar', '.jav')): 58 | media = "Apps" 59 | elif chk.lower().endswith(('.exe', '.msi')): 60 | media = "Software" 61 | elif chk.lower().endswith(('.doc', '.docx','.txt','.pdf','.epub','.bat','.py','.js','.html','.css','.go','.xlb','.xls')): 62 | media = "Documents" 63 | elif chk.lower().endswith(('.zip', '.rar','.7z','.gz','.bin')): 64 | media = "Archives" 65 | else: 66 | media = "Misc" 67 | return media 68 | 69 | else: 70 | return False 71 | from base64 import b64decode 72 | from struct import unpack 73 | 74 | def parse_inline_message_id(inline_message_id): 75 | inline_message_id += "=" * ((4 - len(inline_message_id) % 4) % 4) 76 | dc_id, _id, access_hash = unpack(" str: 81 | """ 82 | Adjust the size from bits to the right measure. 83 | 84 | b (``int``): Number of bits. 85 | 86 | 87 | SUCCESS Returns the adjusted measure (``str``). 88 | """ 89 | if human_readable: 90 | B = float(b / 8) 91 | KB = float(1024) 92 | MB = float(pow(KB, 2)) 93 | GB = float(pow(KB, 3)) 94 | TB = float(pow(KB, 4)) 95 | 96 | if B < KB: 97 | return "{0} B".format(B) 98 | elif KB <= B < MB: 99 | return "{0:.2f} KB".format(B/KB) 100 | elif MB <= B < GB: 101 | return "{0:.2f} MB".format(B/MB) 102 | elif GB <= B < TB: 103 | return "{0:.2f} GB".format(B/GB) 104 | elif TB <= B: 105 | return "{0:.2f} TB".format(B/TB) 106 | else: 107 | B, b = divmod(int(b), 8) 108 | KB, B = divmod(B, 1024) 109 | MB, KB = divmod(KB, 1024) 110 | GB, MB = divmod(MB, 1024) 111 | TB, GB = divmod(GB, 1024) 112 | tmp = ((str(TB) + "TB, ") if TB else "") + \ 113 | ((str(GB) + "GB, ") if GB else "") + \ 114 | ((str(MB) + "MB, ") if MB else "") + \ 115 | ((str(KB) + "KB, ") if KB else "") + \ 116 | ((str(B) + "B, ") if B else "") + \ 117 | ((str(b) + "b, ") if b else "") 118 | return tmp[:-2] 119 | 120 | 121 | def TimeFormatter(milliseconds: int) -> str: 122 | """ 123 | Adjust the time from milliseconds to the right measure. 124 | 125 | milliseconds (``int``): Number of milliseconds. 126 | 127 | 128 | SUCCESS Returns the adjusted measure (``str``). 129 | """ 130 | seconds, milliseconds = divmod(int(milliseconds), 1000) 131 | minutes, seconds = divmod(seconds, 60) 132 | hours, minutes = divmod(minutes, 60) 133 | days, hours = divmod(hours, 24) 134 | tmp = ((str(days) + "d, ") if days else "") + \ 135 | ((str(hours) + "h, ") if hours else "") + \ 136 | ((str(minutes) + "m, ") if minutes else "") + \ 137 | ((str(seconds) + "s, ") if seconds else "") + \ 138 | ((str(milliseconds) + "ms, ") if milliseconds else "") 139 | return tmp[:-2] 140 | 141 | 142 | 143 | def DFromUToTelegramProgress(client, 144 | current, 145 | total, 146 | msg, 147 | chat_id, 148 | start, text) -> None: 149 | 150 | # 1048576 is 1 MB in bytes 151 | now = time.time() 152 | diff = now - start 153 | if round(diff % 4.00) == 0 or current == total: 154 | percentage = current * 100 / total 155 | speed = current / diff 156 | elapsed_time = round(diff) * 1000 157 | time_to_completion = round((total - current) / speed) * 1000 158 | estimated_total_time = elapsed_time + time_to_completion 159 | 160 | elapsed_time = TimeFormatter(milliseconds=elapsed_time) 161 | estimated_total_time = TimeFormatter(milliseconds=estimated_total_time) 162 | # 0% = [░░░░░░░░░░░░░░░░░░░░] 163 | # 100% = [████████████████████] 164 | progress = "[{0}{1}] {2}%\n".format(''.join(["█" for i in range(math.floor(percentage / 5))]), 165 | ''.join( 166 | ["░" for i in range(20 - math.floor(percentage / 5))]), 167 | round(percentage, 2)) 168 | tmp = progress + "\n**Running:** {0}/{1}\n\n**Speed:** {2}/s \n\n**Estimated Time:** {3}/{4}\n".format(SizeFormatter(b=current * 8, 169 | human_readable=True), 170 | SizeFormatter(b=total * 8, 171 | human_readable=True), 172 | SizeFormatter(b=speed * 8, 173 | human_readable=True), 174 | elapsed_time if elapsed_time != '' else "0 s", 175 | estimated_total_time if estimated_total_time != '' else "0 s") 176 | 177 | msg.edit(text=text + tmp) 178 | 179 | 180 | 181 | 182 | common_words = frozenset(("if", "but", "and", "the", "when", "use", "to", "for")) 183 | title = "When to use Python for web applications" 184 | title_words = set(title.lower().split()) 185 | keywords = title_words.difference(common_words) 186 | 187 | 188 | 189 | 190 | def is_downloadable(url): 191 | """ 192 | Does the url contain a downloadable resource 193 | """ 194 | h = requests.head(url, allow_redirects=True) 195 | header = h.headers 196 | content_type = header.get('content-type') 197 | if 'text' in content_type.lower(): 198 | return False 199 | if 'html' in content_type.lower(): 200 | return False 201 | return True 202 | 203 | 204 | def dict_factory(cursor, row): 205 | d = {} 206 | for idx, col in enumerate(cursor.description): 207 | d[col[0]] = row[idx] 208 | return d 209 | 210 | 211 | def dynamic_data(data): 212 | return Filters.create( 213 | name="DynamicData", 214 | func=lambda filter, callback_query: filter.data == callback_query.data, 215 | data=data # "data" kwarg is accessed with "filter.data" 216 | ) 217 | 218 | def fileExt(url): 219 | """ 220 | Check if file extention exist then 221 | 222 | """ 223 | # compile regular expressions 224 | reQuery = re.compile(r'\?.*$', re.IGNORECASE) 225 | rePort = re.compile(r':[0-9]+', re.IGNORECASE) 226 | reExt = re.compile(r'(\.[A-Za-z0-9]+$)', re.IGNORECASE) 227 | 228 | # remove query string 229 | url = reQuery.sub("", url) 230 | 231 | # remove port 232 | url = rePort.sub("", url) 233 | 234 | # extract extension 235 | matches = reExt.search(url) 236 | if None != matches: 237 | return matches.group(1) 238 | return None 239 | 240 | def get_filename(url): 241 | """ 242 | Get an authentique filename from content-dispostion 243 | """ 244 | options={} 245 | base_headers = { 246 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.5 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.5', 247 | 'Accept-Encoding': 'gzip, deflate, sdch', 248 | 'Accept-Language': 'zh-CN,zh;q=0.8' 249 | } 250 | headers = dict(base_headers, **options) 251 | result = requests.get(url, allow_redirects=True, stream=True, headers=headers) 252 | fname = None 253 | cd = result.headers.get("content-disposition") 254 | if cd: 255 | value, params = cgi.parse_header(cd) 256 | fname = params.get("filename") 257 | content_type = "" 258 | filenams = "" 259 | su = [] 260 | code = result.status_code 261 | headers = result.headers 262 | content_type = headers['content-type'] 263 | if 'text' in content_type.lower(): 264 | return False 265 | if 'html' in content_type.lower(): 266 | return False 267 | else: 268 | pass 269 | if code < 400: 270 | token = '[-!#-\'*+.\dA-Z^-z|~]+' 271 | qdtext='[]-~\t !#-[]' 272 | mimeCharset='[-!#-&+\dA-Z^-z]+' 273 | language='(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}(?:-[A-Za-z]{3}){,2})?|[A-Za-z]{4,8})(?:-[A-Za-z]{4})?(?:-(?:[A-Za-z]{2}|\d{3}))(?:-(?:[\dA-Za-z]{5,8}|\d[\dA-Za-z]{3}))*(?:-[\dA-WY-Za-wy-z](?:-[\dA-Za-z]{2,8})+)*(?:-[Xx](?:-[\dA-Za-z]{1,8})+)?|[Xx](?:-[\dA-Za-z]{1,8})+|[Ee][Nn]-[Gg][Bb]-[Oo][Ee][Dd]|[Ii]-[Aa][Mm][Ii]|[Ii]-[Bb][Nn][Nn]|[Ii]-[Dd][Ee][Ff][Aa][Uu][Ll][Tt]|[Ii]-[Ee][Nn][Oo][Cc][Hh][Ii][Aa][Nn]|[Ii]-[Hh][Aa][Kk]|[Ii]-[Kk][Ll][Ii][Nn][Gg][Oo][Nn]|[Ii]-[Ll][Uu][Xx]|[Ii]-[Mm][Ii][Nn][Gg][Oo]|[Ii]-[Nn][Aa][Vv][Aa][Jj][Oo]|[Ii]-[Pp][Ww][Nn]|[Ii]-[Tt][Aa][Oo]|[Ii]-[Tt][Aa][Yy]|[Ii]-[Tt][Ss][Uu]|[Ss][Gg][Nn]-[Bb][Ee]-[Ff][Rr]|[Ss][Gg][Nn]-[Bb][Ee]-[Nn][Ll]|[Ss][Gg][Nn]-[Cc][Hh]-[Dd][Ee]' 274 | valueChars = '(?:%[\dA-F][\dA-F]|[-!#$&+.\dA-Z^-z|~])*' 275 | dispositionParm = '[Ff][Ii][Ll][Ee][Nn][Aa][Mm][Ee]\s*=\s*(?:({token})|"((?:{qdtext}|\\\\[\t !-~])*)")|[Ff][Ii][Ll][Ee][Nn][Aa][Mm][Ee]\*\s*=\s*({mimeCharset})\'(?:{language})?\'({valueChars})|{token}\s*=\s*(?:{token}|"(?:{qdtext}|\\\\[\t !-~])*")|{token}\*\s*=\s*{mimeCharset}\'(?:{language})?\'{valueChars}'.format(**locals()) 276 | 277 | try: 278 | m = re.match('(?:{token}\s*;\s*)?(?:{dispositionParm})(?:\s*;\s*(?:{dispositionParm}))*|{token}'.format(**locals()), result.headers['Content-Disposition']) 279 | 280 | except KeyError: 281 | name = path.basename(unquote(urlparse(url).path)) 282 | 283 | else: 284 | if not m: 285 | name = path.basename(unquote(urlparse(url).path)) 286 | 287 | # Many user agent implementations predating this specification do not 288 | # understand the "filename*" parameter. Therefore, when both "filename" 289 | # and "filename*" are present in a single header field value, recipients 290 | # SHOULD pick "filename*" and ignore "filename" 291 | 292 | elif m.group(8) is not None: 293 | name = urllib.unquote(m.group(8)).decode(m.group(7)) 294 | 295 | elif m.group(4) is not None: 296 | name = urllib.unquote(m.group(4)).decode(m.group(3)) 297 | 298 | elif m.group(6) is not None: 299 | name = re.sub('\\\\(.)', '\1', m.group(6)) 300 | 301 | elif m.group(5) is not None: 302 | name = m.group(5) 303 | 304 | elif m.group(2) is not None: 305 | name = re.sub('\\\\(.)', '\1', m.group(2)) 306 | 307 | else: 308 | name = m.group(1) 309 | 310 | # Recipients MUST NOT be able to write into any location other than one to 311 | # which they are specifically entitled 312 | 313 | if name: 314 | name = path.basename(name) 315 | 316 | else: 317 | name = path.basename(unquote(urlparse(url).path)) 318 | 319 | name = unquote(name).strip('\n').strip('\*').replace('UTF-8', "").strip('\=').replace('\"','').replace('\'','').replace('?','').replace(" ", "_") 320 | 321 | filenam, ext = splitext(basename(name)) 322 | if ext: 323 | ext = fileExt(url) 324 | if ext == None: 325 | logger.warning("No filetype could be determined for '%s', skipping.", 326 | filenam 327 | ) 328 | if ext in common_types.keys() or ext in types_map.keys(): 329 | ext = '{}'.format(ext) 330 | mime_typ = '{}'.format(types_map[ext]) 331 | filenams = filenam+ext 332 | 333 | 334 | elif content_type == 'image/jpeg' or content_type == 'image/jpg' or content_type == 'image/jpe': 335 | ext = '.jpeg' 336 | 337 | elif content_type == 'image/x-icon' or content_type == 'image/vnd.microsoft.icon': 338 | ext = '.ico' 339 | 340 | elif content_type == 'application/x-7z-compressed': 341 | ext = '.7z' 342 | elif content_type == 'image/png': 343 | ext = '.png' 344 | 345 | elif None == ext: 346 | ext = mimetypes.guess_extension(content_type) 347 | logger.warning("No extension for '%s', guessed '%s'.", 348 | filenam, ext) 349 | 350 | ent = ext 351 | if ent in common_types or ent in types_map: 352 | print ('File Extenstion: {} has MIME Type: {}.'.format(ent, types_map[ent])) 353 | for k, v in types_map.items(): 354 | if content_type in v: 355 | su.append(k) 356 | 357 | return[filenams,filenam, content_type, su, fname] 358 | 359 | def generate_uuid(): 360 | random_string = '' 361 | random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 362 | uuid_format = [8] 363 | for n in uuid_format: 364 | for i in range(0,n): 365 | random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)]) 366 | if n != 8: 367 | random_string += '-' 368 | return random_string.strip('\n').replace('\"','').replace('\'','').replace('?','').replace(" ", "_") 369 | 370 | 371 | 372 | 373 | 374 | def human_readable_bytes(bytes): 375 | KB = 1024 376 | MB = 1024 * 1024 377 | GB = MB * 1024 378 | 379 | if bytes >= KB and bytes < MB: 380 | result = bytes / KB 381 | converted = 'KB' 382 | elif bytes >= MB and bytes < GB: 383 | result = bytes / MB 384 | converted = 'MB' 385 | elif bytes >= GB: 386 | result = bytes / GB 387 | converted = 'GB' 388 | else: 389 | result = bytes 390 | converted = 'byte' 391 | 392 | result = "%.1f" % result 393 | results = ( 394 | str(result) + ' ' + converted, 395 | result, 396 | converted 397 | ) 398 | 399 | return results 400 | 401 | 402 | def pretty_size(sizes): 403 | units = ['B', 'KB', 'MB', 'GB'] 404 | unit = 0 405 | while sizes >= 1024: 406 | sizes /= 1024 407 | unit += 1 408 | return '%0.2f %s' % (sizes, units[unit]) 409 | def dosomething(buf): 410 | """Do something with the content of a file""" 411 | sleep(0.01) 412 | pass 413 | from requests.exceptions import RequestException 414 | 415 | 416 | 417 | 418 | def get_filename_from_cd(cd): 419 | """ 420 | Get filename from content-disposition 421 | """ 422 | if not cd: 423 | return None 424 | fname = re.findall('filename=(.+)', cd) 425 | if len(fname) == 0: 426 | return None 427 | return fname[0] 428 | 429 | 430 | 431 | nowq = datetime.now() 432 | current_date_time = str(nowq).split(" ")[0] + " " + str(nowq.hour) + ":" + str(nowq.minute) + ":" + str(nowq.second) 433 | 434 | def DownL(url): 435 | fname, ext = get_filename(url) 436 | file_name = fname+ext 437 | r = requests.get(url, stream=True, allow_redirects=True, headers=headers) 438 | with open(file_name, 'wb') as file: 439 | total_length = r.headers.get('content-length') 440 | if total_length is None: # no content length header 441 | file.write(r.content) 442 | else: 443 | dl = 0 444 | total_length = int(total_length) 445 | for chunk in progress.bar(r.iter_content(chunk_size=8192*1024), expected_size=(total_length / 1024) + 1): 446 | if chunk: 447 | dl += len(chunk) 448 | done = int(100 * dl / total_length) 449 | file.write(chunk) 450 | file.flush() 451 | os.fsync(file.fileno()) 452 | 453 | 454 | 455 | 456 | def DownLoadFile(url, file_name, fnames, client, message_id, chat_id): 457 | r = requests.get(url, stream=True, allow_redirects=True, headers=headers) 458 | File_name = file_name 459 | with open(download_path+file_name, 'wb') as file: 460 | total_length = int(r.headers.get('content-length', 0)) or None 461 | downloaded_size = 0 462 | chunk_size=8192*1024 463 | if total_length is None: # no content length header 464 | file.write(r.content) 465 | else: 466 | start = time.time() 467 | dl = 0 468 | total_length = int(total_length) 469 | for chunk in progress.bar(r.iter_content(chunk_size=chunk_size), expected_size=(total_length / 1024) + 1): 470 | if chunk: 471 | dl += len(chunk) 472 | file.write(chunk) 473 | done = int(100 * dl / total_length) 474 | DFromUToTelegramProgress(client, dl, total_length, message_id, chat_id, start, "**📥 Downloading:**") 475 | downloaded_size += chunk_size 476 | file.flush() 477 | os.fsync(file.fileno()) 478 | 479 | return file_name 480 | 481 | 482 | -------------------------------------------------------------------------------- /utils/dbmanager.py: -------------------------------------------------------------------------------- 1 | import time, datetime, os, re, sys, sqlite3, json, io 2 | 3 | from datetime import datetime 4 | 5 | from requests import get 6 | import sqlite3 as lite 7 | 8 | from datetime import date, datetime 9 | def dict_factory(cursor, row): 10 | d = {} 11 | for idx, col in enumerate(cursor.description): 12 | d[col[0]] = row[idx] 13 | return d 14 | """ 15 | with sqlite3.connect('inshorts.db', check_same_thread=False) as conn: 16 | cur = conn.cursor() 17 | cursor = conn.execute("DELETE FROM files WHERE Media = ?", ("Music"))""" 18 | 19 | def addtoDb(fn, fs, fid, dlid, times, dates, user, link, year, month, day, h, m, s, priv, media): 20 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 21 | cur = conn.cursor() 22 | title = fn 23 | content = fid 24 | fsize = fs 25 | downloadid = dlid 26 | count = 0 27 | cur.execute('''SELECT Fname FROM files WHERE Fname = ? OR FileId = ?''', (title, content)) 28 | row = cur.fetchone() 29 | if row is None: 30 | cur.execute('''INSERT INTO files (Fname, FileId, Size, Date, Time, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds, Private, Media) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )''', (title, content, fsize, dates, times, downloadid, user, link, year, month, day, h, m, s, priv, media )) 31 | count += 1 32 | conn.commit() 33 | 34 | print ("Total news written to database : ", count) 35 | 36 | 37 | def vfileid(fid): 38 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 39 | cur = conn.cursor() 40 | likeDate = "%" + fid + "%" 41 | cur.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 42 | row = cur.fetchone() 43 | if row is None: 44 | news = 0 45 | else: 46 | news = row[0], row[2], row[3], row[1], row[4], row[5], row[6] 47 | 48 | return news 49 | def doc(fid): 50 | 51 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 52 | c = conn.cursor() 53 | likeDate = "%" + fid + "%" 54 | c.execute("SELECT Fname, DownloadId FROM files WHERE Fname LIKE ? ORDER BY ID DESC LIMIT 1", (likeDate, )) 55 | row = c.fetchone() 56 | if row is None: 57 | news = 0 58 | else: 59 | news = row[1] 60 | return news 61 | 62 | 63 | def cdate(fid): 64 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 65 | c = conn.cursor() 66 | likeDate = "%" + fid + "%" 67 | c.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 68 | row = c.fetchone() 69 | if row is None: 70 | news = 0 71 | else: 72 | news = row[9], row[10], row[11], row[12], row[12], row[13] 73 | 74 | return news 75 | 76 | def ufil(fid, user): 77 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 78 | cur = conn.cursor() 79 | likeDate = "%" + fid + "%" 80 | cur.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds FROM files WHERE User = ? AND DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (user, likeDate, )) 81 | row = cur.fetchone() 82 | if row is None: 83 | news = 0 84 | else: 85 | news = row[7] 86 | 87 | return news 88 | 89 | def getuser(fid, owner): 90 | conn = sqlite3.connect('inshorts.db', check_same_thread=False) 91 | c = conn.cursor() 92 | likeDate = "%" + fid + "%" 93 | c.execute('''SELECT DISTINCT User FROM files WHERE User = ? AND Private = 1 AND DownloadId LIKE ? limit 1''', (owner, likeDate, )) 94 | user = c.fetchone() 95 | if user is not None: 96 | return user[0] 97 | else: 98 | return 0 99 | 100 | 101 | class DBHelper: 102 | def __init__(self, dbname="inshorts.db"): 103 | self.dbname = dbname 104 | self.conn = sqlite3.connect(dbname, check_same_thread=False) 105 | self.c = self.conn.cursor() 106 | self.setup() 107 | 108 | 109 | def __enter__(self): 110 | 111 | return self 112 | 113 | def setup(self): 114 | self.conn.text_factory = str 115 | self.c.executescript('''CREATE TABLE IF NOT EXISTS Users 116 | ( 117 | id INTEGER NOT NULL PRIMARY KEY UNIQUE, 118 | ChatID INTEGER, 119 | LastNewsID INTEGER, 120 | UserID TEXT);''' 121 | ) 122 | #self.c.executescript('''DROP TABLE IF EXISTS files;''') 123 | 124 | self.c.executescript('''CREATE TABLE IF NOT EXISTS files 125 | ( 126 | ID INTEGER NOT NULL PRIMARY KEY UNIQUE, 127 | Media TEXT DEFAULT "Files", 128 | Fname TEXT COLLATE NOCASE, 129 | Size TEXT, 130 | FileId TEXT, 131 | Date TEXT, 132 | Time TEXT, 133 | DownloadId TEXT COLLATE NOCASE, 134 | Link TEXT, 135 | User TEXT, 136 | Private INTEGER, 137 | Year INTEGER, 138 | Month INTEGER, 139 | Day INTEGER, 140 | Hour INTEGER, 141 | Minute INTEGER, 142 | Seconds INTEGER);''' 143 | ) 144 | 145 | self.conn.commit() 146 | 147 | def checkifexist(self, item_text, owner): 148 | likeDate = "%" + str(item_text) + "%" 149 | self.c.execute("SELECT DownloadId, User FROM files WHERE User= (?) AND DownloadId LIKE ?", (owner, likeDate, )) 150 | user = self.c.fetchone() 151 | if user is not None: 152 | return user[1] 153 | else: 154 | return None 155 | 156 | def returnfid(self, item_text, owner): 157 | likeDate = "%" + str(item_text) + "%" 158 | self.c.execute("SELECT FileId FROM files WHERE User= (?) AND DownloadId LIKE ?", (owner, likeDate, )) 159 | user = self.c.fetchone() 160 | if user is not None: 161 | return user[0] 162 | else: 163 | return None 164 | 165 | def checkfileid(self, item_text, owner): 166 | likeDate = "%" + str(item_text) + "%" 167 | self.c.execute("SELECT FileId, User FROM files WHERE User= (?) AND FileId LIKE ?", (owner, likeDate, )) 168 | user = self.c.fetchone() 169 | if user is not None: 170 | return user[0] 171 | else: 172 | return None 173 | 174 | def fetchNews(self, fn, fs, fid, dlid, times, dates, user, link, year, month, day, h, m, s, priv, media): 175 | title = fn 176 | content = fid 177 | fsize = fs 178 | downloadid = dlid 179 | count = 0 180 | self.c.execute('''SELECT Fname FROM files WHERE Fname = ? OR FileId = ?''', (title, content)) 181 | row = self.c.fetchone() 182 | if row is None: 183 | self.c.execute('''INSERT INTO files (Fname, FileId, Size, Date, Time, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds, Private, Media) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )''', (title, content, fsize, dates, times, downloadid, user, link, year, month, day, h, m, s, priv, media )) 184 | count += 1 185 | self.conn.commit() 186 | 187 | print ("Total news written to database : ", count) 188 | 189 | def checkUserLastNews(self, chat_id): 190 | 191 | self.c.execute('SELECT LastNewsID FROM Users WHERE ChatID = ?', (chat_id, )) 192 | row = self.c.fetchone() 193 | if row is None: 194 | self.c.execute('INSERT INTO Users (ChatID, LastNewsID) VALUES (? , ?)', (chat_id, 1)) 195 | LastReadNewsID = 1 196 | print ("\nNew User :", chat_id, "\nLast Read News ID =", LastReadNewsID) 197 | else: 198 | LastReadNewsID = row[0] 199 | print ("\nOld User :", chat_id, "\nLast Read News ID =", LastReadNewsID) 200 | self.conn.commit() 201 | 202 | return LastReadNewsID 203 | 204 | def checkTodayFirstNewsID(self): 205 | now = datetime.now() 206 | date = now.strftime("%B %d, %Y") 207 | likeDate = "%" + date + "%" 208 | self.c.execute('''SELECT ID FROM files WHERE Date LIKE ? ORDER BY ID ASC LIMIT 1''', (likeDate, )) 209 | row = self.c.fetchone() 210 | if row is None: 211 | TodayFirstNewsID = 0 212 | print ("\nToday First News :", "No news") 213 | else: 214 | TodayFirstNewsID = row[0] 215 | print ("\nToday First News :", TodayFirstNewsID) 216 | return TodayFirstNewsID 217 | 218 | 219 | def fileid(self, fid): 220 | likeDate = "%" + fid + "%" 221 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, Time, DownloadId, User, Link FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 222 | 223 | row = self.c.fetchone() 224 | if row is None: 225 | news = 0 226 | else: 227 | news = row[3] 228 | return news 229 | 230 | def vfileid(self, fid): 231 | likeDate = "%" + fid + "%" 232 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 233 | row = self.c.fetchone() 234 | if row is None: 235 | news = 0 236 | else: 237 | news = row[0], row[2], row[3], row[1], row[4], row[5], row[6] 238 | return news 239 | 240 | 241 | 242 | def ufil(self, fid, user): 243 | likeDate = "%" + fid + "%" 244 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds FROM files WHERE User = ? AND DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (user, likeDate, )) 245 | row = self.c.fetchone() 246 | if row is None: 247 | news = 0 248 | else: 249 | news = row[7] 250 | return news 251 | 252 | def checkd(self, id, q): 253 | now = datetime.now() 254 | date = now.strftime("%B %d, %Y") 255 | likeDate = "%" + q + "%" 256 | TodayFirstNewsID = "" 257 | items = "" 258 | self.c.execute("SELECT DownloadId from files WHERE User = ? AND DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (id, likeDate, )) 259 | row = self.c.fetchone() 260 | if row is not None: 261 | TodayFirstNewsID = row[0] 262 | else: 263 | TodayFirstNewsID = None 264 | return TodayFirstNewsID 265 | 266 | def cdate(self, fid): 267 | 268 | likeDate = "%" + fid + "%" 269 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 270 | 271 | row = self.c.fetchone() 272 | if row is None: 273 | news = 0 274 | else: 275 | news = row[9], row[10], row[11], row[12], row[12], row[13] 276 | return news 277 | 278 | 279 | 280 | def doc(self, fid): 281 | 282 | likeDate = "%" + fid + "%" 283 | self.c.execute("SELECT Fname, DownloadId FROM files WHERE Fname LIKE ? ORDER BY ID DESC LIMIT 1", (likeDate, )) 284 | row = self.c.fetchone() 285 | if row is None: 286 | news = 0 287 | else: 288 | news = row[1] 289 | return news 290 | 291 | 292 | def cdate(self, fid): 293 | 294 | likeDate = "%" + fid + "%" 295 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 296 | 297 | row = self.c.fetchone() 298 | if row is None: 299 | news = 0 300 | else: 301 | news = row[9], row[10], row[11], row[12], row[12], row[13] 302 | return news 303 | 304 | 305 | def delid(self, fid): 306 | self.c.execute("DELETE FROM files WHERE DownloadId= (?) AND User= (?)", (tnews, chat_id, )) 307 | row = self.c.fetchone() 308 | if row is None: 309 | news = 0 310 | valid = cur.rowcount 311 | else: 312 | news = row[3] 313 | valid = cur.rowcount 314 | self.conn.commit() 315 | return[news, valid] 316 | 317 | def filen(self, fid): 318 | 319 | likeDate = "%" + fid + "%" 320 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, Time, DownloadId, User, Link FROM files WHERE Fname LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 321 | row = self.c.fetchone() 322 | if row is None: 323 | news = 0 324 | else: 325 | news = row[7] 326 | 327 | return news 328 | 329 | def sfileid(self, fid): 330 | 331 | likeDate = "%" + fid + "%" 332 | self.c.execute("SELECT ID, Date, Fname, FileId, Time, Size, Time, DownloadId, User, Link FROM files WHERE Link LIKE ? ORDER BY ID ASC LIMIT 1", (likeDate, )) 333 | row = self.c.fetchone() 334 | if row is None: 335 | tfid = 0 336 | size = 0 337 | else: 338 | tfid = row[3] 339 | size = row[5] 340 | 341 | return (tfid, size) 342 | 343 | 344 | def getNews(self, LastReadNewsID, chat_id): 345 | self.c.execute("SELECT ID, Date, Fname, FileId, Size, Time, DownloadId, User, Link FROM files WHERE ID > ? ORDER BY ID ASC LIMIT 1", (LastReadNewsID, )) 346 | row = self.c.fetchone() 347 | if row is None: 348 | news = "Saved for future use. You can see all your saved files using /files." 349 | elif(row[0] > LastReadNewsID): 350 | 351 | news = "Ok I got it. Access your library using /files." 352 | else: 353 | news = "" 354 | cursor = self.conn.execute("UPDATE Users SET `LastNewsID` = ? WHERE ChatID = ?", (row[0], chat_id)) 355 | self.conn.commit() 356 | 357 | return (news) 358 | 359 | def make_public(self, dlid, chat_id): 360 | likeDate = "%" + dlid + "%" 361 | self.c.execute('SELECT Private, User FROM files WHERE User = ? AND DownloadId LIKE ? ORDER BY ID ASC LIMIT 1', (chat_id, dlid, )) 362 | row = self.c.fetchone() 363 | ok = 0 364 | if row is not None: 365 | LastReadNewsID = row[0] 366 | 367 | self.conn.execute("UPDATE OR IGNORE files SET `Private` = ? WHERE Private = 1 AND DownloadId = ?", (ok, dlid)) 368 | else: 369 | LastReadNewsID = 1 370 | self.conn.commit() 371 | return LastReadNewsID 372 | 373 | def make_private(self, dlid, chat_id): 374 | likeDate = "%" + dlid + "%" 375 | self.c.execute('SELECT Private, User FROM files WHERE User = ? AND DownloadId LIKE ? ORDER BY ID ASC LIMIT 1', (chat_id, dlid, )) 376 | row = self.c.fetchone() 377 | ok = 1 378 | if row is not None: 379 | LastReadNewsID = row[0] 380 | 381 | self.conn.execute("UPDATE OR IGNORE files SET `Private` = ? WHERE Private = 0 AND DownloadId = ?", (ok, dlid)) 382 | else: 383 | LastReadNewsID = 0 384 | self.conn.commit() 385 | return LastReadNewsID 386 | 387 | def getuser(self, fid, owner): 388 | likeDate = "%" + fid + "%" 389 | self.c.execute('''SELECT DISTINCT User FROM files WHERE User = ? AND Private = 1 AND DownloadId LIKE ? limit 1''', (owner, likeDate, )) 390 | user = self.c.fetchone() 391 | if user is not None: 392 | return user[0] 393 | else: 394 | return 0 395 | 396 | def copy(self, dlid, tnews, times, dates, chat_id, year, month, day, hr, mins, sec): 397 | likeDate = "%" + dlid + "%" 398 | self.c.execute('SELECT Fname, FileId, Size, Link, DownloadId, Private, media FROM files WHERE DownloadId LIKE ? ORDER BY ID ASC LIMIT 1', (dlid, )) 399 | row = self.c.fetchone() 400 | if row is not None: 401 | self.c.execute('INSERT OR IGNORE INTO files (Fname, FileId, Size, Date, Time, DownloadId, User, Link, Year, Month, Day, Hour, Minute, Seconds, Private, Media) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (row[0], row[1], row[2], dates, times, tnews, chat_id, row[3], year, month, day, hr, mins, sec, row[6], row[7] )) 402 | LastReadNewsID = tnews 403 | print ("\nnNew file token :", dlid, "\nLast Read News ID =", LastReadNewsID) 404 | else: 405 | LastReadNewsID = None 406 | print ("\nOld file token :", dlid, "\nLast Read News ID =", LastReadNewsID) 407 | self.conn.commit() 408 | return LastReadNewsID 409 | 410 | 411 | def delete_item(self, item_text,owner): 412 | stmt="DELETE FROM files WHERE DownloadId= (?) AND User= (?)" 413 | args=(item_text,owner ) 414 | self.conn.execute(stmt,args) 415 | self.conn.commit() 416 | 417 | 418 | def delete_all(self, owner): 419 | stmt="DELETE FROM files WHERE Media= (?)" 420 | args=(owner ) 421 | self.conn.execute(stmt,args) 422 | self.conn.commit() 423 | 424 | def add_column_to_table(self, table_name, column_name, column_type, default, value): 425 | 426 | for row in self.c.execute('PRAGMA table_info({})'.format(table_name)): 427 | if row[1] == column_name: 428 | print('column {} already exists in {}'.format(column_name, table_name)) 429 | return 430 | else: 431 | print('add column {} to {}'.format(column_name, table_name)) 432 | self.c.execute('ALTER TABLE {} ADD COLUMN {} {} {} {}'.format(table_name, column_name, column_type, default, value)) 433 | 434 | 435 | def __exit__(self, exc_class, exc, traceback): 436 | 437 | self.conn.commit() 438 | 439 | self.conn.close() 440 | 441 | db = DBHelper() 442 | """mu = [] 443 | sw = [] 444 | for num, th in enumerate(mu[0:49]): 445 | sw.append(str(th[0])) 446 | for i in sw: 447 | db.delete_item(i, 197005208) 448 | with sqlite3.connect('inshorts.db', check_same_thread=False) as conn: 449 | cur = conn.cursor() 450 | cur.execute("SELECT DownloadId FROM files WHERE Media = ? ORDER BY ID DESC LIMIT 100", ('Music', )) 451 | row = cur.fetchall() 452 | for r in row: 453 | mu.append(r[0]) 454 | print(mu) 455 | for o in mu: 456 | cur.execute("DELETE FROM files WHERE DownloadId= (?) AND User= (?)", (197005208, o)) 457 | print(cur.rowcount)""" 458 | now = datetime.now() 459 | y = int(now.strftime("%Y")) 460 | mm = int(now.strftime("%m")) 461 | d = int(now.strftime("%d")) 462 | h = int(now.strftime("%H")) 463 | m = int(now.strftime("%M")) 464 | s = int(now.strftime("%S")) 465 | #add_column_to_table(c, 'files', 'Hour', 'INTEGER', 'DEFAULT', h) 466 | #add_column_to_table(c, 'files', 'Minute', 'INTEGER', 'DEFAULT', m) 467 | #add_column_to_table(c, 'files', 'Seconds', 'INTEGER', 'DEFAULT', s) 468 | 469 | #add_column_to_table(c, 'files', 'Year', 'INTEGER', 'DEFAULT', y) 470 | #add_column_to_table(c, 'files', 'Month', 'INTEGER', 'DEFAULT', mm) 471 | #add_column_to_table(c, 'files', 'Day', 'INTEGER', 'DEFAULT', d) 472 | #db.add_column_to_table('files', 'Private', 'BOOL', 'DEFAULT', 0) 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | -------------------------------------------------------------------------------- /plugins/callbacks/callbacks.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from utils.menus import * 3 | from pyrogram import ( 4 | api, Emoji, Client, InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardMarkup, InlineKeyboardButton, InputMediaDocument 5 | ) 6 | from base64 import b64decode 7 | from struct import unpack 8 | 9 | def parse_inline_message_id(inline_message_id): 10 | inline_message_id += "=" * ((4 - len(inline_message_id) % 4) % 4) 11 | dc_id, _id, access_hash = unpack(" rowcount: 87 | new_offset = rowcount - 1 88 | else: 89 | new_offset = rowcount - 1 90 | show_next = False 91 | else: 92 | new_offset = offset 93 | 94 | logger.warning(new_offset) 95 | likeDate = "%" + str(q) + "%" 96 | c.execute("SELECT ID, Fname, DownloadId, Size, Media FROM files WHERE Fname LIKE ? OR DownloadId LIKE ? OR Media LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?", (likeDate, likeDate, likeDate, new_offset, )) 97 | med = "" 98 | su = [] 99 | if "Software" in su: 100 | med = "🗳" 101 | elif "Music" in su: 102 | med = "📮" 103 | elif "Video" in su: 104 | med = "💽" 105 | elif "Documents" in su: 106 | med = "📑" 107 | elif "Archives" in su: 108 | med = "🗃" 109 | elif "Apps" in su: 110 | med = "🗂" 111 | elif "Pictures" in su: 112 | med = "🖼" 113 | else: 114 | med = "📦" 115 | items = "" 116 | rows = c.fetchall() 117 | things = [list(i) for i in rows] 118 | for ft in things[0:49]: 119 | su.append(str(ft[4])) 120 | try: 121 | if things: 122 | lens = len(rows) 123 | for num, row in enumerate(things[0:5]): 124 | items += ( 125 | "#{} " 126 | " {}" 127 | "\n\n📥 Download | 📍 Details | ⚖️ {} | {} {}\n" 128 | "\n" 129 | "-------------------------\n" 130 | "\n".format(str(num), (row[1][:70] + '..') if len(row[1]) > 75 else row[1], row[2], row[2], pretty_size(int(row[3])), med, row[4])) 131 | 132 | except (TypeError, ValueError, AttributeError): 133 | items = None 134 | 135 | else: 136 | offset = new_offset 137 | 138 | reply = None 139 | if action in ('old', 'new', 'last', 'first'): 140 | if items: 141 | reply = items 142 | elif (offset < 0): 143 | m.answer_callback_query(query.id, "WTF! {}, 🙄 I can't go back to the future 😏".format(query.from_user.first_name), show_alert=True) 144 | offset = 0 145 | elif (offset > rowcount): 146 | m.answer_callback_query(query.id, "Hold on! {}, That was it i have nothing more to show you 🚶🏼‍♂️🚶🏼‍♂️🚶🏼‍♂️".format(query.from_user.first_name), show_alert=True) 147 | offset = offset - 5 148 | return 149 | try: 150 | ids = [chat_id, str(hide)] 151 | confirmed = chat_id in ids if chat_id else False 152 | except: 153 | pass 154 | elif action == 'copy': 155 | 156 | if not confirmed: 157 | report = "**❗Report:**\n\n✅ File successfully deleted from your storage:\n\nSend /files to see your download history" 158 | err = "\n**❌ Invalid file token:**\n\nUse /help to learn more about me" 159 | unc = "\n**⚠️ 309 Uncaught Error:**\n\nThe file you are trying to save was deleted by the original uploader. You need to resend the file to save it again" 160 | savetwice = "\n**⚠️ 603 NotProcessed Error:**\n\nWhy would you want to save the same file more than once? 🙄 If you wish to continue, feel free its your choice" 161 | nauth = "\n**⚠️ 506 Unknown Error:**\n\n You are not authorised to delete this file because are not the owner\n\n Your uploaded file can be accessed using /files" 162 | user = db.ufil(str(q), str(chat_id)) 163 | ids = [chat_id, str(user)] 164 | 165 | kbs = regs_keyboard(id=str(q), admin=True, confirmed=user in ids if user else False, ids=user, chat_id=chat_id) 166 | reply_markups = InlineKeyboardMarkup(kbs) 167 | 168 | link = "https://t.me/jhbjh14514jjhbot" 169 | download_id = generate_uuid() 170 | times = datetime.now().strftime("%I:%M%p") 171 | dates = datetime.now().strftime("%B %d, %Y") 172 | now = datetime.now() 173 | year = int(now.strftime("%Y")) 174 | month = int(now.strftime("%m")) 175 | day = int(now.strftime("%d")) 176 | hr = int(now.strftime("%H")) 177 | mins = int(now.strftime("%M")) 178 | sec = int(now.strftime("%S")) 179 | try: 180 | tnews = str(q) 181 | snews = db.fileid(tnews) 182 | df = db.returnfid(tnews, chat_id) 183 | if df is not None: 184 | chkfid = db.checkfileid(df, chat_id) 185 | if chkfid is not None: 186 | m.edit_message_text(chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(savetwice), disable_web_page_preview=True, parse_mode="markdown", reply_markup=reply_markups) 187 | m.answer_callback_query(query.id, "The file you are trying to save is not available") 188 | return 189 | else: 190 | pass 191 | else: 192 | pass 193 | #(dlid, times, dates, user, year, month, day, h, m, s) 194 | fids = db.copy(tnews, str(download_id+"b"), times, dates, chat_id, year, month, day, hr, mins, sec) 195 | if fids is not None: 196 | fidse = fids 197 | else: 198 | m.edit_message_text(chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(unc), disable_web_page_preview=True, parse_mode="markdown", reply_markup=reply_markups) 199 | m.answer_callback_query(query.id, "The file you are trying to save is not available") 200 | return 201 | logger.warning(fids) 202 | ver = db.checkifexist(fidse, chat_id) 203 | item = "" 204 | reply_markups = InlineKeyboardMarkup(kbs) 205 | if snews: 206 | num, row, fid, dat, tim, siz, did = db.vfileid(fidse) 207 | nums = db.checkd(chat_id, did) 208 | else: 209 | did = None 210 | 211 | if ver: 212 | if did: 213 | yr, mm, day, hr, mte, sec = db.cdate(did) 214 | ds = datetime(yr, mm, day, hr, mte, sec ) 215 | user = db.ufil(did, str(chat_id)) 216 | ids = [chat_id, str(user)] 217 | kbs = reg_keyboard(id=did, admin=True, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=1, auth=[]) 218 | reply_markups = InlineKeyboardMarkup(kbs) 219 | 220 | logger.warning(user) 221 | 222 | if(user != 0): 223 | item = ( 224 | "🆔 : #{} \n\n" 225 | "ℹ️ : {}\n\n" 226 | "⌛️ : {} | 🕰 {}\n\n" 227 | "⚖️ : {}\n" 228 | "-----------------------------------------------------------------------------------------""".format(str(nums), str(row), dat, timedate(ds), pretty_size(int(siz)))) 229 | 230 | 231 | m.edit_message_text(chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(item), disable_web_page_preview=True, parse_mode="html", reply_markup=reply_markups) 232 | m.answer_callback_query(query.id, "Wao! You just saved this to your storage. Have fun 😊") 233 | 234 | else: 235 | 236 | m.edit_message_text(chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(report), disable_web_page_preview=True, reply_markup=reply_markups) 237 | m.answer_callback_query(query.id, "You appear to be an alien. Why not check yur storage first", show_alert=True) 238 | 239 | else: 240 | m.edit_message_text( 241 | chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(nauth), disable_web_page_preview=True, reply_markup=reply_markups) 242 | m.answer_callback_query(query.id, "The file ID is invalid. Kindly refresh your files list", show_alert=True) 243 | else: 244 | m.edit_message_text( 245 | chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(err), disable_web_page_preview=True, reply_markup=reply_markups) 246 | m.answer_callback_query(query.id, "🙄​ Just stop the madness. The required file is missen / deleted / or may be private", show_alert=True) 247 | except AttributeError: 248 | m.answer_callback_query(query.id, "The action can't be performed kindly try again", show_alert=True) 249 | return 250 | else: 251 | report = "**❗Report:**\n\n✅ File successfully deleted from your storage:\n\nSend /files to see your download history" 252 | err = "\n**❌ Invalid file token:**\n\nUse /help to learn more about me" 253 | nauth = "\n**⚠️ 506 Unknown Error:**\n\n You are not authorised to delete this file because are not the owner\n\n Your uploaded file can be accessed using /files" 254 | try: 255 | tnews = str(q) 256 | snews = db.fileid(tnews) 257 | ver = db.checkifexist(tnews, chat_id) 258 | ids = [chat_id, str(ver)] 259 | user = db.ufil(tnews, str(chat_id)) 260 | kbs = regs_keyboard(id=tnews, admin=False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id) 261 | reply_markups = InlineKeyboardMarkup(kbs) 262 | if snews: 263 | if (ver == chat_id): 264 | db.delete_item(tnews, chat_id) 265 | m.edit_message_text(chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(report), disable_web_page_preview=True, reply_markup=reply_markups) 266 | m.answer_callback_query(query.id, "File was removed successfully") 267 | #g = str(q) 268 | elif not ver: 269 | m.edit_message_text( 270 | chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(nauth), disable_web_page_preview=True, reply_markup=reply_markups) 271 | m.answer_callback_query(query.id, "You can't delete this. Why not save it first", show_alert=True) 272 | 273 | 274 | else: 275 | m.edit_message_text( 276 | chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(err), disable_web_page_preview=True, reply_markup=reply_markups) 277 | m.answer_callback_query(query.id, "The token is invalid", show_alert=True) 278 | except TypeError as e: 279 | logger.debug(e) 280 | m.answer_callback_query(query.id, "The action can't be performed kindly try again", show_alert=True) 281 | except ValueError as e: 282 | logger.debug(e) 283 | m.answer_callback_query(query.id, "308 Unidentified error... My master has been notified", show_alert=True) 284 | return 285 | except AttributeError as e: 286 | logger.debug(e) 287 | m.answer_callback_query(query.id, "307 System error... My master has been notified", show_alert=True) 288 | return 289 | 290 | show_download = not confirmed 291 | return 292 | 293 | 294 | elif action == 'auth': 295 | if not admin: 296 | did = str(q) 297 | user = db.ufil(str(q), str(chat_id)) 298 | ids = [chat_id, str(user)] 299 | pr = db.make_private(did, str(chat_id)) 300 | usr = db.getuser(did, str(chat_id)) 301 | if (usr != chat_id): 302 | m.answer_callback_query(query.id, "😏 Stop dreaming please i can't perform that action", show_alert=True) 303 | return 304 | else: 305 | idss = [chat_id, usr] 306 | kbs = reg_keyboard(id=did, admin=usr in idss if usr else False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=private, auth=auth) 307 | reply_markups = InlineKeyboardMarkup(kbs) 308 | rep = "Your file is now Private. Only you can download this file" 309 | m.edit_message_text( 310 | chat_id=update.message.chat.id, message_id=update.message.message_id, text=rep, reply_markup=reply_markups, disable_web_page_preview=True) 311 | m.answer_callback_query(query.id, "Only you can download this file", show_alert=True) 312 | auth.add(user) 313 | logger.debug(auth) 314 | return 315 | 316 | else: 317 | did = str(q) 318 | user = db.ufil(str(q), str(chat_id)) 319 | ids = [chat_id, str(user)] 320 | pr = db.make_public(did, str(chat_id)) 321 | usr = db.getuser(did, str(chat_id)) 322 | idss = [chat_id, usr] 323 | iss = [usr] 324 | if usr not in iss: 325 | m.answer_callback_query(query.id, "🙄 Only {} Can unlock this file. Just get home and stop fooling around".format(chat_id), show_alert=True) 326 | return 327 | else: 328 | 329 | rep = "Your file is now public. Anyone with your file token can use it" 330 | 331 | kbs = reg_keyboard(id=did, admin=usr in idss if usr else False, confirmed=user in ids if user else False, ids=user, chat_id=chat_id, private=private, auth=auth) 332 | reply_markups = InlineKeyboardMarkup(kbs) 333 | m.edit_message_text( 334 | chat_id=update.message.chat.id, message_id=update.message.message_id, text=rep, reply_markup=reply_markups, disable_web_page_preview=True) 335 | m.answer_callback_query(query.id, "Your file is now public.", show_alert=True) 336 | return 337 | auth.add(admin) 338 | logger.debug(auth) 339 | admin = not admin 340 | return 341 | 342 | 343 | elif action == 'dl': 344 | user = db.ufil(str(q), str(chat_id)) 345 | ids = [chat_id, str(user)] 346 | did = str(q) 347 | user = db.ufil(str(q), str(chat_id)) 348 | ids = [chat_id, str(user)] 349 | pr = db.make_private(did, str(chat_id)) 350 | usr = db.getuser(did, str(chat_id)) 351 | if (admin == 1): 352 | m.answer_callback_query(query.id, "⚠️ You are not authorized to download this file. Sorry", show_alert=True) 353 | return 354 | kbs = regs_keyboard(id=str(q), admin=True, confirmed=user in ids if user else False, ids=user, chat_id=chat_id) 355 | reply_markups = InlineKeyboardMarkup(kbs) 356 | try: 357 | g = str(q) 358 | snews = db.fileid(g) 359 | if snews: 360 | num, row, fid, dat, tim, siz, did = db.vfileid(g) 361 | nums = db.checkd(str(user), g) 362 | else: 363 | fid = None 364 | if fid: 365 | m.send_chat_action(update.message.chat.id,'UPLOAD_DOCUMENT') 366 | time.sleep(1) 367 | m.edit_message_reply_markup(update.message.chat.id, 368 | update.message.message_id,reply_markups) 369 | time.sleep(1) 370 | m.send_cached_media(update.message.chat.id, fid, caption="Powered with ❤️ - @Bfas237Bots") 371 | 372 | return 373 | else: 374 | m.send_chat_action(update.message.chat.id,'TYPING') 375 | time.sleep(1.5) 376 | inv = "😔 `404` **Invalid FILE_ID**.\n\n Send /files to see your saved files" 377 | m.edit_message_text( 378 | chat_id=update.message.chat.id, message_id=update.message.message_id, text="{}".format(inv), disable_web_page_preview=True, reply_markup=reply_markups) 379 | m.answer_callback_query(query.id, "The file ID is invalid", show_alert=True) 380 | return 381 | except FileIdInvalid: 382 | m.answer_callback_query(query.id, "The was a problem sending this file. Thats all i know", show_alert=True) 383 | return 384 | else: 385 | m.answer_callback_query(query.id, text="😔 Action currently Unavailable. Kindly try again after sometime") 386 | offset = offset - 4 387 | return 388 | 389 | #mm = state.get(update.message.chat.id).get('msgid') 390 | 391 | 392 | if reply: 393 | try: 394 | kb = search_keyboard(query=q, offset=offset, rows=rowcount, last=last, show_download=show_download) 395 | username = query.from_user.first_name 396 | reply_markup = InlineKeyboardMarkup(kb) 397 | m.edit_message_text( 398 | chat_id=update.message.chat.id, 399 | message_id=update.message.message_id, 400 | text="📄 {}'s files Library: {} out of {} \n\n {}".format(username, offset, rowcount, reply), 401 | parse_mode="HTML", 402 | disable_web_page_preview=True, 403 | reply_markup=reply_markup 404 | ) 405 | 406 | except UnboundLocalError as e: 407 | logger.debug(e) 408 | m.answer_callback_query(query.id, "⚠️ Actually you can navigate because your uploads are less than 5\n\n\n🗳 Total Uploads: {}".format(rowcount), show_alert=True) 409 | return 410 | 411 | except AttributeError as e: 412 | logger.debug(e) 413 | m.answer_callback_query(query.id, "Hold on! {}, Your session has expired 🙄:(".format(query.from_user.first_name), show_alert=True) 414 | return 415 | 416 | except MessageNotModified as e: 417 | logger.debug(e) 418 | m.answer_callback_query(query.id, "⚠️ Actually you can navigate because your uploads are less than 5\n\n\n🗳 Total Uploads: {}".format(rowcount), show_alert=True) 419 | return 420 | else: 421 | try: 422 | kb = search_keyboard(query=q, offset=offset, rows=rowcount, last=last, show_download=show_download) 423 | username = query.from_user.first_name 424 | reply_markup = InlineKeyboardMarkup(kb) 425 | m.edit_message_reply_markup(update.message.chat.id, 426 | update.message.message_id,reply_markup) 427 | except AttributeError as e: 428 | logger.debug(e) 429 | m.answer_callback_query(query.id, "Hold on! {}, Your session has expired 🙄:(".format(query.from_user.first_name), show_alert=True) 430 | return 431 | except MessageNotModified as e: 432 | logger.debug(e) 433 | m.answer_callback_query(query.id, "⚠️ Actually you can navigate because your uploads are less than {}\n\n\n🗳 Total Uploads: {}".format(offset+4, rowcount), show_alert=True) 434 | return 435 | except UnboundLocalError as e: 436 | logger.debug(e) 437 | m.answer_callback_query(query.id, "⚠️ Try by uploading more files first before you can navaigate", show_alert=True) 438 | return 439 | 440 | 441 | 442 | -------------------------------------------------------------------------------- /plugins/inlines/inline.py: -------------------------------------------------------------------------------- 1 | from utils.typing import * 2 | from docs.docs import * 3 | from telegram.utils.helpers import escape_markdown 4 | import logging 5 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 6 | 7 | 8 | 9 | def answer_inline(update, inline_query): 10 | """Handle the inline query.""" 11 | query = update.inline_query.query 12 | logger.warning(update) 13 | chat_id = update.effective_user.id 14 | userd = chat_id 15 | articles = [] 16 | sw = [] 17 | conn = sqlite3.connect('inshorts.db') 18 | c = conn.cursor() 19 | con = conn.cursor() 20 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.OPEN_FILE_FOLDER) 21 | DEFAULT_RESULTS = [ 22 | InlineQueryResultArticle( 23 | id=uuid4(), 24 | title="About Tele MultiStore Bot", 25 | input_message_content=InputTextMessageContent( 26 | "{} *Tele MultiStore*\n\n" 27 | "Tele MultiStore is an advanced, easy-to-use Telegram bot that replaces keeps track of all " 28 | "your uploaded files either through forwading, uploading " 29 | "or downloading from the web.".format(Emoji.CARD_INDEX_DIVIDERS), 30 | parse_mode=ParseMode.MARKDOWN, 31 | ), 32 | description="Tele MultiStore is an advanced storage bot for storing and retriving files", 33 | thumb_url=ABOUT_BOT_THUMB 34 | ), 35 | InlineQueryResultArticle( 36 | id=uuid4(), 37 | title="Usage", 38 | input_message_content=InputTextMessageContent(HELP, 39 | parse_mode=ParseMode.MARKDOWN), 40 | description="Learn some useful commands, tricks, and lots more how to use this bot", 41 | thumb_url=FILES_THUMB 42 | ), 43 | InlineQueryResultArticle( 44 | id=uuid4(), 45 | title="Help and Faqs", 46 | input_message_content=InputTextMessageContent(HELP_INLINE, 47 | parse_mode=ParseMode.MARKDOWN), 48 | reply_markup=InlineKeyboardMarkup( 49 | [ 50 | [InlineKeyboardButton("Inline Help 🆘", switch_inline_query_current_chat="!h")] 51 | ] 52 | ), 53 | description="Frequently asked questions and other helpful resources", 54 | thumb_url=HELP_THUMB 55 | ), 56 | InlineQueryResultArticle( 57 | id=uuid4(), 58 | title="Contribution", 59 | input_message_content=InputTextMessageContent(CONTRIBUTE, 60 | parse_mode=ParseMode.MARKDOWN), 61 | description="How to contribute and make this bot better than it is", 62 | thumb_url=CONTRIBUTE_THUMB 63 | ) 64 | 65 | ] 66 | 67 | string = update.inline_query.query.lower() 68 | 69 | if string == "": 70 | update.inline_query.answer( 71 | results=DEFAULT_RESULTS, 72 | cache_time=CACHE_TIME, 73 | is_personal=True, 74 | switch_pm_text=switch_pm_text, 75 | switch_pm_parameter="start", 76 | ) 77 | 78 | return 79 | offset = int(update.inline_query.offset or 0) 80 | su = [] 81 | if query.startswith('!pic'): 82 | likeDate = "%" + str(query[5:]) + "%" 83 | media = "Pictures" 84 | logger.warning(likeDate) 85 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 8 OFFSET ?', (media, likeDate, offset )) 86 | result = c.fetchall() 87 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 88 | rowcount = con.fetchone()[0] 89 | things = [list(i) for i in result] 90 | logger.warning('Query "%s"', things) 91 | try: 92 | for ft in things[0:49]: 93 | su.append(str(ft[3])) 94 | if offset == 0: 95 | articles = [ 96 | InlineQueryResultArticle( 97 | id=uuid4(), 98 | title=str(su[0]).upper(), 99 | description="All your desired image in one click", 100 | input_message_content=InputTextMessageContent( 101 | "🖼 **Image Store**\n\n" 102 | "`You can search for all images either by extention or file name if you know`" 103 | ), 104 | thumb_url=MISC_SEARCH_THUMB, 105 | ) 106 | ] 107 | except IndexError as e: 108 | articles = [InlineQueryResultArticle( 109 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 110 | description="Try by uploading something first", 111 | input_message_content=InputTextMessageContent( 112 | "This section happens to be empty.... Sorry!!!" 113 | ))] 114 | update.inline_query.answer( 115 | results=articles, 116 | cache_time=CACHE_TIME, 117 | switch_pm_text=switch_pm_text, 118 | switch_pm_parameter="start", 119 | offset=offset, 120 | ) 121 | return 122 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 123 | if things: 124 | s = 's' 125 | all = str(su[0]) 126 | 127 | for num, th in enumerate(things[0:49]): 128 | sw.append(str(th[0])) 129 | articles.append(InlineQueryResultCachedPhoto( 130 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=IMG_THUMB,photo_file_id="{}".format(str(th[2])), 131 | description="Click to view the details", 132 | caption="{}".format(str(th[1])), 133 | reply_markup=InlineKeyboardMarkup( 134 | [ 135 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 136 | ] 137 | ))) 138 | count = len(articles) - 1 139 | res = "" 140 | ress = "" 141 | if len(str(string[5:])) == 0: 142 | res = "Items in category" if count > 1 else "Item in category" 143 | if len(str(string[5:])) >= 1: 144 | ress = "Results for" if count > 1 else "Result for" 145 | 146 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[5:])) == 0 else ress, all if len(str(string[5:])) < 1 else str(string[5:])) 147 | elif not things: 148 | s = 's' 149 | all = 'Media' 150 | articles = [InlineQueryResultArticle( 151 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 152 | description="Try Searching for ("+str(rowcount)+")", 153 | input_message_content=InputTextMessageContent( 154 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 155 | parse_mode=ParseMode.MARKDOWN, 156 | ), 157 | reply_markup=InlineKeyboardMarkup([[ 158 | 159 | InlineKeyboardButton( 160 | "Try this example", 161 | switch_inline_query_current_chat="!store telegram" 162 | )]]) 163 | 164 | )] 165 | count = len(articles) - 1 166 | 167 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if string == "!f" else str(query[5:])) 168 | 169 | count = len(articles) - 1 170 | if articles: 171 | update.inline_query.answer( 172 | results=articles, 173 | cache_time=CACHE_TIME, 174 | switch_pm_text=switch_pm_text, 175 | switch_pm_parameter="start", 176 | next_offset="" if count <= 49 else offset 177 | ) 178 | else: 179 | if offset: 180 | update.inline_query.answer( 181 | results=[], 182 | cache_time=CACHE_TIME, 183 | switch_pm_text=switch_pm_text, 184 | switch_pm_parameter="start", 185 | next_offset="", 186 | ) 187 | 188 | 189 | elif query.startswith('!h'): 190 | logger.warning(string) 191 | INLINE_HELP = [ 192 | InlineQueryResultArticle( 193 | id=uuid4(), 194 | title="💻 Software Search", 195 | input_message_content=InputTextMessageContent( 196 | "🖥️ *Software Search*\n\n" 197 | "`Don't hassle any longer for you have it all. Search for your desired software " 198 | "by typing either the full or just part of the name " 199 | "or by extension. It works like magic.`\n" 200 | "\n" 201 | "*Supported Syntax:* `@TeleMultiStoreBot `" 202 | "\n\n" 203 | "*Example:* `@TeleMultiStoreBot !soft idm`", 204 | parse_mode=ParseMode.MARKDOWN, 205 | ), 206 | reply_markup=InlineKeyboardMarkup([[ 207 | 208 | InlineKeyboardButton( 209 | "Give it a try", 210 | switch_inline_query_current_chat="!soft idm" 211 | )]]), 212 | description="Learn how to search for software", 213 | thumb_url=INLINE_HELP_SOFTWARE_THUMB 214 | ), 215 | 216 | InlineQueryResultArticle( 217 | id=uuid4(), 218 | title="📱 Mobile Apps Search", 219 | input_message_content=InputTextMessageContent( 220 | "📱 *Mobile Apps Search*\n\n" 221 | "`You can perform instantaneous app search using any " 222 | " regex pattern either using the full app name " 223 | "or by extension. It works like magic.`\n" 224 | "\n" 225 | "*Supported Syntax:* `@TeleMultiStoreBot `" 226 | "\n\n" 227 | "*Example:* `@TeleMultiStoreBot !store telegram`", 228 | parse_mode=ParseMode.MARKDOWN, 229 | ), 230 | reply_markup=InlineKeyboardMarkup([[ 231 | 232 | InlineKeyboardButton( 233 | "Give it a try", 234 | switch_inline_query_current_chat="!store telegram" 235 | )]]), 236 | description="Learn how to search for software", 237 | thumb_url=INLINE_HELP_MOBILE_THUMB 238 | ) 239 | 240 | 241 | ] 242 | switch_pm_text = "🆘 TELE MULTISTORE HELP" 243 | if string == "": 244 | update.inline_query.answer( 245 | results=[], 246 | cache_time=CACHE_TIME, 247 | switch_pm_text="{} Type to search".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 248 | switch_pm_parameter="start", 249 | ) 250 | 251 | 252 | things = ["ok"] 253 | logger.warning('Query "%s"', things) 254 | try: 255 | for ft in things[0:49]: 256 | su.append(str(ft[3])) 257 | except IndexError as e: 258 | articles = INLINE_HELP 259 | update.inline_query.answer( 260 | results=articles, 261 | cache_time=CACHE_TIME, 262 | switch_pm_text=switch_pm_text, 263 | switch_pm_parameter="start", 264 | offset=offset, 265 | ) 266 | return 267 | 268 | 269 | 270 | elif query.startswith('!store'): 271 | logger.warning(string) 272 | if string == "": 273 | update.inline_query.answer( 274 | results=[], 275 | cache_time=CACHE_TIME, 276 | switch_pm_text="{} Type to search Raw Docs".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 277 | switch_pm_parameter="start", 278 | ) 279 | 280 | 281 | likeDate = "%" + str(string[7:]) + "%" 282 | media = "Apps" 283 | logger.warning(likeDate) 284 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 285 | result = c.fetchall() 286 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 287 | rowcount = con.fetchone()[0] 288 | things = [list(i) for i in result] 289 | logger.warning('Query "%s"', things) 290 | try: 291 | for ft in things[0:49]: 292 | su.append(str(ft[3])) 293 | if offset == 0: 294 | articles.append( 295 | InlineQueryResultArticle( 296 | id=uuid4(), 297 | title=str(su[0]).upper(), 298 | description="Your onestop mobile app search", 299 | input_message_content=InputTextMessageContent( 300 | "📱 **Mobile Apps finder**\n\n" 301 | "`This section deals with all mobile apps. You just need to pass a search term and get the available results`" 302 | ), 303 | thumb_url=APK_SEARCH_THUMB, 304 | ) 305 | ) 306 | 307 | except IndexError as e: 308 | articles = [InlineQueryResultArticle( 309 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 310 | description="Try by uploading something first", 311 | input_message_content=InputTextMessageContent( 312 | "Try uploading something first" 313 | ))] 314 | update.inline_query.answer( 315 | results=articles, 316 | cache_time=CACHE_TIME, 317 | switch_pm_text=switch_pm_text, 318 | switch_pm_parameter="start", 319 | offset=offset, 320 | ) 321 | return 322 | 323 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 324 | if things: 325 | s = 's' 326 | all = str(su[0]) 327 | 328 | for num, th in enumerate(things[0:49]): 329 | sw.append(str(th[0])) 330 | articles.append(InlineQueryResultCachedDocument( 331 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=MEDIA_THUMB,document_file_id="{}".format(str(th[2])), 332 | description="Click to view the details", 333 | caption="{}".format(str(th[1])), 334 | reply_markup=InlineKeyboardMarkup( 335 | [ 336 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 337 | ] 338 | ))) 339 | count = len(articles) - 1 340 | res = "" 341 | ress = "" 342 | if len(str(string[7:])) == 0: 343 | res = "Items in category" if count > 1 else "Item in category" 344 | if len(str(string[7:])) >= 1: 345 | ress = "Results for" if count > 1 else "Result for" 346 | 347 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[7:])) == 0 else ress, all if len(str(string[7:])) < 1 else str(query[7:])) 348 | elif not things: 349 | s = 's' 350 | all = 'Apps' 351 | articles = [InlineQueryResultArticle( 352 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 353 | description="Try Searching for ("+str(rowcount)+")", 354 | input_message_content=InputTextMessageContent( 355 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 356 | parse_mode=ParseMode.MARKDOWN, 357 | ), 358 | reply_markup=InlineKeyboardMarkup([[ 359 | 360 | InlineKeyboardButton( 361 | "Try this example", 362 | switch_inline_query_current_chat="!store telegram" 363 | )]]))] 364 | count = len(articles) - 1 365 | strings = (string[:8] + '..') if len(string) > 10 else string 366 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[7:])) 367 | 368 | count = len(articles) - 1 369 | 370 | 371 | 372 | elif query.startswith('!doc'): 373 | logger.warning(string) 374 | if string == "": 375 | update.inline_query.answer( 376 | results=[], 377 | cache_time=CACHE_TIME, 378 | switch_pm_text="{} Type to search Raw Docs".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 379 | switch_pm_parameter="start", 380 | ) 381 | 382 | 383 | likeDate = "%" + str(string[5:]) + "%" 384 | media = "Documents" 385 | logger.warning(likeDate) 386 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 387 | result = c.fetchall() 388 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 389 | rowcount = con.fetchone()[0] 390 | things = [list(i) for i in result] 391 | logger.warning('Query "%s"', things) 392 | try: 393 | for ft in things[0:49]: 394 | su.append(str(ft[3])) 395 | if offset == 0: 396 | articles.append( 397 | InlineQueryResultArticle( 398 | id=uuid4(), 399 | title=str(su[0]).upper(), 400 | description="Find all types of documents for your personal needs", 401 | input_message_content=InputTextMessageContent( 402 | "📱 **Mobile Apps finder**\n\n" 403 | "`This section deals with all mobile apps. You just need to pass a search term and get the available results`" 404 | ), 405 | thumb_url=APK_SEARCH_THUMB, 406 | ) 407 | ) 408 | 409 | except IndexError as e: 410 | articles = [InlineQueryResultArticle( 411 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 412 | description="Try by uploading something first", 413 | input_message_content=InputTextMessageContent( 414 | "Try uploading something first" 415 | ))] 416 | update.inline_query.answer( 417 | results=articles, 418 | cache_time=CACHE_TIME, 419 | switch_pm_text=switch_pm_text, 420 | switch_pm_parameter="start", 421 | offset=offset, 422 | ) 423 | return 424 | 425 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 426 | if things: 427 | s = 's' 428 | all = str(su[0]) 429 | 430 | for num, th in enumerate(things[0:49]): 431 | sw.append(str(th[0])) 432 | articles.append(InlineQueryResultCachedDocument( 433 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=DOC_THUMB,document_file_id="{}".format(str(th[2])), 434 | description="Click to view the details", 435 | caption="{}".format(str(th[1])), 436 | reply_markup=InlineKeyboardMarkup( 437 | [ 438 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 439 | ] 440 | ))) 441 | count = len(articles) - 1 442 | res = "" 443 | ress = "" 444 | if len(str(string[5:])) == 0: 445 | res = "Items in category" if count > 1 else "Item in category" 446 | if len(str(string[5:])) >= 1: 447 | ress = "Results for" if count > 1 else "Result for" 448 | 449 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[5:])) == 0 else ress, all if len(str(string[5:])) < 1 else str(query[5:])) 450 | elif not things: 451 | s = 's' 452 | all = 'Document' 453 | articles = [InlineQueryResultArticle( 454 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 455 | description="Try Searching for ("+str(rowcount)+")", 456 | input_message_content=InputTextMessageContent( 457 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 458 | parse_mode=ParseMode.MARKDOWN, 459 | ), 460 | reply_markup=InlineKeyboardMarkup([[ 461 | 462 | InlineKeyboardButton( 463 | "Try this example", 464 | switch_inline_query_current_chat="!store telegram" 465 | )]]))] 466 | count = len(articles) - 1 467 | strings = (string[:8] + '..') if len(string) > 10 else string 468 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[7:])) 469 | 470 | count = len(articles) - 1 471 | 472 | 473 | 474 | 475 | elif query.startswith('!zip'): 476 | logger.warning(string) 477 | if string == "": 478 | update.inline_query.answer( 479 | results=[], 480 | cache_time=CACHE_TIME, 481 | switch_pm_text="{} Type to search Raw Docs".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 482 | switch_pm_parameter="start", 483 | ) 484 | 485 | 486 | likeDate = "%" + str(string[5:]) + "%" 487 | media = "Archives" 488 | logger.warning(likeDate) 489 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 490 | result = c.fetchall() 491 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 492 | rowcount = con.fetchone()[0] 493 | things = [list(i) for i in result] 494 | logger.warning('Query "%s"', things) 495 | try: 496 | for ft in things[0:49]: 497 | su.append(str(ft[3])) 498 | if offset == 0: 499 | articles.append( 500 | InlineQueryResultArticle( 501 | id=uuid4(), 502 | title=str(su[0]), 503 | description="Your onestop mobile app search", 504 | input_message_content=InputTextMessageContent( 505 | "📱 **Mobile Apps finder**\n\n" 506 | "`This section deals with all mobile apps. You just need to pass a search term and get the available results`" 507 | ), 508 | thumb_url=APK_SEARCH_THUMB, 509 | ) 510 | ) 511 | 512 | except IndexError as e: 513 | articles = [InlineQueryResultArticle( 514 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 515 | description="Try by uploading something first", 516 | input_message_content=InputTextMessageContent( 517 | "Try uploading something first" 518 | ))] 519 | update.inline_query.answer( 520 | results=articles, 521 | cache_time=CACHE_TIME, 522 | switch_pm_text=switch_pm_text, 523 | switch_pm_parameter="start", 524 | offset=offset, 525 | ) 526 | return 527 | 528 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 529 | if things: 530 | s = 's' 531 | all = str(su[0]) 532 | 533 | for num, th in enumerate(things[0:49]): 534 | sw.append(str(th[0])) 535 | articles.append(InlineQueryResultCachedDocument( 536 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=MEDIA_THUMB,document_file_id="{}".format(str(th[2])), 537 | description="Click to view the details", 538 | caption="{}".format(str(th[1])), 539 | reply_markup=InlineKeyboardMarkup( 540 | [ 541 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 542 | ] 543 | ))) 544 | count = len(articles) - 1 545 | res = "" 546 | ress = "" 547 | if len(str(string[5:])) == 0: 548 | res = "Items in category" if count > 1 else "Item in category" 549 | if len(str(string[5:])) >= 1: 550 | ress = "Results for" if count > 1 else "Result for" 551 | 552 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[5:])) == 0 else ress, all if len(str(string[5:])) < 1 else str(query[5:])) 553 | elif not things: 554 | s = 's' 555 | all = 'Document' 556 | articles = [InlineQueryResultArticle( 557 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 558 | description="Try Searching for ("+str(rowcount)+")", 559 | input_message_content=InputTextMessageContent( 560 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 561 | parse_mode=ParseMode.MARKDOWN, 562 | ), 563 | reply_markup=InlineKeyboardMarkup([[ 564 | 565 | InlineKeyboardButton( 566 | "Try this example", 567 | switch_inline_query_current_chat="!store telegram" 568 | )]]))] 569 | count = len(articles) - 1 570 | strings = (string[:8] + '..') if len(string) > 10 else string 571 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[7:])) 572 | 573 | count = len(articles) - 1 574 | 575 | 576 | elif query.startswith('!soft'): 577 | logger.warning(string) 578 | if string == "": 579 | update.inline_query.answer( 580 | results=[], 581 | cache_time=CACHE_TIME, 582 | switch_pm_text="{} Type to search".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 583 | switch_pm_parameter="start", 584 | ) 585 | 586 | 587 | likeDate = "%" + str(string[7:]) + "%" 588 | media = "Software" 589 | logger.warning(likeDate) 590 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 591 | result = c.fetchall() 592 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 593 | rowcount = con.fetchone()[0] 594 | things = [list(i) for i in result] 595 | logger.warning('Query "%s"', things) 596 | try: 597 | for ft in things[0:49]: 598 | su.append(str(ft[3])) 599 | if offset == 0: 600 | articles.append( 601 | InlineQueryResultArticle( 602 | id=uuid4(), 603 | title=str(su[0]).upper(), 604 | description="A reliable source for all your desired softwares", 605 | input_message_content=InputTextMessageContent( 606 | "🖥 *Software Search Tool*\n\n" 607 | "`Within this section, you can perform some queries to get your desired software.\n\n regex search is also supported`", parse_mode=ParseMode.MARKDOWN 608 | ), 609 | reply_markup=InlineKeyboardMarkup( 610 | [ 611 | [InlineKeyboardButton("Example 1", switch_inline_query_current_chat="!soft idm")],[InlineKeyboardButton("Example 2", switch_inline_query_current_chat="!soft exe")] 612 | ] 613 | ), 614 | thumb_url=SOFTWARE_THUMB, 615 | ) 616 | ) 617 | 618 | except IndexError as e: 619 | articles = [InlineQueryResultArticle( 620 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 621 | description="Try by uploading something first", 622 | input_message_content=InputTextMessageContent( 623 | "Try uploading something first" 624 | ))] 625 | update.inline_query.answer( 626 | results=articles, 627 | cache_time=CACHE_TIME, 628 | switch_pm_text=switch_pm_text, 629 | switch_pm_parameter="start", 630 | offset=offset, 631 | ) 632 | return 633 | 634 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 635 | if things: 636 | s = 's' 637 | all = str(su[0]) 638 | 639 | for num, th in enumerate(things[0:49]): 640 | sw.append(str(th[0])) 641 | articles.append(InlineQueryResultCachedDocument( 642 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=MEDIA_THUMB,document_file_id="{}".format(str(th[2])), 643 | description="Click to view the details", 644 | caption="{}".format(str(th[1])), 645 | reply_markup=InlineKeyboardMarkup( 646 | [ 647 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 648 | ] 649 | ))) 650 | count = len(articles) - 1 651 | res = "" 652 | ress = "" 653 | if len(str(string[7:])) == 0: 654 | res = "Items in category" if count > 1 else "Item in category" 655 | if len(str(string[7:])) >= 1: 656 | ress = "Results for" if count > 1 else "Result for" 657 | 658 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[7:])) == 0 else ress, all if len(str(string[7:])) < 1 else str(query[7:])) 659 | elif not things: 660 | s = 's' 661 | all = 'Software' 662 | articles = [InlineQueryResultArticle( 663 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 664 | description="Try Searching for ("+str(rowcount)+")", 665 | input_message_content=InputTextMessageContent( 666 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 667 | parse_mode=ParseMode.MARKDOWN, 668 | ), 669 | reply_markup=InlineKeyboardMarkup([[ 670 | 671 | InlineKeyboardButton( 672 | "Try this example", 673 | switch_inline_query_current_chat="!store telegram" 674 | )]]))] 675 | count = len(articles) - 1 676 | strings = (string[:8] + '..') if len(string) > 10 else string 677 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[7:])) 678 | 679 | count = len(articles) - 1 680 | 681 | 682 | elif query.startswith('!mp3'): 683 | logger.warning(string) 684 | if string == "": 685 | update.inline_query.answer( 686 | results=[], 687 | cache_time=CACHE_TIME, 688 | switch_pm_text="{} Type to search Raw Docs".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 689 | switch_pm_parameter="start", 690 | ) 691 | 692 | 693 | likeDate = "%" + str(string[5:]) + "%" 694 | media = "Music" 695 | logger.warning(likeDate) 696 | c.execute('SELECT DISTINCT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 697 | result = c.fetchall() 698 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 699 | rowcount = con.fetchone()[0] 700 | things = [list(i) for i in result] 701 | logger.warning('Query "%s"', things) 702 | try: 703 | for ft in things[0:49]: 704 | su.append(str(ft[3])) 705 | if offset == 0: 706 | articles.append( 707 | InlineQueryResultArticle( 708 | id=uuid4(), 709 | title=str(su[0]).upper(), 710 | description="Your soul is filled with lovely music", 711 | input_message_content=InputTextMessageContent( 712 | "🖼 **Mobile Apps finder**\n\n" 713 | "`This section deals with all mobile apps. You just need to pass a search term and get the available results`" 714 | ), 715 | thumb_url=APK_SEARCH_THUMB, 716 | ) 717 | ) 718 | 719 | except IndexError as e: 720 | articles = [InlineQueryResultArticle( 721 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 722 | description="Try by uploading something first", 723 | input_message_content=InputTextMessageContent( 724 | "Try uploading something first" 725 | ))] 726 | update.inline_query.answer( 727 | results=articles, 728 | cache_time=CACHE_TIME, 729 | switch_pm_text=switch_pm_text, 730 | switch_pm_parameter="start", 731 | offset=offset, 732 | ) 733 | return 734 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 735 | if things: 736 | s = 's' 737 | all = str(su[0]) 738 | 739 | for num, th in enumerate(things[0:49]): 740 | sw.append(str(th[0])) 741 | articles.append(InlineQueryResultCachedAudio( 742 | id=uuid4(), title="("+str(num)+") - {} @Bfas237Bots".format(str(th[1])), thumb_url=MP3_THUMB,audio_file_id="{}".format(str(th[2])), 743 | description="Click to view the details", 744 | caption="{}".format(str(th[1])), 745 | reply_markup=InlineKeyboardMarkup( 746 | [ 747 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 748 | ] 749 | ))) 750 | count = len(articles) - 1 751 | res = "" 752 | ress = "" 753 | if len(str(string[5:])) == 0: 754 | res = "Items in category" if count > 1 else "Item in category" 755 | if len(str(string[5:])) >= 1: 756 | ress = "Results for" if count > 1 else "Result for" 757 | 758 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[5:])) == 0 else ress, all if len(str(string[5:])) < 1 else str(query[5:])) 759 | elif not things: 760 | s = 's' 761 | all = 'Music' 762 | articles = [InlineQueryResultArticle( 763 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 764 | description="Try Searching for ("+str(rowcount)+")", 765 | input_message_content=InputTextMessageContent( 766 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 767 | parse_mode=ParseMode.MARKDOWN, 768 | ), 769 | reply_markup=InlineKeyboardMarkup([[ 770 | 771 | InlineKeyboardButton( 772 | "Try this example", 773 | switch_inline_query_current_chat="!store telegram" 774 | )]]))] 775 | count = len(articles) - 1 776 | strings = (string[:8] + '..') if len(string) > 10 else string 777 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[5:])) 778 | 779 | count = len(articles) - 1 780 | 781 | 782 | 783 | elif query.startswith('!vid'): 784 | logger.warning(string) 785 | if string == "": 786 | update.inline_query.answer( 787 | results=[], 788 | cache_time=CACHE_TIME, 789 | switch_pm_text="{} Type to search Raw Docs".format(Emoji.MAGNIFYING_GLASS_TILTED_RIGHT), 790 | switch_pm_parameter="start", 791 | ) 792 | 793 | 794 | likeDate = "%" + str(string[5:]) + "%" 795 | media = "Video" 796 | logger.warning(likeDate) 797 | c.execute('SELECT DownloadId, Fname, FileId, Media FROM files WHERE Media = ? AND Fname LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (media, likeDate, offset )) 798 | result = c.fetchall() 799 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE Media = ?", (media, )) 800 | rowcount = con.fetchone()[0] 801 | things = [list(i) for i in result] 802 | logger.warning('Query "%s"', things) 803 | try: 804 | for ft in things[0:49]: 805 | su.append(str(ft[3])) 806 | if offset == 0: 807 | articles.append( 808 | InlineQueryResultArticle( 809 | id=uuid4(), 810 | title=str(su[0]).upper(), 811 | description="Your onestop mobile app search", 812 | input_message_content=InputTextMessageContent( 813 | "🖼 **Mobile Apps finder**\n\n" 814 | "`This section deals with all mobile apps. You just need to pass a search term and get the available results`" 815 | ), 816 | thumb_url=SOFTWARE_THUMB, 817 | ) 818 | ) 819 | 820 | except IndexError as e: 821 | articles = [InlineQueryResultArticle( 822 | id=uuid4(), title="Nothing has been uploaded so far", thumb_url=NOT_FOUND, 823 | description="Try by uploading something first", 824 | input_message_content=InputTextMessageContent( 825 | "Try uploading something first" 826 | ))] 827 | update.inline_query.answer( 828 | results=articles, 829 | cache_time=CACHE_TIME, 830 | switch_pm_text=switch_pm_text, 831 | switch_pm_parameter="start", 832 | offset=offset, 833 | ) 834 | return 835 | 836 | switch_pm_text = "{} TELE MULTISTORE BOT".format(Emoji.BALLOT_BOX_WITH_BALLOT) 837 | if things: 838 | s = 's' 839 | all = str(su[0]) 840 | 841 | for num, th in enumerate(things[0:49]): 842 | sw.append(str(th[0])) 843 | articles.append(InlineQueryResultCachedVideo( 844 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=MEDIA_THUMB,video_file_id="{}".format(str(th[2])), 845 | description="Click to view the details", 846 | caption="{}".format(str(th[1])), 847 | reply_markup=InlineKeyboardMarkup( 848 | [ 849 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 850 | ] 851 | ))) 852 | count = len(articles) - 1 853 | res = "" 854 | ress = "" 855 | if len(str(string[5:])) == 0: 856 | res = "Items in category" if count > 1 else "Item in category" 857 | if len(str(string[5:])) >= 1: 858 | ress = "Results for" if count > 1 else "Result for" 859 | 860 | switch_pm_text = "{} Found {} {} \"{}\"".format(Emoji.OPEN_BOOK, count, res if len(str(string[5:])) == 0 else ress, all if len(str(string[5:])) < 1 else str(query[5:])) 861 | elif not things: 862 | s = 's' 863 | all = 'Videos' 864 | articles = [InlineQueryResultArticle( 865 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 866 | description="Try Searching for ("+str(rowcount)+")", 867 | input_message_content=InputTextMessageContent( 868 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 869 | parse_mode=ParseMode.MARKDOWN, 870 | ), 871 | reply_markup=InlineKeyboardMarkup([[ 872 | 873 | InlineKeyboardButton( 874 | "Try this example", 875 | switch_inline_query_current_chat="!store telegram" 876 | )]]))] 877 | count = len(articles) - 1 878 | strings = (string[:8] + '..') if len(string) > 10 else string 879 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.OPEN_BOOK, count, s if count > 1 else '', all if strings == "!f" else str(query[5:])) 880 | 881 | count = len(articles) - 1 882 | 883 | 884 | 885 | 886 | 887 | elif len(string) > 0: 888 | articles = [ 889 | InlineQueryResultArticle( 890 | id=uuid4(), 891 | title="Global Search", 892 | description="Search globally for any uploaded file or media", 893 | input_message_content=InputTextMessageContent( 894 | "{} **Global Search**\n\n" 895 | "`You can search globally for any uploaded file, media that has been uploaded to my storage. It doesn't matter if you are the uploader`".format(Emoji.MAGNIFYING_GLASS_TILTED_LEFT) 896 | ), 897 | thumb_url=GLOBAL_SEARCH_THUMB, 898 | ) 899 | ] 900 | likeDate = "%" + str(query) + "%" 901 | med = [] 902 | ct = len(med) - 1 903 | c.execute('SELECT DownloadId, Fname, FileId, Media FROM files WHERE Fname LIKE ? OR DownloadId LIKE ? OR Media LIKE ? ORDER BY ID DESC LIMIT 100 OFFSET ?', (likeDate, likeDate, likeDate, ct )) 904 | result = c.fetchall() 905 | con.execute("SELECT DISTINCT COUNT (*) FROM files WHERE User = ?", (chat_id, )) 906 | 907 | rowcount = con.fetchone()[0] 908 | things = [list(i) for i in result] 909 | 910 | for ft in things[0:49]: 911 | su.append(str(ft[3])) 912 | if things: 913 | s = 's' 914 | all = str(su[0]) 915 | for num, th in enumerate(things[0:49]): 916 | sw.append(str(th[0])) 917 | med.append(th[3]) 918 | articles.append(InlineQueryResultCachedDocument( 919 | id=uuid4(), title="("+str(num)+") - {}".format(str(th[1])), thumb_url=MEDIA_THUMB,document_file_id="{}".format(str(th[2])), 920 | description="Click to view the details", 921 | caption="{}".format(str(th[1])), 922 | reply_markup=InlineKeyboardMarkup( 923 | [ 924 | [InlineKeyboardButton("🔄 Send to another Chat", switch_inline_query=str(sw[0]))] 925 | ] 926 | ))) 927 | count = len(articles) - 1 928 | rst = len(result) 929 | res = "" 930 | ress = "" 931 | nu = "" 932 | if len(str(string)) == 0: 933 | res = "Items in category" if count > 1 else "Item in category" 934 | if len(str(string)) >= 1: 935 | ress = "Results for" if count > 1 else "Result for" 936 | if len(str(string)) >= 1: 937 | cnts = str(rst)+"+" if rst > 50 else "" 938 | if len(str(string)) == 0: 939 | nu = "and "+str(len(all))+" Others" if count > 1 else "" 940 | switch_pm_text = "{} Found {} {} \"{} {}\"".format(Emoji.OPEN_BOOK, cnts if rst > 50 else count, res if len(str(string)) == 0 else ress, all if len(str(string)) < 1 else str(query), nu) 941 | elif not things: 942 | s = 's' 943 | all = 'Media' 944 | articles = [InlineQueryResultArticle( 945 | id=uuid4(), title="Your search returned Nothing", thumb_url=NOT_FOUND, 946 | description="Click to view details", 947 | input_message_content=InputTextMessageContent( 948 | "This section happens to be empty.... Sorry!!!\n\n*Supported Syntax:* `@TeleMultiStoreBot `", 949 | parse_mode=ParseMode.MARKDOWN, 950 | ), 951 | reply_markup=InlineKeyboardMarkup([[ 952 | 953 | InlineKeyboardButton( 954 | "Try this example", 955 | switch_inline_query_current_chat="!store telegram" 956 | )]]))] 957 | count = len(articles) * 0 958 | strings = (string[:8] + '..') if len(string) > 10 else string 959 | switch_pm_text = "{} Found {} Result{} for \"{}\"".format(Emoji.CROSS_MARK, str(count), s if count > 1 else '', strings if count <= 1 else str(string)) 960 | if articles: 961 | b = len(articles) - 1 962 | count = int(round(b/5.0)*5.0) 963 | update.inline_query.answer( 964 | results=articles, 965 | cache_time=CACHE_TIME, 966 | switch_pm_text=switch_pm_text, 967 | switch_pm_parameter="start", 968 | next_offset="" if count <= 48 else offset 969 | ) 970 | else: 971 | update.inline_query.answer( 972 | results=[], 973 | cache_time=CACHE_TIME, 974 | switch_pm_text='{} No results for "{}"'.format(Emoji.CROSS_MARK, string), 975 | switch_pm_parameter="okay", 976 | ) 977 | --------------------------------------------------------------------------------