├── runtime.txt
├── heroku.yml
├── assets
└── logo.jpg
├── requirements.txt
├── Dockerfile
├── start.sh
├── plugins
├── channel.py
├── banned.py
├── broadcast.py
├── inline.py
├── genlink.py
├── connection.py
├── misc.py
├── index.py
├── filters.py
├── p_ttishow.py
├── commands.py
└── pm_filter.py
├── logging.conf
├── sample_info.py
├── .gitignore
├── app.json
├── database
├── filters_mdb.py
├── connections_mdb.py
├── users_chats_db.py
└── ia_filterdb.py
├── bot.py
├── Script.py
├── info.py
├── README.md
├── utils.py
└── LICENSE
/runtime.txt:
--------------------------------------------------------------------------------
1 | python-3.8.7
2 |
--------------------------------------------------------------------------------
/heroku.yml:
--------------------------------------------------------------------------------
1 | build:
2 | docker:
3 | worker: Dockerfile
--------------------------------------------------------------------------------
/assets/logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/itsyogieu/EvaMaria/HEAD/assets/logo.jpg
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pyrogram>=2.0.30
2 | tgcrypto
3 | pymongo[srv]==3.12.3
4 | motor==2.5.1
5 | marshmallow==3.14.1
6 | umongo==3.0.1
7 | requests
8 | bs4
9 | imdbpy==2021.4.18
10 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.8-slim-buster
2 |
3 | RUN apt update && apt upgrade -y
4 | RUN apt install git -y
5 | COPY requirements.txt /requirements.txt
6 |
7 | RUN cd /
8 | RUN pip3 install -U pip && pip3 install -U -r requirements.txt
9 | RUN mkdir /EvaMaria
10 | WORKDIR /EvaMaria
11 | COPY start.sh /start.sh
12 | CMD ["/bin/bash", "/start.sh"]
13 |
--------------------------------------------------------------------------------
/start.sh:
--------------------------------------------------------------------------------
1 | if [ -z $UPSTREAM_REPO ]
2 | then
3 | echo "Cloning main Repository"
4 | git clone https://github.com/EvamariaTG/EvaMaria.git /EvaMaria
5 | else
6 | echo "Cloning Custom Repo from $UPSTREAM_REPO "
7 | git clone $UPSTREAM_REPO /EvaMaria
8 | fi
9 | cd /EvaMaria
10 | pip3 install -U -r requirements.txt
11 | echo "Starting Bot...."
12 | python3 bot.py
--------------------------------------------------------------------------------
/plugins/channel.py:
--------------------------------------------------------------------------------
1 | from pyrogram import Client, filters
2 | from info import CHANNELS
3 | from database.ia_filterdb import save_file
4 |
5 | media_filter = filters.document | filters.video | filters.audio
6 |
7 |
8 | @Client.on_message(filters.chat(CHANNELS) & media_filter)
9 | async def media(bot, message):
10 | """Media Handler"""
11 | for file_type in ("document", "video", "audio"):
12 | media = getattr(message, file_type, None)
13 | if media is not None:
14 | break
15 | else:
16 | return
17 |
18 | media.file_type = file_type
19 | media.caption = message.caption
20 | await save_file(media)
--------------------------------------------------------------------------------
/logging.conf:
--------------------------------------------------------------------------------
1 | [loggers]
2 | keys=root
3 |
4 | [handlers]
5 | keys=consoleHandler,fileHandler
6 |
7 | [formatters]
8 | keys=consoleFormatter,fileFormatter
9 |
10 | [logger_root]
11 | level=DEBUG
12 | handlers=consoleHandler,fileHandler
13 |
14 | [handler_consoleHandler]
15 | class=StreamHandler
16 | level=INFO
17 | formatter=consoleFormatter
18 | args=(sys.stdout,)
19 |
20 | [handler_fileHandler]
21 | class=FileHandler
22 | level=ERROR
23 | formatter=fileFormatter
24 | args=('TelegramBot.log','w',)
25 |
26 | [formatter_consoleFormatter]
27 | format=%(asctime)s - %(lineno)d - %(name)s - %(module)s - %(levelname)s - %(message)s
28 | datefmt=%I:%M:%S %p
29 |
30 | [formatter_fileFormatter]
31 | format=[%(asctime)s:%(name)s:%(lineno)d:%(levelname)s] %(message)s
32 | datefmt=%m/%d/%Y %I:%M:%S %p
--------------------------------------------------------------------------------
/sample_info.py:
--------------------------------------------------------------------------------
1 | # Bot information
2 | SESSION = 'Media_search'
3 | USER_SESSION = 'User_Bot'
4 | API_ID = 12345
5 | API_HASH = '0123456789abcdef0123456789abcdef'
6 | BOT_TOKEN = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'
7 | USERBOT_STRING_SESSION = ''
8 |
9 | # Bot settings
10 | CACHE_TIME = 300
11 | USE_CAPTION_FILTER = False
12 |
13 | # Admins, Channels & Users
14 | ADMINS = [12345789, 'admin123', 98765432]
15 | CHANNELS = [-10012345678, -100987654321, 'channelusername']
16 | AUTH_USERS = []
17 | AUTH_CHANNEL = None
18 |
19 | # MongoDB information
20 | DATABASE_URI = "mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb]?retryWrites=true&w=majority"
21 | DATABASE_NAME = 'Telegram'
22 | COLLECTION_NAME = 'channel_files' # If you are using the same database, then use different collection name for each bot
23 |
24 |
25 |
--------------------------------------------------------------------------------
/plugins/banned.py:
--------------------------------------------------------------------------------
1 | from pyrogram import Client, filters
2 | from utils import temp
3 | from pyrogram.types import Message
4 | from database.users_chats_db import db
5 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
6 | from info import SUPPORT_CHAT
7 |
8 | async def banned_users(_, client, message: Message):
9 | return (
10 | message.from_user is not None or not message.sender_chat
11 | ) and message.from_user.id in temp.BANNED_USERS
12 |
13 | banned_user = filters.create(banned_users)
14 |
15 | async def disabled_chat(_, client, message: Message):
16 | return message.chat.id in temp.BANNED_CHATS
17 |
18 | disabled_group=filters.create(disabled_chat)
19 |
20 |
21 | @Client.on_message(filters.private & banned_user & filters.incoming)
22 | async def ban_reply(bot, message):
23 | ban = await db.get_ban_status(message.from_user.id)
24 | await message.reply(f'Sorry Dude, You are Banned to use Me. \nBan Reason: {ban["ban_reason"]}')
25 |
26 | @Client.on_message(filters.group & disabled_group & filters.incoming)
27 | async def grp_bd(bot, message):
28 | buttons = [[
29 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
30 | ]]
31 | reply_markup=InlineKeyboardMarkup(buttons)
32 | vazha = await db.get_chat(message.chat.id)
33 | k = await message.reply(
34 | text=f"CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..\nReason :
2 |
59 |
60 |
61 | [](https://heroku.com/deploy?template=https://github.com/itsyogieu/EvaMaria )
62 |
63 |
68 | {vazha['reason']}.",
35 | reply_markup=reply_markup)
36 | try:
37 | await k.pin()
38 | except:
39 | pass
40 | await bot.leave_chat(message.chat.id)
41 |
--------------------------------------------------------------------------------
/plugins/broadcast.py:
--------------------------------------------------------------------------------
1 |
2 | from pyrogram import Client, filters
3 | import datetime
4 | import time
5 | from database.users_chats_db import db
6 | from info import ADMINS
7 | from utils import broadcast_messages
8 | import asyncio
9 |
10 | @Client.on_message(filters.command("broadcast") & filters.user(ADMINS) & filters.reply)
11 | # https://t.me/GetTGLink/4178
12 | async def verupikkals(bot, message):
13 | users = await db.get_all_users()
14 | b_msg = message.reply_to_message
15 | sts = await message.reply_text(
16 | text='Broadcasting your messages...'
17 | )
18 | start_time = time.time()
19 | total_users = await db.total_users_count()
20 | done = 0
21 | blocked = 0
22 | deleted = 0
23 | failed =0
24 |
25 | success = 0
26 | async for user in users:
27 | pti, sh = await broadcast_messages(int(user['id']), b_msg)
28 | if pti:
29 | success += 1
30 | elif pti == False:
31 | if sh == "Blocked":
32 | blocked+=1
33 | elif sh == "Deleted":
34 | deleted += 1
35 | elif sh == "Error":
36 | failed += 1
37 | done += 1
38 | await asyncio.sleep(2)
39 | if not done % 20:
40 | await sts.edit(f"Broadcast in progress:\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
41 | time_taken = datetime.timedelta(seconds=int(time.time()-start_time))
42 | await sts.edit(f"Broadcast Completed:\nCompleted in {time_taken} seconds.\n\nTotal Users {total_users}\nCompleted: {done} / {total_users}\nSuccess: {success}\nBlocked: {blocked}\nDeleted: {deleted}")
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Personal files
2 | *.session
3 | *.session-journal
4 | .vscode
5 | *test*.py
6 | setup.cfg
7 |
8 | # Byte-compiled / optimized / DLL files
9 | __pycache__/
10 | *.py[cod]
11 | *$py.class
12 |
13 | # C extensions
14 | *.so
15 |
16 | # Distribution / packaging
17 | .Python
18 | build/
19 | develop-eggs/
20 | dist/
21 | downloads/
22 | eggs/
23 | .eggs/
24 | lib/
25 | lib64/
26 | parts/
27 | sdist/
28 | var/
29 | wheels/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | *.py,cover
57 | .hypothesis/
58 | .pytest_cache/
59 | cover/
60 |
61 | # Translations
62 | *.mo
63 | *.pot
64 |
65 | # Django stuff:
66 | *.log
67 | local_settings.py
68 | db.sqlite3
69 | db.sqlite3-journal
70 |
71 | # Flask stuff:
72 | instance/
73 | .webassets-cache
74 |
75 | # Scrapy stuff:
76 | .scrapy
77 |
78 | # Sphinx documentation
79 | docs/_build/
80 |
81 | # PyBuilder
82 | .pybuilder/
83 | target/
84 |
85 | # Jupyter Notebook
86 | .ipynb_checkpoints
87 |
88 | # IPython
89 | profile_default/
90 | ipython_config.py
91 |
92 | # pyenv
93 | # For a library or package, you might want to ignore these files since the code is
94 | # intended to run in multiple environments; otherwise, check them in:
95 | # .python-version
96 |
97 | # pipenv
98 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
100 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
101 | # install all needed dependencies.
102 | #Pipfile.lock
103 |
104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105 | __pypackages__/
106 |
107 | # Celery stuff
108 | celerybeat-schedule
109 | celerybeat.pid
110 |
111 | # SageMath parsed files
112 | *.sage.py
113 |
114 | # Environments
115 | .env
116 | .venv
117 | env/
118 | venv/
119 | ENV/
120 | env.bak/
121 | venv.bak/
122 |
123 | # Spyder project settings
124 | .spyderproject
125 | .spyproject
126 |
127 | # Rope project settings
128 | .ropeproject
129 |
130 | # mkdocs documentation
131 | /site
132 |
133 | # mypy
134 | .mypy_cache/
135 | .dmypy.json
136 | dmypy.json
137 |
138 | # Pyre type checker
139 | .pyre/
140 |
141 | # pytype static type analyzer
142 | .pytype/
143 |
144 | # Cython debug symbols
145 | cython_debug/
146 | config.py
147 | .goutputstream-VAFWB1
148 | result.json
149 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "EvaMariaBot",
3 | "description": "When you going to send file on telegram channel this bot will save that in database, So you can search that easily in inline mode",
4 | "stack": "container",
5 | "keywords": [
6 | "telegram",
7 | "auto-filter",
8 | "filter",
9 | "best",
10 | "indian",
11 | "pyrogram",
12 | "media",
13 | "search",
14 | "channel",
15 | "index",
16 | "inline"
17 | ],
18 | "website": "https://github.com/EvamariaTG/EvaMaria",
19 | "repository": "https://github.com/itsyogieu/EvaMaria",
20 | "env": {
21 | "BOT_TOKEN": {
22 | "description": "Your bot token.",
23 | "required": true
24 | },
25 | "API_ID": {
26 | "description": "Get this value from https://my.telegram.org",
27 | "required": true
28 | },
29 | "API_HASH": {
30 | "description": "Get this value from https://my.telegram.org",
31 | "required": true
32 | },
33 | "CHANNELS": {
34 | "description": "Username or ID of channel or group. Separate multiple IDs by space.",
35 | "required": false
36 | },
37 | "ADMINS": {
38 | "description": "Username or ID of Admin. Separate multiple Admins by space.",
39 | "required": true
40 | },
41 | "PICS": {
42 | "description": "Add some telegraph link of pictures .",
43 | "required": false
44 | },
45 | "LOG_CHANNEL": {
46 | "description": "Bot Logs,Give a channel id with -100xxxxxxx",
47 | "required": true
48 | },
49 | "AUTH_USERS": {
50 | "description": "Username or ID of users to give access of inline search. Separate multiple users by space.\nLeave it empty if you don't want to restrict bot usage.",
51 | "required": false
52 | },
53 | "AUTH_CHANNEL": {
54 | "description": "ID of channel.Make sure bot is admin in this channel. Without subscribing this channel users cannot use bot.",
55 | "required": false
56 | },
57 | "DATABASE_URI": {
58 | "description": "mongoDB URI. Get this value from https://www.mongodb.com. For more help watch this video - https://youtu.be/dsuTn4qV2GA",
59 | "required": true
60 | },
61 | "DATABASE_NAME": {
62 | "description": "Name of the database in mongoDB. For more help watch this video - https://youtu.be/dsuTn4qV2GA",
63 | "required": false
64 | },
65 | "COLLECTION_NAME": {
66 | "description": "Name of the collections. Defaults to Telegram_files. If you are using the same database, then use different collection name for each bot",
67 | "value": "Telegram_files",
68 | "required": false
69 | }
70 | },
71 | "addons": [],
72 | "buildpacks": [{
73 | "url": "heroku/python"
74 | }],
75 | "formation": {
76 | "worker": {
77 | "quantity": 1,
78 | "size": "free"
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/database/filters_mdb.py:
--------------------------------------------------------------------------------
1 | import pymongo
2 | from pyrogram import enums
3 | from info import DATABASE_URI, DATABASE_NAME
4 | import logging
5 | logger = logging.getLogger(__name__)
6 | logger.setLevel(logging.ERROR)
7 |
8 | myclient = pymongo.MongoClient(DATABASE_URI)
9 | mydb = myclient[DATABASE_NAME]
10 |
11 |
12 |
13 | async def add_filter(grp_id, text, reply_text, btn, file, alert):
14 | mycol = mydb[str(grp_id)]
15 | # mycol.create_index([('text', 'text')])
16 |
17 | data = {
18 | 'text':str(text),
19 | 'reply':str(reply_text),
20 | 'btn':str(btn),
21 | 'file':str(file),
22 | 'alert':str(alert)
23 | }
24 |
25 | try:
26 | mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True)
27 | except:
28 | logger.exception('Some error occured!', exc_info=True)
29 |
30 |
31 | async def find_filter(group_id, name):
32 | mycol = mydb[str(group_id)]
33 |
34 | query = mycol.find( {"text":name})
35 | # query = mycol.find( { "$text": {"$search": name}})
36 | try:
37 | for file in query:
38 | reply_text = file['reply']
39 | btn = file['btn']
40 | fileid = file['file']
41 | try:
42 | alert = file['alert']
43 | except:
44 | alert = None
45 | return reply_text, btn, alert, fileid
46 | except:
47 | return None, None, None, None
48 |
49 |
50 | async def get_filters(group_id):
51 | mycol = mydb[str(group_id)]
52 |
53 | texts = []
54 | query = mycol.find()
55 | try:
56 | for file in query:
57 | text = file['text']
58 | texts.append(text)
59 | except:
60 | pass
61 | return texts
62 |
63 |
64 | async def delete_filter(message, text, group_id):
65 | mycol = mydb[str(group_id)]
66 |
67 | myquery = {'text':text }
68 | query = mycol.count_documents(myquery)
69 | if query == 1:
70 | mycol.delete_one(myquery)
71 | await message.reply_text(
72 | f"'`{text}`' deleted. I'll not respond to that filter anymore.",
73 | quote=True,
74 | parse_mode=enums.ParseMode.MARKDOWN
75 | )
76 | else:
77 | await message.reply_text("Couldn't find that filter!", quote=True)
78 |
79 |
80 | async def del_all(message, group_id, title):
81 | if str(group_id) not in mydb.list_collection_names():
82 | await message.edit_text(f"Nothing to remove in {title}!")
83 | return
84 |
85 | mycol = mydb[str(group_id)]
86 | try:
87 | mycol.drop()
88 | await message.edit_text(f"All filters from {title} has been removed")
89 | except:
90 | await message.edit_text("Couldn't remove all filters from group!")
91 | return
92 |
93 |
94 | async def count_filters(group_id):
95 | mycol = mydb[str(group_id)]
96 |
97 | count = mycol.count()
98 | return False if count == 0 else count
99 |
100 |
101 | async def filter_stats():
102 | collections = mydb.list_collection_names()
103 |
104 | if "CONNECTION" in collections:
105 | collections.remove("CONNECTION")
106 |
107 | totalcount = 0
108 | for collection in collections:
109 | mycol = mydb[collection]
110 | count = mycol.count()
111 | totalcount += count
112 |
113 | totalcollections = len(collections)
114 |
115 | return totalcollections, totalcount
116 |
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import logging.config
3 |
4 | # Get logging configurations
5 | logging.config.fileConfig('logging.conf')
6 | logging.getLogger().setLevel(logging.INFO)
7 | logging.getLogger("pyrogram").setLevel(logging.ERROR)
8 | logging.getLogger("imdbpy").setLevel(logging.ERROR)
9 |
10 | from pyrogram import Client, __version__
11 | from pyrogram.raw.all import layer
12 | from database.ia_filterdb import Media
13 | from database.users_chats_db import db
14 | from info import SESSION, API_ID, API_HASH, BOT_TOKEN, LOG_STR
15 | from utils import temp
16 | from typing import Union, Optional, AsyncGenerator
17 | from pyrogram import types
18 |
19 | class Bot(Client):
20 |
21 | def __init__(self):
22 | super().__init__(
23 | name=SESSION,
24 | api_id=API_ID,
25 | api_hash=API_HASH,
26 | bot_token=BOT_TOKEN,
27 | workers=50,
28 | plugins={"root": "plugins"},
29 | sleep_threshold=5,
30 | )
31 |
32 | async def start(self):
33 | b_users, b_chats = await db.get_banned()
34 | temp.BANNED_USERS = b_users
35 | temp.BANNED_CHATS = b_chats
36 | await super().start()
37 | await Media.ensure_indexes()
38 | me = await self.get_me()
39 | temp.ME = me.id
40 | temp.U_NAME = me.username
41 | temp.B_NAME = me.first_name
42 | self.username = '@' + me.username
43 | logging.info(f"{me.first_name} with for Pyrogram v{__version__} (Layer {layer}) started on {me.username}.")
44 | logging.info(LOG_STR)
45 |
46 | async def stop(self, *args):
47 | await super().stop()
48 | logging.info("Bot stopped. Bye.")
49 |
50 | async def iter_messages(
51 | self,
52 | chat_id: Union[int, str],
53 | limit: int,
54 | offset: int = 0,
55 | ) -> Optional[AsyncGenerator["types.Message", None]]:
56 | """Iterate through a chat sequentially.
57 | This convenience method does the same as repeatedly calling :meth:`~pyrogram.Client.get_messages` in a loop, thus saving
58 | you from the hassle of setting up boilerplate code. It is useful for getting the whole chat messages with a
59 | single call.
60 | Parameters:
61 | chat_id (``int`` | ``str``):
62 | Unique identifier (int) or username (str) of the target chat.
63 | For your personal cloud (Saved Messages) you can simply use "me" or "self".
64 | For a contact that exists in your Telegram address book you can use his phone number (str).
65 |
66 | limit (``int``):
67 | Identifier of the last message to be returned.
68 |
69 | offset (``int``, *optional*):
70 | Identifier of the first message to be returned.
71 | Defaults to 0.
72 | Returns:
73 | ``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects.
74 | Example:
75 | .. code-block:: python
76 | for message in app.iter_messages("pyrogram", 1, 15000):
77 | print(message.text)
78 | """
79 | current = offset
80 | while True:
81 | new_diff = min(200, limit - current)
82 | if new_diff <= 0:
83 | return
84 | messages = await self.get_messages(chat_id, list(range(current, current+new_diff+1)))
85 | for message in messages:
86 | yield message
87 | current += 1
88 |
89 |
90 | app = Bot()
91 | app.run()
92 |
--------------------------------------------------------------------------------
/database/connections_mdb.py:
--------------------------------------------------------------------------------
1 | import pymongo
2 |
3 | from info import DATABASE_URI, DATABASE_NAME
4 |
5 | import logging
6 | logger = logging.getLogger(__name__)
7 | logger.setLevel(logging.ERROR)
8 |
9 | myclient = pymongo.MongoClient(DATABASE_URI)
10 | mydb = myclient[DATABASE_NAME]
11 | mycol = mydb['CONNECTION']
12 |
13 |
14 | async def add_connection(group_id, user_id):
15 | query = mycol.find_one(
16 | { "_id": user_id },
17 | { "_id": 0, "active_group": 0 }
18 | )
19 | if query is not None:
20 | group_ids = [x["group_id"] for x in query["group_details"]]
21 | if group_id in group_ids:
22 | return False
23 |
24 | group_details = {
25 | "group_id" : group_id
26 | }
27 |
28 | data = {
29 | '_id': user_id,
30 | 'group_details' : [group_details],
31 | 'active_group' : group_id,
32 | }
33 |
34 | if mycol.count_documents( {"_id": user_id} ) == 0:
35 | try:
36 | mycol.insert_one(data)
37 | return True
38 | except:
39 | logger.exception('Some error occurred!', exc_info=True)
40 |
41 | else:
42 | try:
43 | mycol.update_one(
44 | {'_id': user_id},
45 | {
46 | "$push": {"group_details": group_details},
47 | "$set": {"active_group" : group_id}
48 | }
49 | )
50 | return True
51 | except:
52 | logger.exception('Some error occurred!', exc_info=True)
53 |
54 |
55 | async def active_connection(user_id):
56 |
57 | query = mycol.find_one(
58 | { "_id": user_id },
59 | { "_id": 0, "group_details": 0 }
60 | )
61 | if not query:
62 | return None
63 |
64 | group_id = query['active_group']
65 | return int(group_id) if group_id != None else None
66 |
67 |
68 | async def all_connections(user_id):
69 | query = mycol.find_one(
70 | { "_id": user_id },
71 | { "_id": 0, "active_group": 0 }
72 | )
73 | if query is not None:
74 | return [x["group_id"] for x in query["group_details"]]
75 | else:
76 | return None
77 |
78 |
79 | async def if_active(user_id, group_id):
80 | query = mycol.find_one(
81 | { "_id": user_id },
82 | { "_id": 0, "group_details": 0 }
83 | )
84 | return query is not None and query['active_group'] == group_id
85 |
86 |
87 | async def make_active(user_id, group_id):
88 | update = mycol.update_one(
89 | {'_id': user_id},
90 | {"$set": {"active_group" : group_id}}
91 | )
92 | return update.modified_count != 0
93 |
94 |
95 | async def make_inactive(user_id):
96 | update = mycol.update_one(
97 | {'_id': user_id},
98 | {"$set": {"active_group" : None}}
99 | )
100 | return update.modified_count != 0
101 |
102 |
103 | async def delete_connection(user_id, group_id):
104 |
105 | try:
106 | update = mycol.update_one(
107 | {"_id": user_id},
108 | {"$pull" : { "group_details" : {"group_id":group_id} } }
109 | )
110 | if update.modified_count == 0:
111 | return False
112 | query = mycol.find_one(
113 | { "_id": user_id },
114 | { "_id": 0 }
115 | )
116 | if len(query["group_details"]) >= 1:
117 | if query['active_group'] == group_id:
118 | prvs_group_id = query["group_details"][len(query["group_details"]) - 1]["group_id"]
119 |
120 | mycol.update_one(
121 | {'_id': user_id},
122 | {"$set": {"active_group" : prvs_group_id}}
123 | )
124 | else:
125 | mycol.update_one(
126 | {'_id': user_id},
127 | {"$set": {"active_group" : None}}
128 | )
129 | return True
130 | except Exception as e:
131 | logger.exception(f'Some error occurred! {e}', exc_info=True)
132 | return False
133 |
134 |
--------------------------------------------------------------------------------
/Script.py:
--------------------------------------------------------------------------------
1 | class script(object):
2 | START_TXT = """𝙷𝙴𝙻𝙾 {},
3 | 𝙼𝚈 𝙽𝙰𝙼𝙴 𝙸𝚂 {}, 𝙸 𝙲𝙰𝙽 𝙿𝚁𝙾𝚅𝙸𝙳𝙴 𝙼𝙾𝚅𝙸𝙴𝚂, 𝙹𝚄𝚂𝚃 𝙰𝙳𝙳 𝙼𝙴 𝚃𝙾 𝚈𝙾𝚄𝚁 𝙶𝚁𝙾𝚄𝙿 𝙰𝙽𝙳 𝙴𝙽𝙹𝙾𝚈 😍"""
4 | HELP_TXT = """𝙷𝙴𝚈 {}
5 | 𝙷𝙴𝚁𝙴 𝙸𝚂 𝚃𝙷𝙴 𝙷𝙴𝙻𝙿 𝙵𝙾𝚁 𝙼𝚈 𝙲𝙾𝙼𝙼𝙰𝙽𝙳𝚂."""
6 | ABOUT_TXT = """✯ 𝙼𝚈 𝙽𝙰𝙼𝙴: {}
7 | ✯ 𝙲𝚁𝙴𝙰𝚃𝙾𝚁: Team Eva Maria
8 | ✯ 𝙻𝙸𝙱𝚁𝙰𝚁𝚈: 𝙿𝚈𝚁𝙾𝙶𝚁𝙰𝙼
9 | ✯ 𝙻𝙰𝙽𝙶𝚄𝙰𝙶𝙴: 𝙿𝚈𝚃𝙷𝙾𝙽 𝟹
10 | ✯ 𝙳𝙰𝚃𝙰 𝙱𝙰𝚂𝙴: 𝙼𝙾𝙽𝙶𝙾 𝙳𝙱
11 | ✯ 𝙱𝙾𝚃 𝚂𝙴𝚁𝚅𝙴𝚁: 𝙷𝙴𝚁𝙾𝙺𝚄
12 | ✯ 𝙱𝚄𝙸𝙻𝙳 𝚂𝚃𝙰𝚃𝚄𝚂: v1.0.1 [ 𝙱𝙴𝚃𝙰 ]"""
13 | SOURCE_TXT = """NOTE:
14 | - Eva Maria is a open source project.
15 | - Source - https://github.com/EvamariaTG/EvaMaria
16 |
17 | DEVS:
18 | - Team Eva Maria"""
19 | MANUELFILTER_TXT = """Help: Filters
20 |
21 | - Filter is the feature were users can set automated replies for a particular keyword and EvaMaria will respond whenever a keyword is found the message
22 |
23 | NOTE:
24 | 1. eva maria should have admin privillage.
25 | 2. only admins can add filters in a chat.
26 | 3. alert buttons have a limit of 64 characters.
27 |
28 | Commands and Usage:
29 | • /filter - add a filter in chat
30 | • /filters - list all the filters of a chat
31 | • /del - delete a specific filter in chat
32 | • /delall - delete the whole filters in a chat (chat owner only)"""
33 | BUTTON_TXT = """Help: Buttons
34 |
35 | - Eva Maria Supports both url and alert inline buttons.
36 |
37 | NOTE:
38 | 1. Telegram will not allows you to send buttons without any content, so content is mandatory.
39 | 2. Eva Maria supports buttons with any telegram media type.
40 | 3. Buttons should be properly parsed as markdown format
41 |
42 | URL buttons:
43 | [Button Text](buttonurl:https://t.me/EvaMariaBot)
44 |
45 | Alert buttons:
46 | [Button Text](buttonalert:This is an alert message)"""
47 | AUTOFILTER_TXT = """Help: Auto Filter
48 |
49 | NOTE:
50 | 1. Make me the admin of your channel if it's private.
51 | 2. make sure that your channel does not contains camrips, porn and fake files.
52 | 3. Forward the last message to me with quotes.
53 | I'll add all the files in that channel to my db."""
54 | CONNECTION_TXT = """Help: Connections
55 |
56 | - Used to connect bot to PM for managing filters
57 | - it helps to avoid spamming in groups.
58 |
59 | NOTE:
60 | 1. Only admins can add a connection.
61 | 2. Send /connect for connecting me to ur PM
62 |
63 | Commands and Usage:
64 | • /connect - connect a particular chat to your PM
65 | • /disconnect - disconnect from a chat
66 | • /connections - list all your connections"""
67 | EXTRAMOD_TXT = """Help: Extra Modules
68 |
69 | NOTE:
70 | these are the extra features of Eva Maria
71 |
72 | Commands and Usage:
73 | • /id - get id of a specified user.
74 | • /info - get information about a user.
75 | • /imdb - get the film information from IMDb source.
76 | • /search - get the film information from various sources."""
77 | ADMIN_TXT = """Help: Admin mods
78 |
79 | NOTE:
80 | This module only works for my admins
81 |
82 | Commands and Usage:
83 | • /logs - to get the rescent errors
84 | • /stats - to get status of files in db.
85 | • /delete - to delete a specific file from db.
86 | • /users - to get list of my users and ids.
87 | • /chats - to get list of the my chats and ids
88 | • /leave - to leave from a chat.
89 | • /disable - do disable a chat.
90 | • /ban - to ban a user.
91 | • /unban - to unban a user.
92 | • /channel - to get list of total connected channels
93 | • /broadcast - to broadcast a message to all users"""
94 | STATUS_TXT = """★ 𝚃𝙾𝚃𝙰𝙻 𝙵𝙸𝙻𝙴𝚂: {}
95 | ★ 𝚃𝙾𝚃𝙰𝙻 𝚄𝚂𝙴𝚁𝚂: {}
96 | ★ 𝚃𝙾𝚃𝙰𝙻 𝙲𝙷𝙰𝚃𝚂: {}
97 | ★ 𝚄𝚂𝙴𝙳 𝚂𝚃𝙾𝚁𝙰𝙶𝙴: {} 𝙼𝚒𝙱
98 | ★ 𝙵𝚁𝙴𝙴 𝚂𝚃𝙾𝚁𝙰𝙶𝙴: {} 𝙼𝚒𝙱"""
99 | LOG_TEXT_G = """#NewGroup
100 | Group = {}({})
101 | Total Members = {}
102 | Added By - {}
103 | """
104 | LOG_TEXT_P = """#NewUser
105 | ID - {}
106 | Name - {}
107 | """
108 |
--------------------------------------------------------------------------------
/plugins/inline.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from pyrogram import Client, emoji, filters
3 | from pyrogram.errors.exceptions.bad_request_400 import QueryIdInvalid
4 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultCachedDocument, InlineQuery
5 | from database.ia_filterdb import get_search_results
6 | from utils import is_subscribed, get_size, temp
7 | from info import CACHE_TIME, AUTH_USERS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION
8 |
9 | logger = logging.getLogger(__name__)
10 | cache_time = 0 if AUTH_USERS or AUTH_CHANNEL else CACHE_TIME
11 |
12 | async def inline_users(query: InlineQuery):
13 | if AUTH_USERS:
14 | if query.from_user and query.from_user.id in AUTH_USERS:
15 | return True
16 | else:
17 | return False
18 | if query.from_user and query.from_user.id not in temp.BANNED_USERS:
19 | return True
20 | return False
21 |
22 | @Client.on_inline_query()
23 | async def answer(bot, query):
24 | """Show search results for given inline query"""
25 |
26 | if not await inline_users(query):
27 | await query.answer(results=[],
28 | cache_time=0,
29 | switch_pm_text='okDa',
30 | switch_pm_parameter="hehe")
31 | return
32 |
33 | if AUTH_CHANNEL and not await is_subscribed(bot, query):
34 | await query.answer(results=[],
35 | cache_time=0,
36 | switch_pm_text='You have to subscribe my channel to use the bot',
37 | switch_pm_parameter="subscribe")
38 | return
39 |
40 | results = []
41 | if '|' in query.query:
42 | string, file_type = query.query.split('|', maxsplit=1)
43 | string = string.strip()
44 | file_type = file_type.strip().lower()
45 | else:
46 | string = query.query.strip()
47 | file_type = None
48 |
49 | offset = int(query.offset or 0)
50 | reply_markup = get_reply_markup(query=string)
51 | files, next_offset, total = await get_search_results(string,
52 | file_type=file_type,
53 | max_results=10,
54 | offset=offset)
55 |
56 | for file in files:
57 | title=file.file_name
58 | size=get_size(file.file_size)
59 | f_caption=file.caption
60 | if CUSTOM_FILE_CAPTION:
61 | try:
62 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
63 | except Exception as e:
64 | logger.exception(e)
65 | f_caption=f_caption
66 | if f_caption is None:
67 | f_caption = f"{file.file_name}"
68 | results.append(
69 | InlineQueryResultCachedDocument(
70 | title=file.file_name,
71 | document_file_id=file.file_id,
72 | caption=f_caption,
73 | description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}',
74 | reply_markup=reply_markup))
75 |
76 | if results:
77 | switch_pm_text = f"{emoji.FILE_FOLDER} Results - {total}"
78 | if string:
79 | switch_pm_text += f" for {string}"
80 | try:
81 | await query.answer(results=results,
82 | is_personal = True,
83 | cache_time=cache_time,
84 | switch_pm_text=switch_pm_text,
85 | switch_pm_parameter="start",
86 | next_offset=str(next_offset))
87 | except QueryIdInvalid:
88 | pass
89 | except Exception as e:
90 | logging.exception(str(e))
91 | else:
92 | switch_pm_text = f'{emoji.CROSS_MARK} No results'
93 | if string:
94 | switch_pm_text += f' for "{string}"'
95 |
96 | await query.answer(results=[],
97 | is_personal = True,
98 | cache_time=cache_time,
99 | switch_pm_text=switch_pm_text,
100 | switch_pm_parameter="okay")
101 |
102 |
103 | def get_reply_markup(query):
104 | buttons = [
105 | [
106 | InlineKeyboardButton('Search again', switch_inline_query_current_chat=query)
107 | ]
108 | ]
109 | return InlineKeyboardMarkup(buttons)
110 |
111 |
112 |
113 |
114 |
--------------------------------------------------------------------------------
/database/users_chats_db.py:
--------------------------------------------------------------------------------
1 | # https://github.com/odysseusmax/animated-lamp/blob/master/bot/database/database.py
2 | import motor.motor_asyncio
3 | from info import DATABASE_NAME, DATABASE_URI, IMDB, IMDB_TEMPLATE, MELCOW_NEW_USERS, P_TTI_SHOW_OFF, SINGLE_BUTTON, SPELL_CHECK_REPLY, PROTECT_CONTENT
4 |
5 | class Database:
6 |
7 | def __init__(self, uri, database_name):
8 | self._client = motor.motor_asyncio.AsyncIOMotorClient(uri)
9 | self.db = self._client[database_name]
10 | self.col = self.db.users
11 | self.grp = self.db.groups
12 |
13 |
14 | def new_user(self, id, name):
15 | return dict(
16 | id = id,
17 | name = name,
18 | ban_status=dict(
19 | is_banned=False,
20 | ban_reason="",
21 | ),
22 | )
23 |
24 |
25 | def new_group(self, id, title):
26 | return dict(
27 | id = id,
28 | title = title,
29 | chat_status=dict(
30 | is_disabled=False,
31 | reason="",
32 | ),
33 | )
34 |
35 | async def add_user(self, id, name):
36 | user = self.new_user(id, name)
37 | await self.col.insert_one(user)
38 |
39 | async def is_user_exist(self, id):
40 | user = await self.col.find_one({'id':int(id)})
41 | return bool(user)
42 |
43 | async def total_users_count(self):
44 | count = await self.col.count_documents({})
45 | return count
46 |
47 | async def remove_ban(self, id):
48 | ban_status = dict(
49 | is_banned=False,
50 | ban_reason=''
51 | )
52 | await self.col.update_one({'id': id}, {'$set': {'ban_status': ban_status}})
53 |
54 | async def ban_user(self, user_id, ban_reason="No Reason"):
55 | ban_status = dict(
56 | is_banned=True,
57 | ban_reason=ban_reason
58 | )
59 | await self.col.update_one({'id': user_id}, {'$set': {'ban_status': ban_status}})
60 |
61 | async def get_ban_status(self, id):
62 | default = dict(
63 | is_banned=False,
64 | ban_reason=''
65 | )
66 | user = await self.col.find_one({'id':int(id)})
67 | if not user:
68 | return default
69 | return user.get('ban_status', default)
70 |
71 | async def get_all_users(self):
72 | return self.col.find({})
73 |
74 |
75 | async def delete_user(self, user_id):
76 | await self.col.delete_many({'id': int(user_id)})
77 |
78 |
79 | async def get_banned(self):
80 | users = self.col.find({'ban_status.is_banned': True})
81 | chats = self.grp.find({'chat_status.is_disabled': True})
82 | b_chats = [chat['id'] async for chat in chats]
83 | b_users = [user['id'] async for user in users]
84 | return b_users, b_chats
85 |
86 |
87 |
88 | async def add_chat(self, chat, title):
89 | chat = self.new_group(chat, title)
90 | await self.grp.insert_one(chat)
91 |
92 |
93 | async def get_chat(self, chat):
94 | chat = await self.grp.find_one({'id':int(chat)})
95 | return False if not chat else chat.get('chat_status')
96 |
97 |
98 | async def re_enable_chat(self, id):
99 | chat_status=dict(
100 | is_disabled=False,
101 | reason="",
102 | )
103 | await self.grp.update_one({'id': int(id)}, {'$set': {'chat_status': chat_status}})
104 |
105 | async def update_settings(self, id, settings):
106 | await self.grp.update_one({'id': int(id)}, {'$set': {'settings': settings}})
107 |
108 |
109 | async def get_settings(self, id):
110 | default = {
111 | 'button': SINGLE_BUTTON,
112 | 'botpm': P_TTI_SHOW_OFF,
113 | 'file_secure': PROTECT_CONTENT,
114 | 'imdb': IMDB,
115 | 'spell_check': SPELL_CHECK_REPLY,
116 | 'welcome': MELCOW_NEW_USERS,
117 | 'template': IMDB_TEMPLATE
118 | }
119 | chat = await self.grp.find_one({'id':int(id)})
120 | if chat:
121 | return chat.get('settings', default)
122 | return default
123 |
124 |
125 | async def disable_chat(self, chat, reason="No Reason"):
126 | chat_status=dict(
127 | is_disabled=True,
128 | reason=reason,
129 | )
130 | await self.grp.update_one({'id': int(chat)}, {'$set': {'chat_status': chat_status}})
131 |
132 |
133 | async def total_chat_count(self):
134 | count = await self.grp.count_documents({})
135 | return count
136 |
137 |
138 | async def get_all_chats(self):
139 | return self.grp.find({})
140 |
141 |
142 | async def get_db_size(self):
143 | return (await self.db.command("dbstats"))['dataSize']
144 |
145 |
146 | db = Database(DATABASE_URI, DATABASE_NAME)
147 |
--------------------------------------------------------------------------------
/database/ia_filterdb.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from struct import pack
3 | import re
4 | import base64
5 | from pyrogram.file_id import FileId
6 | from pymongo.errors import DuplicateKeyError
7 | from umongo import Instance, Document, fields
8 | from motor.motor_asyncio import AsyncIOMotorClient
9 | from marshmallow.exceptions import ValidationError
10 | from info import DATABASE_URI, DATABASE_NAME, COLLECTION_NAME, USE_CAPTION_FILTER
11 |
12 | logger = logging.getLogger(__name__)
13 | logger.setLevel(logging.INFO)
14 |
15 |
16 | client = AsyncIOMotorClient(DATABASE_URI)
17 | db = client[DATABASE_NAME]
18 | instance = Instance.from_db(db)
19 |
20 | @instance.register
21 | class Media(Document):
22 | file_id = fields.StrField(attribute='_id')
23 | file_ref = fields.StrField(allow_none=True)
24 | file_name = fields.StrField(required=True)
25 | file_size = fields.IntField(required=True)
26 | file_type = fields.StrField(allow_none=True)
27 | mime_type = fields.StrField(allow_none=True)
28 | caption = fields.StrField(allow_none=True)
29 |
30 | class Meta:
31 | indexes = ('$file_name', )
32 | collection_name = COLLECTION_NAME
33 |
34 |
35 | async def save_file(media):
36 | """Save file in database"""
37 |
38 | # TODO: Find better way to get same file_id for same media to avoid duplicates
39 | file_id, file_ref = unpack_new_file_id(media.file_id)
40 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
41 | try:
42 | file = Media(
43 | file_id=file_id,
44 | file_ref=file_ref,
45 | file_name=file_name,
46 | file_size=media.file_size,
47 | file_type=media.file_type,
48 | mime_type=media.mime_type,
49 | caption=media.caption.html if media.caption else None,
50 | )
51 | except ValidationError:
52 | logger.exception('Error occurred while saving file in database')
53 | return False, 2
54 | else:
55 | try:
56 | await file.commit()
57 | except DuplicateKeyError:
58 | logger.warning(
59 | f'{getattr(media, "file_name", "NO_FILE")} is already saved in database'
60 | )
61 |
62 | return False, 0
63 | else:
64 | logger.info(f'{getattr(media, "file_name", "NO_FILE")} is saved to database')
65 | return True, 1
66 |
67 |
68 |
69 | async def get_search_results(query, file_type=None, max_results=10, offset=0, filter=False):
70 | """For given query return (results, next_offset)"""
71 |
72 | query = query.strip()
73 | #if filter:
74 | #better ?
75 | #query = query.replace(' ', r'(\s|\.|\+|\-|_)')
76 | #raw_pattern = r'(\s|_|\-|\.|\+)' + query + r'(\s|_|\-|\.|\+)'
77 | if not query:
78 | raw_pattern = '.'
79 | elif ' ' not in query:
80 | raw_pattern = r'(\b|[\.\+\-_])' + query + r'(\b|[\.\+\-_])'
81 | else:
82 | raw_pattern = query.replace(' ', r'.*[\s\.\+\-_]')
83 |
84 | try:
85 | regex = re.compile(raw_pattern, flags=re.IGNORECASE)
86 | except:
87 | return []
88 |
89 | if USE_CAPTION_FILTER:
90 | filter = {'$or': [{'file_name': regex}, {'caption': regex}]}
91 | else:
92 | filter = {'file_name': regex}
93 |
94 | if file_type:
95 | filter['file_type'] = file_type
96 |
97 | total_results = await Media.count_documents(filter)
98 | next_offset = offset + max_results
99 |
100 | if next_offset > total_results:
101 | next_offset = ''
102 |
103 | cursor = Media.find(filter)
104 | # Sort by recent
105 | cursor.sort('$natural', -1)
106 | # Slice files according to offset and max results
107 | cursor.skip(offset).limit(max_results)
108 | # Get list of files
109 | files = await cursor.to_list(length=max_results)
110 |
111 | return files, next_offset, total_results
112 |
113 |
114 |
115 | async def get_file_details(query):
116 | filter = {'file_id': query}
117 | cursor = Media.find(filter)
118 | filedetails = await cursor.to_list(length=1)
119 | return filedetails
120 |
121 |
122 | def encode_file_id(s: bytes) -> str:
123 | r = b""
124 | n = 0
125 |
126 | for i in s + bytes([22]) + bytes([4]):
127 | if i == 0:
128 | n += 1
129 | else:
130 | if n:
131 | r += b"\x00" + bytes([n])
132 | n = 0
133 |
134 | r += bytes([i])
135 |
136 | return base64.urlsafe_b64encode(r).decode().rstrip("=")
137 |
138 |
139 | def encode_file_ref(file_ref: bytes) -> str:
140 | return base64.urlsafe_b64encode(file_ref).decode().rstrip("=")
141 |
142 |
143 | def unpack_new_file_id(new_file_id):
144 | """Return file_id, file_ref"""
145 | decoded = FileId.decode(new_file_id)
146 | file_id = encode_file_id(
147 | pack(
148 | "/batch https://t.me/TeamEvamaria/10 https://t.me/TeamEvamaria/20.")
44 | links = message.text.strip().split(" ")
45 | if len(links) != 3:
46 | return await message.reply("Use correct format.\nExample /batch https://t.me/TeamEvamaria/10 https://t.me/TeamEvamaria/20.")
47 | cmd, first, last = links
48 | regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")
49 | match = regex.match(first)
50 | if not match:
51 | return await message.reply('Invalid link')
52 | f_chat_id = match.group(4)
53 | f_msg_id = int(match.group(5))
54 | if f_chat_id.isnumeric():
55 | f_chat_id = int(("-100" + f_chat_id))
56 |
57 | match = regex.match(last)
58 | if not match:
59 | return await message.reply('Invalid link')
60 | l_chat_id = match.group(4)
61 | l_msg_id = int(match.group(5))
62 | if l_chat_id.isnumeric():
63 | l_chat_id = int(("-100" + l_chat_id))
64 |
65 | if f_chat_id != l_chat_id:
66 | return await message.reply("Chat ids not matched.")
67 | try:
68 | chat_id = (await bot.get_chat(f_chat_id)).id
69 | except ChannelInvalid:
70 | return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.')
71 | except (UsernameInvalid, UsernameNotModified):
72 | return await message.reply('Invalid Link specified.')
73 | except Exception as e:
74 | return await message.reply(f'Errors - {e}')
75 |
76 | sts = await message.reply("Generating link for your message.\nThis may take time depending upon number of messages")
77 | if chat_id in FILE_STORE_CHANNEL:
78 | string = f"{f_msg_id}_{l_msg_id}_{chat_id}_{cmd.lower().strip()}"
79 | b_64 = base64.urlsafe_b64encode(string.encode("ascii")).decode().strip("=")
80 | return await sts.edit(f"Here is your link https://t.me/{temp.U_NAME}?start=DSTORE-{b_64}")
81 |
82 | FRMT = "Generating Link...\nTotal Messages: `{total}`\nDone: `{current}`\nRemaining: `{rem}`\nStatus: `{sts}`"
83 |
84 | outlist = []
85 |
86 | # file store without db channel
87 | og_msg = 0
88 | tot = 0
89 | async for msg in bot.iter_messages(f_chat_id, l_msg_id, f_msg_id):
90 | tot += 1
91 | if msg.empty or msg.service:
92 | continue
93 | if not msg.media:
94 | # only media messages supported.
95 | continue
96 | try:
97 | file_type = msg.media
98 | file = getattr(msg, file_type.value)
99 | caption = getattr(msg, 'caption', '')
100 | if caption:
101 | caption = caption.html
102 | if file:
103 | file = {
104 | "file_id": file.file_id,
105 | "caption": caption,
106 | "title": getattr(file, "file_name", ""),
107 | "size": file.file_size,
108 | "protect": cmd.lower().strip() == "/pbatch",
109 | }
110 |
111 | og_msg +=1
112 | outlist.append(file)
113 | except:
114 | pass
115 | if not og_msg % 20:
116 | try:
117 | await sts.edit(FRMT.format(total=l_msg_id-f_msg_id, current=tot, rem=((l_msg_id-f_msg_id) - tot), sts="Saving Messages"))
118 | except:
119 | pass
120 | with open(f"batchmode_{message.from_user.id}.json", "w+") as out:
121 | json.dump(outlist, out)
122 | post = await bot.send_document(LOG_CHANNEL, f"batchmode_{message.from_user.id}.json", file_name="Batch.json", caption="⚠️Generated for filestore.")
123 | os.remove(f"batchmode_{message.from_user.id}.json")
124 | file_id, ref = unpack_new_file_id(post.document.file_id)
125 | await sts.edit(f"Here is your link\nContains `{og_msg}` files.\n https://t.me/{temp.U_NAME}?start=BATCH-{file_id}")
126 |
--------------------------------------------------------------------------------
/plugins/connection.py:
--------------------------------------------------------------------------------
1 | from pyrogram import filters, Client, enums
2 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
3 | from database.connections_mdb import add_connection, all_connections, if_active, delete_connection
4 | from info import ADMINS
5 | import logging
6 |
7 | logger = logging.getLogger(__name__)
8 | logger.setLevel(logging.ERROR)
9 |
10 |
11 | @Client.on_message((filters.private | filters.group) & filters.command('connect'))
12 | async def addconnection(client, message):
13 | userid = message.from_user.id if message.from_user else None
14 | if not userid:
15 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
16 | chat_type = message.chat.type
17 |
18 | if chat_type == enums.ChatType.PRIVATE:
19 | try:
20 | cmd, group_id = message.text.split(" ", 1)
21 | except:
22 | await message.reply_text(
23 | "Enter in correct format!\n\n"
24 | "/connect groupid\n\n"
25 | "Get your Group id by adding this bot to your group and use /id",
26 | quote=True
27 | )
28 | return
29 |
30 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
31 | group_id = message.chat.id
32 |
33 | try:
34 | st = await client.get_chat_member(group_id, userid)
35 | if (
36 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
37 | and st.status != enums.ChatMemberStatus.OWNER
38 | and userid not in ADMINS
39 | ):
40 | await message.reply_text("You should be an admin in Given group!", quote=True)
41 | return
42 | except Exception as e:
43 | logger.exception(e)
44 | await message.reply_text(
45 | "Invalid Group ID!\n\nIf correct, Make sure I'm present in your group!!",
46 | quote=True,
47 | )
48 |
49 | return
50 | try:
51 | st = await client.get_chat_member(group_id, "me")
52 | if st.status == enums.ChatMemberStatus.ADMINISTRATOR:
53 | ttl = await client.get_chat(group_id)
54 | title = ttl.title
55 |
56 | addcon = await add_connection(str(group_id), str(userid))
57 | if addcon:
58 | await message.reply_text(
59 | f"Successfully connected to **{title}**\nNow manage your group from my pm !",
60 | quote=True,
61 | parse_mode=enums.ParseMode.MARKDOWN
62 | )
63 | if chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
64 | await client.send_message(
65 | userid,
66 | f"Connected to **{title}** !",
67 | parse_mode=enums.ParseMode.MARKDOWN
68 | )
69 | else:
70 | await message.reply_text(
71 | "You're already connected to this chat!",
72 | quote=True
73 | )
74 | else:
75 | await message.reply_text("Add me as an admin in group", quote=True)
76 | except Exception as e:
77 | logger.exception(e)
78 | await message.reply_text('Some error occurred! Try again later.', quote=True)
79 | return
80 |
81 |
82 | @Client.on_message((filters.private | filters.group) & filters.command('disconnect'))
83 | async def deleteconnection(client, message):
84 | userid = message.from_user.id if message.from_user else None
85 | if not userid:
86 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
87 | chat_type = message.chat.type
88 |
89 | if chat_type == enums.ChatType.PRIVATE:
90 | await message.reply_text("Run /connections to view or disconnect from groups!", quote=True)
91 |
92 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
93 | group_id = message.chat.id
94 |
95 | st = await client.get_chat_member(group_id, userid)
96 | if (
97 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
98 | and st.status != enums.ChatMemberStatus.OWNER
99 | and str(userid) not in ADMINS
100 | ):
101 | return
102 |
103 | delcon = await delete_connection(str(userid), str(group_id))
104 | if delcon:
105 | await message.reply_text("Successfully disconnected from this chat", quote=True)
106 | else:
107 | await message.reply_text("This chat isn't connected to me!\nDo /connect to connect.", quote=True)
108 |
109 |
110 | @Client.on_message(filters.private & filters.command(["connections"]))
111 | async def connections(client, message):
112 | userid = message.from_user.id
113 |
114 | groupids = await all_connections(str(userid))
115 | if groupids is None:
116 | await message.reply_text(
117 | "There are no active connections!! Connect to some groups first.",
118 | quote=True
119 | )
120 | return
121 | buttons = []
122 | for groupid in groupids:
123 | try:
124 | ttl = await client.get_chat(int(groupid))
125 | title = ttl.title
126 | active = await if_active(str(userid), str(groupid))
127 | act = " - ACTIVE" if active else ""
128 | buttons.append(
129 | [
130 | InlineKeyboardButton(
131 | text=f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}"
132 | )
133 | ]
134 | )
135 | except:
136 | pass
137 | if buttons:
138 | await message.reply_text(
139 | "Your connected group details ;\n\n",
140 | reply_markup=InlineKeyboardMarkup(buttons),
141 | quote=True
142 | )
143 | else:
144 | await message.reply_text(
145 | "There are no active connections!! Connect to some groups first.",
146 | quote=True
147 | )
148 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
3 |
5 | Eva Maria Bot
6 |
7 |
8 |
9 | [](https://github.com/EvamariaTG/EvaMaria/stargazers)
10 | [](https://github.com/EvamariaTG/EvaMaria/fork)
11 | [](https://github.com/EvamariaTG/EvaMaria/)
12 | [](https://github.com/EvamariaTG/EvaMaria)
13 | [](https://github.com/EvamariaTG/EvaMaria/graphs/contributors)
14 | [](https://github.com/EvamariaTG/EvaMaria/blob/main/LICENSE)
15 | [](https://stars.medv.io/EvamariaTG/EvaMaria)
16 |
17 |
18 | ## Features
19 |
20 | - [x] Auto Filter
21 | - [x] Manual Filter
22 | - [x] IMDB
23 | - [x] Admin Commands
24 | - [x] Broadcast
25 | - [x] Index
26 | - [x] IMDB search
27 | - [x] Inline Search
28 | - [x] Random pics
29 | - [x] ids and User info
30 | - [x] Stats, Users, Chats, Ban, Unban, Leave, Disable, Channel
31 | - [x] Spelling Check Feature
32 | - [x] File Store
33 | ## Variables
34 |
35 | Read [this](https://telegram.dog/TeamEvamaria/12) before you start messing up with your edits.
36 |
37 | ### Required Variables
38 | * `BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token.
39 | * `API_ID`: Get this value from [telegram.org](https://my.telegram.org/apps)
40 | * `API_HASH`: Get this value from [telegram.org](https://my.telegram.org/apps)
41 | * `CHANNELS`: Username or ID of channel or group. Separate multiple IDs by space
42 | * `ADMINS`: Username or ID of Admin. Separate multiple Admins by space
43 | * `DATABASE_URI`: [mongoDB](https://www.mongodb.com) URI. Get this value from [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/1G1XwEOnxxo)
44 | * `DATABASE_NAME`: Name of the database in [mongoDB](https://www.mongodb.com). For more help watch this [video](https://youtu.be/1G1XwEOnxxo)
45 | * `LOG_CHANNEL` : A channel to log the activities of bot. Make sure bot is an admin in the channel.
46 | ### Optional Variables
47 | * `PICS`: Telegraph links of images to show in start message.( Multiple images can be used separated by space )
48 | * `FILE_STORE_CHANNEL`: Channel from were file store links of posts should be made.Separate multiple IDs by space
49 | * Check [info.py](https://github.com/EvamariaTG/evamaria/blob/master/info.py) for more
50 |
51 |
52 | ## Deploy
53 | You can deploy this bot anywhere.
54 |
55 | **[Watch Deploying Tutorial...](https://youtu.be/1G1XwEOnxxo)**
56 |
57 | Deploy To Heroku
58 | Deploy To VPS
67 |
69 | git clone https://github.com/EvamariaTG/evamaria
70 | # Install Packages
71 | pip3 install -U -r requirements.txt
72 | Edit info.py with variables as given below then run bot
73 | python3 bot.py
74 |
75 |
{user_id}\n➲ Data Centre: {dc_id}",
24 | quote=True
25 | )
26 |
27 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
28 | _id = ""
29 | _id += (
30 | "➲ Chat ID: "
31 | f"{message.chat.id}\n"
32 | )
33 | if message.reply_to_message:
34 | _id += (
35 | "➲ User ID: "
36 | f"{message.from_user.id if message.from_user else 'Anonymous'}\n"
37 | "➲ Replied User ID: "
38 | f"{message.reply_to_message.from_user.id if message.reply_to_message.from_user else 'Anonymous'}\n"
39 | )
40 | file_info = get_file_id(message.reply_to_message)
41 | else:
42 | _id += (
43 | "➲ User ID: "
44 | f"{message.from_user.id if message.from_user else 'Anonymous'}\n"
45 | )
46 | file_info = get_file_id(message)
47 | if file_info:
48 | _id += (
49 | f"{file_info.message_type}: "
50 | f"{file_info.file_id}\n"
51 | )
52 | await message.reply_text(
53 | _id,
54 | quote=True
55 | )
56 |
57 | @Client.on_message(filters.command(["info"]))
58 | async def who_is(client, message):
59 | # https://github.com/SpEcHiDe/PyroGramBot/blob/master/pyrobot/plugins/admemes/whois.py#L19
60 | status_message = await message.reply_text(
61 | "`Fetching user info...`"
62 | )
63 | await status_message.edit(
64 | "`Processing user info...`"
65 | )
66 | from_user = None
67 | from_user_id, _ = extract_user(message)
68 | try:
69 | from_user = await client.get_users(from_user_id)
70 | except Exception as error:
71 | await status_message.edit(str(error))
72 | return
73 | if from_user is None:
74 | return await status_message.edit("no valid user_id / message specified")
75 | message_out_str = ""
76 | message_out_str += f"➲First Name: {from_user.first_name}\n"
77 | last_name = from_user.last_name or "None"
78 | message_out_str += f"➲Last Name: {last_name}\n"
79 | message_out_str += f"➲Telegram ID: {from_user.id}\n"
80 | username = from_user.username or "None"
81 | dc_id = from_user.dc_id or "[User Doesn't Have A Valid DP]"
82 | message_out_str += f"➲Data Centre: {dc_id}\n"
83 | message_out_str += f"➲User Name: @{username}\n"
84 | message_out_str += f"➲User 𝖫𝗂𝗇𝗄: Click Here\n"
85 | if message.chat.type in ((enums.ChatType.SUPERGROUP, enums.ChatType.CHANNEL)):
86 | try:
87 | chat_member_p = await message.chat.get_member(from_user.id)
88 | joined_date = (
89 | chat_member_p.joined_date or datetime.now()
90 | ).strftime("%Y.%m.%d %H:%M:%S")
91 | message_out_str += (
92 | "➲Joined this Chat on: "
93 | f"{joined_date}"
94 | "\n"
95 | )
96 | except UserNotParticipant:
97 | pass
98 | chat_photo = from_user.photo
99 | if chat_photo:
100 | local_user_photo = await client.download_media(
101 | message=chat_photo.big_file_id
102 | )
103 | buttons = [[
104 | InlineKeyboardButton('🔐 Close', callback_data='close_data')
105 | ]]
106 | reply_markup = InlineKeyboardMarkup(buttons)
107 | await message.reply_photo(
108 | photo=local_user_photo,
109 | quote=True,
110 | reply_markup=reply_markup,
111 | caption=message_out_str,
112 | parse_mode=enums.ParseMode.HTML,
113 | disable_notification=True
114 | )
115 | os.remove(local_user_photo)
116 | else:
117 | buttons = [[
118 | InlineKeyboardButton('🔐 Close', callback_data='close_data')
119 | ]]
120 | reply_markup = InlineKeyboardMarkup(buttons)
121 | await message.reply_text(
122 | text=message_out_str,
123 | reply_markup=reply_markup,
124 | quote=True,
125 | parse_mode=enums.ParseMode.HTML,
126 | disable_notification=True
127 | )
128 | await status_message.delete()
129 |
130 | @Client.on_message(filters.command(["imdb", 'search']))
131 | async def imdb_search(client, message):
132 | if ' ' in message.text:
133 | k = await message.reply('Searching ImDB')
134 | r, title = message.text.split(None, 1)
135 | movies = await get_poster(title, bulk=True)
136 | if not movies:
137 | return await message.reply("No results Found")
138 | btn = [
139 | [
140 | InlineKeyboardButton(
141 | text=f"{movie.get('title')} - {movie.get('year')}",
142 | callback_data=f"imdb#{movie.movieID}",
143 | )
144 | ]
145 | for movie in movies
146 | ]
147 | await k.edit('Here is what i found on IMDb', reply_markup=InlineKeyboardMarkup(btn))
148 | else:
149 | await message.reply('Give me a movie / series Name')
150 |
151 | @Client.on_callback_query(filters.regex('^imdb'))
152 | async def imdb_callback(bot: Client, quer_y: CallbackQuery):
153 | i, movie = quer_y.data.split('#')
154 | imdb = await get_poster(query=movie, id=True)
155 | btn = [
156 | [
157 | InlineKeyboardButton(
158 | text=f"{imdb.get('title')}",
159 | url=imdb['url'],
160 | )
161 | ]
162 | ]
163 | message = quer_y.message.reply_to_message or quer_y.message
164 | if imdb:
165 | caption = IMDB_TEMPLATE.format(
166 | query = imdb['title'],
167 | title = imdb['title'],
168 | votes = imdb['votes'],
169 | aka = imdb["aka"],
170 | seasons = imdb["seasons"],
171 | box_office = imdb['box_office'],
172 | localized_title = imdb['localized_title'],
173 | kind = imdb['kind'],
174 | imdb_id = imdb["imdb_id"],
175 | cast = imdb["cast"],
176 | runtime = imdb["runtime"],
177 | countries = imdb["countries"],
178 | certificates = imdb["certificates"],
179 | languages = imdb["languages"],
180 | director = imdb["director"],
181 | writer = imdb["writer"],
182 | producer = imdb["producer"],
183 | composer = imdb["composer"],
184 | cinematographer = imdb["cinematographer"],
185 | music_team = imdb["music_team"],
186 | distributors = imdb["distributors"],
187 | release_date = imdb['release_date'],
188 | year = imdb['year'],
189 | genres = imdb['genres'],
190 | poster = imdb['poster'],
191 | plot = imdb['plot'],
192 | rating = imdb['rating'],
193 | url = imdb['url'],
194 | **locals()
195 | )
196 | else:
197 | caption = "No Results"
198 | if imdb.get('poster'):
199 | try:
200 | await quer_y.message.reply_photo(photo=imdb['poster'], caption=caption, reply_markup=InlineKeyboardMarkup(btn))
201 | except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
202 | pic = imdb.get('poster')
203 | poster = pic.replace('.jpg', "._V1_UX360.jpg")
204 | await quer_y.message.reply_photo(photo=poster, caption=caption, reply_markup=InlineKeyboardMarkup(btn))
205 | except Exception as e:
206 | logger.exception(e)
207 | await quer_y.message.reply(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False)
208 | await quer_y.message.delete()
209 | else:
210 | await quer_y.message.edit(caption, reply_markup=InlineKeyboardMarkup(btn), disable_web_page_preview=False)
211 | await quer_y.answer()
212 |
213 |
214 |
215 |
--------------------------------------------------------------------------------
/plugins/index.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import asyncio
3 | from pyrogram import Client, filters, enums
4 | from pyrogram.errors import FloodWait
5 | from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid, ChatAdminRequired, UsernameInvalid, UsernameNotModified
6 | from info import ADMINS
7 | from info import INDEX_REQ_CHANNEL as LOG_CHANNEL
8 | from database.ia_filterdb import save_file
9 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
10 | from utils import temp
11 | import re
12 | logger = logging.getLogger(__name__)
13 | logger.setLevel(logging.INFO)
14 | lock = asyncio.Lock()
15 |
16 |
17 | @Client.on_callback_query(filters.regex(r'^index'))
18 | async def index_files(bot, query):
19 | if query.data.startswith('index_cancel'):
20 | temp.CANCEL = True
21 | return await query.answer("Cancelling Indexing")
22 | _, raju, chat, lst_msg_id, from_user = query.data.split("#")
23 | if raju == 'reject':
24 | await query.message.delete()
25 | await bot.send_message(int(from_user),
26 | f'Your Submission for indexing {chat} has been decliened by our moderators.',
27 | reply_to_message_id=int(lst_msg_id))
28 | return
29 |
30 | if lock.locked():
31 | return await query.answer('Wait until previous process complete.', show_alert=True)
32 | msg = query.message
33 |
34 | await query.answer('Processing...⏳', show_alert=True)
35 | if int(from_user) not in ADMINS:
36 | await bot.send_message(int(from_user),
37 | f'Your Submission for indexing {chat} has been accepted by our moderators and will be added soon.',
38 | reply_to_message_id=int(lst_msg_id))
39 | await msg.edit(
40 | "Starting Indexing",
41 | reply_markup=InlineKeyboardMarkup(
42 | [[InlineKeyboardButton('Cancel', callback_data='index_cancel')]]
43 | )
44 | )
45 | try:
46 | chat = int(chat)
47 | except:
48 | chat = chat
49 | await index_files_to_db(int(lst_msg_id), chat, msg, bot)
50 |
51 |
52 | @Client.on_message((filters.forwarded | (filters.regex("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")) & filters.text ) & filters.private & filters.incoming)
53 | async def send_for_index(bot, message):
54 | if message.text:
55 | regex = re.compile("(https://)?(t\.me/|telegram\.me/|telegram\.dog/)(c/)?(\d+|[a-zA-Z_0-9]+)/(\d+)$")
56 | match = regex.match(message.text)
57 | if not match:
58 | return await message.reply('Invalid link')
59 | chat_id = match.group(4)
60 | last_msg_id = int(match.group(5))
61 | if chat_id.isnumeric():
62 | chat_id = int(("-100" + chat_id))
63 | elif message.forward_from_chat.type == enums.ChatType.CHANNEL:
64 | last_msg_id = message.forward_from_message_id
65 | chat_id = message.forward_from_chat.username or message.forward_from_chat.id
66 | else:
67 | return
68 | try:
69 | await bot.get_chat(chat_id)
70 | except ChannelInvalid:
71 | return await message.reply('This may be a private channel / group. Make me an admin over there to index the files.')
72 | except (UsernameInvalid, UsernameNotModified):
73 | return await message.reply('Invalid Link specified.')
74 | except Exception as e:
75 | logger.exception(e)
76 | return await message.reply(f'Errors - {e}')
77 | try:
78 | k = await bot.get_messages(chat_id, last_msg_id)
79 | except:
80 | return await message.reply('Make Sure That Iam An Admin In The Channel, if channel is private')
81 | if k.empty:
82 | return await message.reply('This may be group and iam not a admin of the group.')
83 |
84 | if message.from_user.id in ADMINS:
85 | buttons = [
86 | [
87 | InlineKeyboardButton('Yes',
88 | callback_data=f'index#accept#{chat_id}#{last_msg_id}#{message.from_user.id}')
89 | ],
90 | [
91 | InlineKeyboardButton('close', callback_data='close_data'),
92 | ]
93 | ]
94 | reply_markup = InlineKeyboardMarkup(buttons)
95 | return await message.reply(
96 | f'Do you Want To Index This Channel/ Group ?\n\nChat ID/ Username: {chat_id}\nLast Message ID: {last_msg_id}',
97 | reply_markup=reply_markup)
98 |
99 | if type(chat_id) is int:
100 | try:
101 | link = (await bot.create_chat_invite_link(chat_id)).invite_link
102 | except ChatAdminRequired:
103 | return await message.reply('Make sure iam an admin in the chat and have permission to invite users.')
104 | else:
105 | link = f"@{message.forward_from_chat.username}"
106 | buttons = [
107 | [
108 | InlineKeyboardButton('Accept Index',
109 | callback_data=f'index#accept#{chat_id}#{last_msg_id}#{message.from_user.id}')
110 | ],
111 | [
112 | InlineKeyboardButton('Reject Index',
113 | callback_data=f'index#reject#{chat_id}#{message.id}#{message.from_user.id}'),
114 | ]
115 | ]
116 | reply_markup = InlineKeyboardMarkup(buttons)
117 | await bot.send_message(LOG_CHANNEL,
118 | f'#IndexRequest\n\nBy : {message.from_user.mention} ({message.from_user.id})\nChat ID/ Username - {chat_id}\nLast Message ID - {last_msg_id}\nInviteLink - {link}',
119 | reply_markup=reply_markup)
120 | await message.reply('ThankYou For the Contribution, Wait For My Moderators to verify the files.')
121 |
122 |
123 | @Client.on_message(filters.command('setskip') & filters.user(ADMINS))
124 | async def set_skip_number(bot, message):
125 | if ' ' in message.text:
126 | _, skip = message.text.split(" ")
127 | try:
128 | skip = int(skip)
129 | except:
130 | return await message.reply("Skip number should be an integer.")
131 | await message.reply(f"Successfully set SKIP number as {skip}")
132 | temp.CURRENT = int(skip)
133 | else:
134 | await message.reply("Give me a skip number")
135 |
136 |
137 | async def index_files_to_db(lst_msg_id, chat, msg, bot):
138 | total_files = 0
139 | duplicate = 0
140 | errors = 0
141 | deleted = 0
142 | no_media = 0
143 | unsupported = 0
144 | async with lock:
145 | try:
146 | current = temp.CURRENT
147 | temp.CANCEL = False
148 | async for message in bot.iter_messages(chat, lst_msg_id, temp.CURRENT):
149 | if temp.CANCEL:
150 | await msg.edit(f"Successfully Cancelled!!\n\nSaved {total_files} files to dataBase!\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}")
151 | break
152 | current += 1
153 | if current % 20 == 0:
154 | can = [[InlineKeyboardButton('Cancel', callback_data='index_cancel')]]
155 | reply = InlineKeyboardMarkup(can)
156 | await msg.edit_text(
157 | text=f"Total messages fetched: {current}\nTotal messages saved: {total_files}\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}",
158 | reply_markup=reply)
159 | if message.empty:
160 | deleted += 1
161 | continue
162 | elif not message.media:
163 | no_media += 1
164 | continue
165 | elif message.media not in [enums.MessageMediaType.VIDEO, enums.MessageMediaType.AUDIO, enums.MessageMediaType.DOCUMENT]:
166 | unsupported += 1
167 | continue
168 | media = getattr(message, message.media.value, None)
169 | if not media:
170 | unsupported += 1
171 | continue
172 | media.file_type = message.media.value
173 | media.caption = message.caption
174 | aynav, vnay = await save_file(media)
175 | if aynav:
176 | total_files += 1
177 | elif vnay == 0:
178 | duplicate += 1
179 | elif vnay == 2:
180 | errors += 1
181 | except Exception as e:
182 | logger.exception(e)
183 | await msg.edit(f'Error: {e}')
184 | else:
185 | await msg.edit(f'Succesfully saved {total_files} to dataBase!\nDuplicate Files Skipped: {duplicate}\nDeleted Messages Skipped: {deleted}\nNon-Media messages skipped: {no_media + unsupported}(Unsupported Media - `{unsupported}` )\nErrors Occurred: {errors}')
186 |
--------------------------------------------------------------------------------
/plugins/filters.py:
--------------------------------------------------------------------------------
1 | import io
2 | from pyrogram import filters, Client, enums
3 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
4 | from database.filters_mdb import(
5 | add_filter,
6 | get_filters,
7 | delete_filter,
8 | count_filters
9 | )
10 |
11 | from database.connections_mdb import active_connection
12 | from utils import get_file_id, parser, split_quotes
13 | from info import ADMINS
14 |
15 |
16 | @Client.on_message(filters.command(['filter', 'add']) & filters.incoming)
17 | async def addfilter(client, message):
18 | userid = message.from_user.id if message.from_user else None
19 | if not userid:
20 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
21 | chat_type = message.chat.type
22 | args = message.text.html.split(None, 1)
23 |
24 | if chat_type == enums.ChatType.PRIVATE:
25 | grpid = await active_connection(str(userid))
26 | if grpid is not None:
27 | grp_id = grpid
28 | try:
29 | chat = await client.get_chat(grpid)
30 | title = chat.title
31 | except:
32 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
33 | return
34 | else:
35 | await message.reply_text("I'm not connected to any groups!", quote=True)
36 | return
37 |
38 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
39 | grp_id = message.chat.id
40 | title = message.chat.title
41 |
42 | else:
43 | return
44 |
45 | st = await client.get_chat_member(grp_id, userid)
46 | if (
47 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
48 | and st.status != enums.ChatMemberStatus.OWNER
49 | and str(userid) not in ADMINS
50 | ):
51 | return
52 |
53 |
54 | if len(args) < 2:
55 | await message.reply_text("Command Incomplete :(", quote=True)
56 | return
57 |
58 | extracted = split_quotes(args[1])
59 | text = extracted[0].lower()
60 |
61 | if not message.reply_to_message and len(extracted) < 2:
62 | await message.reply_text("Add some content to save your filter!", quote=True)
63 | return
64 |
65 | if (len(extracted) >= 2) and not message.reply_to_message:
66 | reply_text, btn, alert = parser(extracted[1], text)
67 | fileid = None
68 | if not reply_text:
69 | await message.reply_text("You cannot have buttons alone, give some text to go with it!", quote=True)
70 | return
71 |
72 | elif message.reply_to_message and message.reply_to_message.reply_markup:
73 | try:
74 | rm = message.reply_to_message.reply_markup
75 | btn = rm.inline_keyboard
76 | msg = get_file_id(message.reply_to_message)
77 | if msg:
78 | fileid = msg.file_id
79 | reply_text = message.reply_to_message.caption.html
80 | else:
81 | reply_text = message.reply_to_message.text.html
82 | fileid = None
83 | alert = None
84 | except:
85 | reply_text = ""
86 | btn = "[]"
87 | fileid = None
88 | alert = None
89 |
90 | elif message.reply_to_message and message.reply_to_message.media:
91 | try:
92 | msg = get_file_id(message.reply_to_message)
93 | fileid = msg.file_id if msg else None
94 | reply_text, btn, alert = parser(extracted[1], text) if message.reply_to_message.sticker else parser(message.reply_to_message.caption.html, text)
95 | except:
96 | reply_text = ""
97 | btn = "[]"
98 | alert = None
99 | elif message.reply_to_message and message.reply_to_message.text:
100 | try:
101 | fileid = None
102 | reply_text, btn, alert = parser(message.reply_to_message.text.html, text)
103 | except:
104 | reply_text = ""
105 | btn = "[]"
106 | alert = None
107 | else:
108 | return
109 |
110 | await add_filter(grp_id, text, reply_text, btn, fileid, alert)
111 |
112 | await message.reply_text(
113 | f"Filter for `{text}` added in **{title}**",
114 | quote=True,
115 | parse_mode=enums.ParseMode.MARKDOWN
116 | )
117 |
118 |
119 | @Client.on_message(filters.command(['viewfilters', 'filters']) & filters.incoming)
120 | async def get_all(client, message):
121 |
122 | chat_type = message.chat.type
123 | userid = message.from_user.id if message.from_user else None
124 | if not userid:
125 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
126 | if chat_type == enums.ChatType.PRIVATE:
127 | grpid = await active_connection(str(userid))
128 | if grpid is not None:
129 | grp_id = grpid
130 | try:
131 | chat = await client.get_chat(grpid)
132 | title = chat.title
133 | except:
134 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
135 | return
136 | else:
137 | await message.reply_text("I'm not connected to any groups!", quote=True)
138 | return
139 |
140 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
141 | grp_id = message.chat.id
142 | title = message.chat.title
143 |
144 | else:
145 | return
146 |
147 | st = await client.get_chat_member(grp_id, userid)
148 | if (
149 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
150 | and st.status != enums.ChatMemberStatus.OWNER
151 | and str(userid) not in ADMINS
152 | ):
153 | return
154 |
155 | texts = await get_filters(grp_id)
156 | count = await count_filters(grp_id)
157 | if count:
158 | filterlist = f"Total number of filters in **{title}** : {count}\n\n"
159 |
160 | for text in texts:
161 | keywords = " × `{}`\n".format(text)
162 |
163 | filterlist += keywords
164 |
165 | if len(filterlist) > 4096:
166 | with io.BytesIO(str.encode(filterlist.replace("`", ""))) as keyword_file:
167 | keyword_file.name = "keywords.txt"
168 | await message.reply_document(
169 | document=keyword_file,
170 | quote=True
171 | )
172 | return
173 | else:
174 | filterlist = f"There are no active filters in **{title}**"
175 |
176 | await message.reply_text(
177 | text=filterlist,
178 | quote=True,
179 | parse_mode=enums.ParseMode.MARKDOWN
180 | )
181 |
182 | @Client.on_message(filters.command('del') & filters.incoming)
183 | async def deletefilter(client, message):
184 | userid = message.from_user.id if message.from_user else None
185 | if not userid:
186 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
187 | chat_type = message.chat.type
188 |
189 | if chat_type == enums.ChatType.PRIVATE:
190 | grpid = await active_connection(str(userid))
191 | if grpid is not None:
192 | grp_id = grpid
193 | try:
194 | chat = await client.get_chat(grpid)
195 | title = chat.title
196 | except:
197 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
198 | return
199 | else:
200 | await message.reply_text("I'm not connected to any groups!", quote=True)
201 | return
202 |
203 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
204 | grp_id = message.chat.id
205 | title = message.chat.title
206 |
207 | else:
208 | return
209 |
210 | st = await client.get_chat_member(grp_id, userid)
211 | if (
212 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
213 | and st.status != enums.ChatMemberStatus.OWNER
214 | and str(userid) not in ADMINS
215 | ):
216 | return
217 |
218 | try:
219 | cmd, text = message.text.split(" ", 1)
220 | except:
221 | await message.reply_text(
222 | "Mention the filtername which you wanna delete!\n\n"
223 | "/del filtername\n\n"
224 | "Use /viewfilters to view all available filters",
225 | quote=True
226 | )
227 | return
228 |
229 | query = text.lower()
230 |
231 | await delete_filter(message, query, grp_id)
232 |
233 |
234 | @Client.on_message(filters.command('delall') & filters.incoming)
235 | async def delallconfirm(client, message):
236 | userid = message.from_user.id if message.from_user else None
237 | if not userid:
238 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
239 | chat_type = message.chat.type
240 |
241 | if chat_type == enums.ChatType.PRIVATE:
242 | grpid = await active_connection(str(userid))
243 | if grpid is not None:
244 | grp_id = grpid
245 | try:
246 | chat = await client.get_chat(grpid)
247 | title = chat.title
248 | except:
249 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
250 | return
251 | else:
252 | await message.reply_text("I'm not connected to any groups!", quote=True)
253 | return
254 |
255 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
256 | grp_id = message.chat.id
257 | title = message.chat.title
258 |
259 | else:
260 | return
261 |
262 |
263 | st = await client.get_chat_member(grp_id, userid)
264 | if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS):
265 | await message.reply_text(
266 | f"This will delete all filters from '{title}'.\nDo you want to continue??",
267 | reply_markup=InlineKeyboardMarkup([
268 | [InlineKeyboardButton(text="YES",callback_data="delallconfirm")],
269 | [InlineKeyboardButton(text="CANCEL",callback_data="delallcancel")]
270 | ]),
271 | quote=True
272 | )
273 |
274 |
--------------------------------------------------------------------------------
/plugins/p_ttishow.py:
--------------------------------------------------------------------------------
1 | from pyrogram import Client, filters, enums
2 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
3 | from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong, PeerIdInvalid
4 | from info import ADMINS, LOG_CHANNEL, SUPPORT_CHAT, MELCOW_NEW_USERS
5 | from database.users_chats_db import db
6 | from database.ia_filterdb import Media
7 | from utils import get_size, temp, get_settings
8 | from Script import script
9 | from pyrogram.errors import ChatAdminRequired
10 |
11 | """-----------------------------------------https://t.me/GetTGLink/4179 --------------------------------------"""
12 |
13 | @Client.on_message(filters.new_chat_members & filters.group)
14 | async def save_group(bot, message):
15 | r_j_check = [u.id for u in message.new_chat_members]
16 | if temp.ME in r_j_check:
17 | if not await db.get_chat(message.chat.id):
18 | total=await bot.get_chat_members_count(message.chat.id)
19 | r_j = message.from_user.mention if message.from_user else "Anonymous"
20 | await bot.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, r_j))
21 | await db.add_chat(message.chat.id, message.chat.title)
22 | if message.chat.id in temp.BANNED_CHATS:
23 | # Inspired from a boat of a banana tree
24 | buttons = [[
25 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
26 | ]]
27 | reply_markup=InlineKeyboardMarkup(buttons)
28 | k = await message.reply(
29 | text='CHAT NOT ALLOWED 🐞\n\nMy admins has restricted me from working here ! If you want to know more about it contact support..',
30 | reply_markup=reply_markup,
31 | )
32 |
33 | try:
34 | await k.pin()
35 | except:
36 | pass
37 | await bot.leave_chat(message.chat.id)
38 | return
39 | buttons = [[
40 | InlineKeyboardButton('ℹ️ Help', url=f"https://t.me/{temp.U_NAME}?start=help"),
41 | InlineKeyboardButton('📢 Updates', url='https://t.me/TeamEvamaria')
42 | ]]
43 | reply_markup=InlineKeyboardMarkup(buttons)
44 | await message.reply_text(
45 | text=f"Thankyou For Adding Me In {message.chat.title} ❣️\n\nIf you have any questions & doubts about using me contact support.",
46 | reply_markup=reply_markup)
47 | else:
48 | settings = await get_settings(message.chat.id)
49 | if settings["welcome"]:
50 | for u in message.new_chat_members:
51 | if (temp.MELCOW).get('welcome') is not None:
52 | try:
53 | await (temp.MELCOW['welcome']).delete()
54 | except:
55 | pass
56 | temp.MELCOW['welcome'] = await message.reply(f"Hey , {u.mention}, Welcome to {message.chat.title}")
57 |
58 |
59 | @Client.on_message(filters.command('leave') & filters.user(ADMINS))
60 | async def leave_a_chat(bot, message):
61 | if len(message.command) == 1:
62 | return await message.reply('Give me a chat id')
63 | chat = message.command[1]
64 | try:
65 | chat = int(chat)
66 | except:
67 | chat = chat
68 | try:
69 | buttons = [[
70 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
71 | ]]
72 | reply_markup=InlineKeyboardMarkup(buttons)
73 | await bot.send_message(
74 | chat_id=chat,
75 | text='Hello Friends, \nMy admin has told me to leave from group so i go! If you wanna add me again contact my support group.',
76 | reply_markup=reply_markup,
77 | )
78 |
79 | await bot.leave_chat(chat)
80 | await message.reply(f"left the chat `{chat}`")
81 | except Exception as e:
82 | await message.reply(f'Error - {e}')
83 |
84 | @Client.on_message(filters.command('disable') & filters.user(ADMINS))
85 | async def disable_chat(bot, message):
86 | if len(message.command) == 1:
87 | return await message.reply('Give me a chat id')
88 | r = message.text.split(None)
89 | if len(r) > 2:
90 | reason = message.text.split(None, 2)[2]
91 | chat = message.text.split(None, 2)[1]
92 | else:
93 | chat = message.command[1]
94 | reason = "No reason Provided"
95 | try:
96 | chat_ = int(chat)
97 | except:
98 | return await message.reply('Give Me A Valid Chat ID')
99 | cha_t = await db.get_chat(int(chat_))
100 | if not cha_t:
101 | return await message.reply("Chat Not Found In DB")
102 | if cha_t['is_disabled']:
103 | return await message.reply(f"This chat is already disabled:\nReason- {cha_t['reason']} ")
104 | await db.disable_chat(int(chat_), reason)
105 | temp.BANNED_CHATS.append(int(chat_))
106 | await message.reply('Chat Successfully Disabled')
107 | try:
108 | buttons = [[
109 | InlineKeyboardButton('Support', url=f'https://t.me/{SUPPORT_CHAT}')
110 | ]]
111 | reply_markup=InlineKeyboardMarkup(buttons)
112 | await bot.send_message(
113 | chat_id=chat_,
114 | text=f'Hello Friends, \nMy admin has told me to leave from group so i go! If you wanna add me again contact my support group. \nReason : {reason}',
115 | reply_markup=reply_markup)
116 | await bot.leave_chat(chat_)
117 | except Exception as e:
118 | await message.reply(f"Error - {e}")
119 |
120 |
121 | @Client.on_message(filters.command('enable') & filters.user(ADMINS))
122 | async def re_enable_chat(bot, message):
123 | if len(message.command) == 1:
124 | return await message.reply('Give me a chat id')
125 | chat = message.command[1]
126 | try:
127 | chat_ = int(chat)
128 | except:
129 | return await message.reply('Give Me A Valid Chat ID')
130 | sts = await db.get_chat(int(chat))
131 | if not sts:
132 | return await message.reply("Chat Not Found In DB !")
133 | if not sts.get('is_disabled'):
134 | return await message.reply('This chat is not yet disabled.')
135 | await db.re_enable_chat(int(chat_))
136 | temp.BANNED_CHATS.remove(int(chat_))
137 | await message.reply("Chat Successfully re-enabled")
138 |
139 |
140 | @Client.on_message(filters.command('stats') & filters.incoming)
141 | async def get_ststs(bot, message):
142 | rju = await message.reply('Fetching stats..')
143 | total_users = await db.total_users_count()
144 | totl_chats = await db.total_chat_count()
145 | files = await Media.count_documents()
146 | size = await db.get_db_size()
147 | free = 536870912 - size
148 | size = get_size(size)
149 | free = get_size(free)
150 | await rju.edit(script.STATUS_TXT.format(files, total_users, totl_chats, size, free))
151 |
152 |
153 | # a function for trespassing into others groups, Inspired by a Vazha
154 | # Not to be used , But Just to showcase his vazhatharam.
155 | # @Client.on_message(filters.command('invite') & filters.user(ADMINS))
156 | async def gen_invite(bot, message):
157 | if len(message.command) == 1:
158 | return await message.reply('Give me a chat id')
159 | chat = message.command[1]
160 | try:
161 | chat = int(chat)
162 | except:
163 | return await message.reply('Give Me A Valid Chat ID')
164 | try:
165 | link = await bot.create_chat_invite_link(chat)
166 | except ChatAdminRequired:
167 | return await message.reply("Invite Link Generation Failed, Iam Not Having Sufficient Rights")
168 | except Exception as e:
169 | return await message.reply(f'Error {e}')
170 | await message.reply(f'Here is your Invite Link {link.invite_link}')
171 |
172 | @Client.on_message(filters.command('ban') & filters.user(ADMINS))
173 | async def ban_a_user(bot, message):
174 | # https://t.me/GetTGLink/4185
175 | if len(message.command) == 1:
176 | return await message.reply('Give me a user id / username')
177 | r = message.text.split(None)
178 | if len(r) > 2:
179 | reason = message.text.split(None, 2)[2]
180 | chat = message.text.split(None, 2)[1]
181 | else:
182 | chat = message.command[1]
183 | reason = "No reason Provided"
184 | try:
185 | chat = int(chat)
186 | except:
187 | pass
188 | try:
189 | k = await bot.get_users(chat)
190 | except PeerIdInvalid:
191 | return await message.reply("This is an invalid user, make sure ia have met him before.")
192 | except IndexError:
193 | return await message.reply("This might be a channel, make sure its a user.")
194 | except Exception as e:
195 | return await message.reply(f'Error - {e}')
196 | else:
197 | jar = await db.get_ban_status(k.id)
198 | if jar['is_banned']:
199 | return await message.reply(f"{k.mention} is already banned\nReason: {jar['ban_reason']}")
200 | await db.ban_user(k.id, reason)
201 | temp.BANNED_USERS.append(k.id)
202 | await message.reply(f"Successfully banned {k.mention}")
203 |
204 |
205 |
206 | @Client.on_message(filters.command('unban') & filters.user(ADMINS))
207 | async def unban_a_user(bot, message):
208 | if len(message.command) == 1:
209 | return await message.reply('Give me a user id / username')
210 | r = message.text.split(None)
211 | if len(r) > 2:
212 | reason = message.text.split(None, 2)[2]
213 | chat = message.text.split(None, 2)[1]
214 | else:
215 | chat = message.command[1]
216 | reason = "No reason Provided"
217 | try:
218 | chat = int(chat)
219 | except:
220 | pass
221 | try:
222 | k = await bot.get_users(chat)
223 | except PeerIdInvalid:
224 | return await message.reply("This is an invalid user, make sure ia have met him before.")
225 | except IndexError:
226 | return await message.reply("Thismight be a channel, make sure its a user.")
227 | except Exception as e:
228 | return await message.reply(f'Error - {e}')
229 | else:
230 | jar = await db.get_ban_status(k.id)
231 | if not jar['is_banned']:
232 | return await message.reply(f"{k.mention} is not yet banned.")
233 | await db.remove_ban(k.id)
234 | temp.BANNED_USERS.remove(k.id)
235 | await message.reply(f"Successfully unbanned {k.mention}")
236 |
237 |
238 |
239 | @Client.on_message(filters.command('users') & filters.user(ADMINS))
240 | async def list_users(bot, message):
241 | # https://t.me/GetTGLink/4184
242 | raju = await message.reply('Getting List Of Users')
243 | users = await db.get_all_users()
244 | out = "Users Saved In DB Are:\n\n"
245 | async for user in users:
246 | out += f"{user['name']}"
247 | if user['ban_status']['is_banned']:
248 | out += '( Banned User )'
249 | out += '\n'
250 | try:
251 | await raju.edit_text(out)
252 | except MessageTooLong:
253 | with open('users.txt', 'w+') as outfile:
254 | outfile.write(out)
255 | await message.reply_document('users.txt', caption="List Of Users")
256 |
257 | @Client.on_message(filters.command('chats') & filters.user(ADMINS))
258 | async def list_chats(bot, message):
259 | raju = await message.reply('Getting List Of chats')
260 | chats = await db.get_all_chats()
261 | out = "Chats Saved In DB Are:\n\n"
262 | async for chat in chats:
263 | out += f"**Title:** `{chat['title']}`\n**- ID:** `{chat['id']}`"
264 | if chat['chat_status']['is_disabled']:
265 | out += '( Disabled Chat )'
266 | out += '\n'
267 | try:
268 | await raju.edit_text(out)
269 | except MessageTooLong:
270 | with open('chats.txt', 'w+') as outfile:
271 | outfile.write(out)
272 | await message.reply_document('chats.txt', caption="List Of Chats")
273 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from pyrogram.errors import InputUserDeactivated, UserNotParticipant, FloodWait, UserIsBlocked, PeerIdInvalid
3 | from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION, MAX_LIST_ELM
4 | from imdb import IMDb
5 | import asyncio
6 | from pyrogram.types import Message, InlineKeyboardButton
7 | from pyrogram import enums
8 | from typing import Union
9 | import re
10 | import os
11 | from datetime import datetime
12 | from typing import List
13 | from database.users_chats_db import db
14 | from bs4 import BeautifulSoup
15 | import requests
16 |
17 | logger = logging.getLogger(__name__)
18 | logger.setLevel(logging.INFO)
19 |
20 | BTN_URL_REGEX = re.compile(
21 | r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))"
22 | )
23 |
24 | imdb = IMDb()
25 |
26 | BANNED = {}
27 | SMART_OPEN = '“'
28 | SMART_CLOSE = '”'
29 | START_CHAR = ('\'', '"', SMART_OPEN)
30 |
31 | # temp db for banned
32 | class temp(object):
33 | BANNED_USERS = []
34 | BANNED_CHATS = []
35 | ME = None
36 | CURRENT=int(os.environ.get("SKIP", 2))
37 | CANCEL = False
38 | MELCOW = {}
39 | U_NAME = None
40 | B_NAME = None
41 | SETTINGS = {}
42 |
43 | async def is_subscribed(bot, query):
44 | try:
45 | user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
46 | except UserNotParticipant:
47 | pass
48 | except Exception as e:
49 | logger.exception(e)
50 | else:
51 | if user.status != 'kicked':
52 | return True
53 |
54 | return False
55 |
56 | async def get_poster(query, bulk=False, id=False, file=None):
57 | if not id:
58 | # https://t.me/GetTGLink/4183
59 | query = (query.strip()).lower()
60 | title = query
61 | year = re.findall(r'[1-2]\d{3}$', query, re.IGNORECASE)
62 | if year:
63 | year = list_to_str(year[:1])
64 | title = (query.replace(year, "")).strip()
65 | elif file is not None:
66 | year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
67 | if year:
68 | year = list_to_str(year[:1])
69 | else:
70 | year = None
71 | movieid = imdb.search_movie(title.lower(), results=10)
72 | if not movieid:
73 | return None
74 | if year:
75 | filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
76 | if not filtered:
77 | filtered = movieid
78 | else:
79 | filtered = movieid
80 | movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
81 | if not movieid:
82 | movieid = filtered
83 | if bulk:
84 | return movieid
85 | movieid = movieid[0].movieID
86 | else:
87 | movieid = query
88 | movie = imdb.get_movie(movieid)
89 | if movie.get("original air date"):
90 | date = movie["original air date"]
91 | elif movie.get("year"):
92 | date = movie.get("year")
93 | else:
94 | date = "N/A"
95 | plot = ""
96 | if not LONG_IMDB_DESCRIPTION:
97 | plot = movie.get('plot')
98 | if plot and len(plot) > 0:
99 | plot = plot[0]
100 | else:
101 | plot = movie.get('plot outline')
102 | if plot and len(plot) > 800:
103 | plot = plot[0:800] + "..."
104 |
105 | return {
106 | 'title': movie.get('title'),
107 | 'votes': movie.get('votes'),
108 | "aka": list_to_str(movie.get("akas")),
109 | "seasons": movie.get("number of seasons"),
110 | "box_office": movie.get('box office'),
111 | 'localized_title': movie.get('localized title'),
112 | 'kind': movie.get("kind"),
113 | "imdb_id": f"tt{movie.get('imdbID')}",
114 | "cast": list_to_str(movie.get("cast")),
115 | "runtime": list_to_str(movie.get("runtimes")),
116 | "countries": list_to_str(movie.get("countries")),
117 | "certificates": list_to_str(movie.get("certificates")),
118 | "languages": list_to_str(movie.get("languages")),
119 | "director": list_to_str(movie.get("director")),
120 | "writer":list_to_str(movie.get("writer")),
121 | "producer":list_to_str(movie.get("producer")),
122 | "composer":list_to_str(movie.get("composer")) ,
123 | "cinematographer":list_to_str(movie.get("cinematographer")),
124 | "music_team": list_to_str(movie.get("music department")),
125 | "distributors": list_to_str(movie.get("distributors")),
126 | 'release_date': date,
127 | 'year': movie.get('year'),
128 | 'genres': list_to_str(movie.get("genres")),
129 | 'poster': movie.get('full-size cover url'),
130 | 'plot': plot,
131 | 'rating': str(movie.get("rating")),
132 | 'url':f'https://www.imdb.com/title/tt{movieid}'
133 | }
134 | # https://github.com/odysseusmax/animated-lamp/blob/2ef4730eb2b5f0596ed6d03e7b05243d93e3415b/bot/utils/broadcast.py#L37
135 |
136 | async def broadcast_messages(user_id, message):
137 | try:
138 | await message.copy(chat_id=user_id)
139 | return True, "Success"
140 | except FloodWait as e:
141 | await asyncio.sleep(e.x)
142 | return await broadcast_messages(user_id, message)
143 | except InputUserDeactivated:
144 | await db.delete_user(int(user_id))
145 | logging.info(f"{user_id}-Removed from Database, since deleted account.")
146 | return False, "Deleted"
147 | except UserIsBlocked:
148 | logging.info(f"{user_id} -Blocked the bot.")
149 | return False, "Blocked"
150 | except PeerIdInvalid:
151 | await db.delete_user(int(user_id))
152 | logging.info(f"{user_id} - PeerIdInvalid")
153 | return False, "Error"
154 | except Exception as e:
155 | return False, "Error"
156 |
157 | async def search_gagala(text):
158 | usr_agent = {
159 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
160 | 'Chrome/61.0.3163.100 Safari/537.36'
161 | }
162 | text = text.replace(" ", '+')
163 | url = f'https://www.google.com/search?q={text}'
164 | response = requests.get(url, headers=usr_agent)
165 | response.raise_for_status()
166 | soup = BeautifulSoup(response.text, 'html.parser')
167 | titles = soup.find_all( 'h3' )
168 | return [title.getText() for title in titles]
169 |
170 |
171 | async def get_settings(group_id):
172 | settings = temp.SETTINGS.get(group_id)
173 | if not settings:
174 | settings = await db.get_settings(group_id)
175 | temp.SETTINGS[group_id] = settings
176 | return settings
177 |
178 | async def save_group_settings(group_id, key, value):
179 | current = await get_settings(group_id)
180 | current[key] = value
181 | temp.SETTINGS[group_id] = current
182 | await db.update_settings(group_id, current)
183 |
184 | def get_size(size):
185 | """Get size in readable format"""
186 |
187 | units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
188 | size = float(size)
189 | i = 0
190 | while size >= 1024.0 and i < len(units):
191 | i += 1
192 | size /= 1024.0
193 | return "%.2f %s" % (size, units[i])
194 |
195 | def split_list(l, n):
196 | for i in range(0, len(l), n):
197 | yield l[i:i + n]
198 |
199 | def get_file_id(msg: Message):
200 | if msg.media:
201 | for message_type in (
202 | "photo",
203 | "animation",
204 | "audio",
205 | "document",
206 | "video",
207 | "video_note",
208 | "voice",
209 | "sticker"
210 | ):
211 | obj = getattr(msg, message_type)
212 | if obj:
213 | setattr(obj, "message_type", message_type)
214 | return obj
215 |
216 | def extract_user(message: Message) -> Union[int, str]:
217 | """extracts the user from a message"""
218 | # https://github.com/SpEcHiDe/PyroGramBot/blob/f30e2cca12002121bad1982f68cd0ff9814ce027/pyrobot/helper_functions/extract_user.py#L7
219 | user_id = None
220 | user_first_name = None
221 | if message.reply_to_message:
222 | user_id = message.reply_to_message.from_user.id
223 | user_first_name = message.reply_to_message.from_user.first_name
224 |
225 | elif len(message.command) > 1:
226 | if (
227 | len(message.entities) > 1 and
228 | message.entities[1].type == enums.MessageEntityType.TEXT_MENTION
229 | ):
230 |
231 | required_entity = message.entities[1]
232 | user_id = required_entity.user.id
233 | user_first_name = required_entity.user.first_name
234 | else:
235 | user_id = message.command[1]
236 | # don't want to make a request -_-
237 | user_first_name = user_id
238 | try:
239 | user_id = int(user_id)
240 | except ValueError:
241 | pass
242 | else:
243 | user_id = message.from_user.id
244 | user_first_name = message.from_user.first_name
245 | return (user_id, user_first_name)
246 |
247 | def list_to_str(k):
248 | if not k:
249 | return "N/A"
250 | elif len(k) == 1:
251 | return str(k[0])
252 | elif MAX_LIST_ELM:
253 | k = k[:int(MAX_LIST_ELM)]
254 | return ' '.join(f'{elem}, ' for elem in k)
255 | else:
256 | return ' '.join(f'{elem}, ' for elem in k)
257 |
258 | def last_online(from_user):
259 | time = ""
260 | if from_user.is_bot:
261 | time += "🤖 Bot :("
262 | elif from_user.status == enums.UserStatus.RECENTLY:
263 | time += "Recently"
264 | elif from_user.status == enums.UserStatus.LAST_WEEK:
265 | time += "Within the last week"
266 | elif from_user.status == enums.UserStatus.LAST_MONTH:
267 | time += "Within the last month"
268 | elif from_user.status == enums.UserStatus.LONG_AGO:
269 | time += "A long time ago :("
270 | elif from_user.status == enums.UserStatus.ONLINE:
271 | time += "Currently Online"
272 | elif from_user.status == enums.UserStatus.OFFLINE:
273 | time += from_user.last_online_date.strftime("%a, %d %b %Y, %H:%M:%S")
274 | return time
275 |
276 |
277 | def split_quotes(text: str) -> List:
278 | if not any(text.startswith(char) for char in START_CHAR):
279 | return text.split(None, 1)
280 | counter = 1 # ignore first char -> is some kind of quote
281 | while counter < len(text):
282 | if text[counter] == "\\":
283 | counter += 1
284 | elif text[counter] == text[0] or (text[0] == SMART_OPEN and text[counter] == SMART_CLOSE):
285 | break
286 | counter += 1
287 | else:
288 | return text.split(None, 1)
289 |
290 | # 1 to avoid starting quote, and counter is exclusive so avoids ending
291 | key = remove_escapes(text[1:counter].strip())
292 | # index will be in range, or `else` would have been executed and returned
293 | rest = text[counter + 1:].strip()
294 | if not key:
295 | key = text[0] + text[0]
296 | return list(filter(None, [key, rest]))
297 |
298 | def parser(text, keyword):
299 | if "buttonalert" in text:
300 | text = (text.replace("\n", "\\n").replace("\t", "\\t"))
301 | buttons = []
302 | note_data = ""
303 | prev = 0
304 | i = 0
305 | alerts = []
306 | for match in BTN_URL_REGEX.finditer(text):
307 | # Check if btnurl is escaped
308 | n_escapes = 0
309 | to_check = match.start(1) - 1
310 | while to_check > 0 and text[to_check] == "\\":
311 | n_escapes += 1
312 | to_check -= 1
313 |
314 | # if even, not escaped -> create button
315 | if n_escapes % 2 == 0:
316 | note_data += text[prev:match.start(1)]
317 | prev = match.end(1)
318 | if match.group(3) == "buttonalert":
319 | # create a thruple with button label, url, and newline status
320 | if bool(match.group(5)) and buttons:
321 | buttons[-1].append(InlineKeyboardButton(
322 | text=match.group(2),
323 | callback_data=f"alertmessage:{i}:{keyword}"
324 | ))
325 | else:
326 | buttons.append([InlineKeyboardButton(
327 | text=match.group(2),
328 | callback_data=f"alertmessage:{i}:{keyword}"
329 | )])
330 | i += 1
331 | alerts.append(match.group(4))
332 | elif bool(match.group(5)) and buttons:
333 | buttons[-1].append(InlineKeyboardButton(
334 | text=match.group(2),
335 | url=match.group(4).replace(" ", "")
336 | ))
337 | else:
338 | buttons.append([InlineKeyboardButton(
339 | text=match.group(2),
340 | url=match.group(4).replace(" ", "")
341 | )])
342 |
343 | else:
344 | note_data += text[prev:to_check]
345 | prev = match.start(1) - 1
346 | else:
347 | note_data += text[prev:]
348 |
349 | try:
350 | return note_data, buttons, alerts
351 | except:
352 | return note_data, buttons, None
353 |
354 | def remove_escapes(text: str) -> str:
355 | res = ""
356 | is_escaped = False
357 | for counter in range(len(text)):
358 | if is_escaped:
359 | res += text[counter]
360 | is_escaped = False
361 | elif text[counter] == "\\":
362 | is_escaped = True
363 | else:
364 | res += text[counter]
365 | return res
366 |
367 |
368 | def humanbytes(size):
369 | if not size:
370 | return ""
371 | power = 2**10
372 | n = 0
373 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
374 | while size > power:
375 | size /= power
376 | n += 1
377 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
378 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {title}"
221 | if CUSTOM_FILE_CAPTION:
222 | try:
223 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='')
224 | except:
225 | return
226 | await msg.edit_caption(f_caption)
227 | return
228 | except:
229 | pass
230 | return await message.reply('No such file exist.')
231 | files = files_[0]
232 | title = files.file_name
233 | size=get_size(files.file_size)
234 | f_caption=files.caption
235 | if CUSTOM_FILE_CAPTION:
236 | try:
237 | f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
238 | except Exception as e:
239 | logger.exception(e)
240 | f_caption=f_caption
241 | if f_caption is None:
242 | f_caption = f"{files.file_name}"
243 | await client.send_cached_media(
244 | chat_id=message.from_user.id,
245 | file_id=file_id,
246 | caption=f_caption,
247 | protect_content=True if pre == 'filep' else False,
248 | )
249 |
250 |
251 | @Client.on_message(filters.command('channel') & filters.user(ADMINS))
252 | async def channel_info(bot, message):
253 |
254 | """Send basic information of channel"""
255 | if isinstance(CHANNELS, (int, str)):
256 | channels = [CHANNELS]
257 | elif isinstance(CHANNELS, list):
258 | channels = CHANNELS
259 | else:
260 | raise ValueError("Unexpected type of CHANNELS")
261 |
262 | text = '📑 **Indexed channels/groups**\n'
263 | for channel in channels:
264 | chat = await bot.get_chat(channel)
265 | if chat.username:
266 | text += '\n@' + chat.username
267 | else:
268 | text += '\n' + chat.title or chat.first_name
269 |
270 | text += f'\n\n**Total:** {len(CHANNELS)}'
271 |
272 | if len(text) < 4096:
273 | await message.reply(text)
274 | else:
275 | file = 'Indexed channels.txt'
276 | with open(file, 'w') as f:
277 | f.write(text)
278 | await message.reply_document(file)
279 | os.remove(file)
280 |
281 |
282 | @Client.on_message(filters.command('logs') & filters.user(ADMINS))
283 | async def log_file(bot, message):
284 | """Send log file"""
285 | try:
286 | await message.reply_document('TelegramBot.log')
287 | except Exception as e:
288 | await message.reply(str(e))
289 |
290 | @Client.on_message(filters.command('delete') & filters.user(ADMINS))
291 | async def delete(bot, message):
292 | """Delete file from database"""
293 | reply = message.reply_to_message
294 | if reply and reply.media:
295 | msg = await message.reply("Processing...⏳", quote=True)
296 | else:
297 | await message.reply('Reply to file with /delete which you want to delete', quote=True)
298 | return
299 |
300 | for file_type in ("document", "video", "audio"):
301 | media = getattr(reply, file_type, None)
302 | if media is not None:
303 | break
304 | else:
305 | await msg.edit('This is not supported file format')
306 | return
307 |
308 | file_id, file_ref = unpack_new_file_id(media.file_id)
309 |
310 | result = await Media.collection.delete_one({
311 | '_id': file_id,
312 | })
313 | if result.deleted_count:
314 | await msg.edit('File is successfully deleted from database')
315 | else:
316 | file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
317 | result = await Media.collection.delete_many({
318 | 'file_name': file_name,
319 | 'file_size': media.file_size,
320 | 'mime_type': media.mime_type
321 | })
322 | if result.deleted_count:
323 | await msg.edit('File is successfully deleted from database')
324 | else:
325 | # files indexed before https://github.com/EvamariaTG/EvaMaria/commit/f3d2a1bcb155faf44178e5d7a685a1b533e714bf#diff-86b613edf1748372103e94cacff3b578b36b698ef9c16817bb98fe9ef22fb669R39
326 | # have original file name.
327 | result = await Media.collection.delete_many({
328 | 'file_name': media.file_name,
329 | 'file_size': media.file_size,
330 | 'mime_type': media.mime_type
331 | })
332 | if result.deleted_count:
333 | await msg.edit('File is successfully deleted from database')
334 | else:
335 | await msg.edit('File not found in database')
336 |
337 |
338 | @Client.on_message(filters.command('deleteall') & filters.user(ADMINS))
339 | async def delete_all_index(bot, message):
340 | await message.reply_text(
341 | 'This will delete all indexed files.\nDo you want to continue??',
342 | reply_markup=InlineKeyboardMarkup(
343 | [
344 | [
345 | InlineKeyboardButton(
346 | text="YES", callback_data="autofilter_delete"
347 | )
348 | ],
349 | [
350 | InlineKeyboardButton(
351 | text="CANCEL", callback_data="close_data"
352 | )
353 | ],
354 | ]
355 | ),
356 | quote=True,
357 | )
358 |
359 |
360 | @Client.on_callback_query(filters.regex(r'^autofilter_delete'))
361 | async def delete_all_index_confirm(bot, message):
362 | await Media.collection.drop()
363 | await message.answer('Piracy Is Crime')
364 | await message.message.edit('Succesfully Deleted All The Indexed Files.')
365 |
366 |
367 | @Client.on_message(filters.command('settings'))
368 | async def settings(client, message):
369 | userid = message.from_user.id if message.from_user else None
370 | if not userid:
371 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
372 | chat_type = message.chat.type
373 |
374 | if chat_type == enums.ChatType.PRIVATE:
375 | grpid = await active_connection(str(userid))
376 | if grpid is not None:
377 | grp_id = grpid
378 | try:
379 | chat = await client.get_chat(grpid)
380 | title = chat.title
381 | except:
382 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
383 | return
384 | else:
385 | await message.reply_text("I'm not connected to any groups!", quote=True)
386 | return
387 |
388 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
389 | grp_id = message.chat.id
390 | title = message.chat.title
391 |
392 | else:
393 | return
394 |
395 | st = await client.get_chat_member(grp_id, userid)
396 | if (
397 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
398 | and st.status != enums.ChatMemberStatus.OWNER
399 | and str(userid) not in ADMINS
400 | ):
401 | return
402 |
403 | settings = await get_settings(grp_id)
404 |
405 | if settings is not None:
406 | buttons = [
407 | [
408 | InlineKeyboardButton(
409 | 'Filter Button',
410 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
411 | ),
412 | InlineKeyboardButton(
413 | 'Single' if settings["button"] else 'Double',
414 | callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
415 | ),
416 | ],
417 | [
418 | InlineKeyboardButton(
419 | 'Bot PM',
420 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
421 | ),
422 | InlineKeyboardButton(
423 | '✅ Yes' if settings["botpm"] else '❌ No',
424 | callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
425 | ),
426 | ],
427 | [
428 | InlineKeyboardButton(
429 | 'File Secure',
430 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
431 | ),
432 | InlineKeyboardButton(
433 | '✅ Yes' if settings["file_secure"] else '❌ No',
434 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
435 | ),
436 | ],
437 | [
438 | InlineKeyboardButton(
439 | 'IMDB',
440 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
441 | ),
442 | InlineKeyboardButton(
443 | '✅ Yes' if settings["imdb"] else '❌ No',
444 | callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
445 | ),
446 | ],
447 | [
448 | InlineKeyboardButton(
449 | 'Spell Check',
450 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
451 | ),
452 | InlineKeyboardButton(
453 | '✅ Yes' if settings["spell_check"] else '❌ No',
454 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
455 | ),
456 | ],
457 | [
458 | InlineKeyboardButton(
459 | 'Welcome',
460 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
461 | ),
462 | InlineKeyboardButton(
463 | '✅ Yes' if settings["welcome"] else '❌ No',
464 | callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
465 | ),
466 | ],
467 | ]
468 |
469 | reply_markup = InlineKeyboardMarkup(buttons)
470 |
471 | await message.reply_text(
472 | text=f"Change Your Settings for {title} As Your Wish ⚙",
473 | reply_markup=reply_markup,
474 | disable_web_page_preview=True,
475 | parse_mode=enums.ParseMode.HTML,
476 | reply_to_message_id=message.id
477 | )
478 |
479 |
480 |
481 | @Client.on_message(filters.command('set_template'))
482 | async def save_template(client, message):
483 | sts = await message.reply("Checking template")
484 | userid = message.from_user.id if message.from_user else None
485 | if not userid:
486 | return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
487 | chat_type = message.chat.type
488 |
489 | if chat_type == enums.ChatType.PRIVATE:
490 | grpid = await active_connection(str(userid))
491 | if grpid is not None:
492 | grp_id = grpid
493 | try:
494 | chat = await client.get_chat(grpid)
495 | title = chat.title
496 | except:
497 | await message.reply_text("Make sure I'm present in your group!!", quote=True)
498 | return
499 | else:
500 | await message.reply_text("I'm not connected to any groups!", quote=True)
501 | return
502 |
503 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
504 | grp_id = message.chat.id
505 | title = message.chat.title
506 |
507 | else:
508 | return
509 |
510 | st = await client.get_chat_member(grp_id, userid)
511 | if (
512 | st.status != enums.ChatMemberStatus.ADMINISTRATOR
513 | and st.status != enums.ChatMemberStatus.OWNER
514 | and str(userid) not in ADMINS
515 | ):
516 | return
517 |
518 | if len(message.command) < 2:
519 | return await sts.edit("No Input!!")
520 | template = message.text.split(" ", 1)[1]
521 | await save_group_settings(grp_id, 'template', template)
522 | await sts.edit(f"Successfully changed template for {title} to\n\n{template}")
523 |
--------------------------------------------------------------------------------
/plugins/pm_filter.py:
--------------------------------------------------------------------------------
1 | # Kanged From @TroJanZheX
2 | import asyncio
3 | import re
4 | import ast
5 | import math
6 | from pyrogram.errors.exceptions.bad_request_400 import MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty
7 | from Script import script
8 | import pyrogram
9 | from database.connections_mdb import active_connection, all_connections, delete_connection, if_active, make_active, \
10 | make_inactive
11 | from info import ADMINS, AUTH_CHANNEL, AUTH_USERS, CUSTOM_FILE_CAPTION, AUTH_GROUPS, P_TTI_SHOW_OFF, IMDB, \
12 | SINGLE_BUTTON, SPELL_CHECK_REPLY, IMDB_TEMPLATE
13 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
14 | from pyrogram import Client, filters, enums
15 | from pyrogram.errors import FloodWait, UserIsBlocked, MessageNotModified, PeerIdInvalid
16 | from utils import get_size, is_subscribed, get_poster, search_gagala, temp, get_settings, save_group_settings
17 | from database.users_chats_db import db
18 | from database.ia_filterdb import Media, get_file_details, get_search_results
19 | from database.filters_mdb import (
20 | del_all,
21 | find_filter,
22 | get_filters,
23 | )
24 | import logging
25 |
26 | logger = logging.getLogger(__name__)
27 | logger.setLevel(logging.ERROR)
28 |
29 | BUTTONS = {}
30 | SPELL_CHECK = {}
31 |
32 |
33 | @Client.on_message(filters.group & filters.text & filters.incoming)
34 | async def give_filter(client, message):
35 | k = await manual_filters(client, message)
36 | if k == False:
37 | await auto_filter(client, message)
38 |
39 |
40 | @Client.on_callback_query(filters.regex(r"^next"))
41 | async def next_page(bot, query):
42 | ident, req, key, offset = query.data.split("_")
43 | if int(req) not in [query.from_user.id, 0]:
44 | return await query.answer("oKda", show_alert=True)
45 | try:
46 | offset = int(offset)
47 | except:
48 | offset = 0
49 | search = BUTTONS.get(key)
50 | if not search:
51 | await query.answer("You are using one of my old messages, please send the request again.", show_alert=True)
52 | return
53 |
54 | files, n_offset, total = await get_search_results(search, offset=offset, filter=True)
55 | try:
56 | n_offset = int(n_offset)
57 | except:
58 | n_offset = 0
59 |
60 | if not files:
61 | return
62 | settings = await get_settings(query.message.chat.id)
63 | if settings['button']:
64 | btn = [
65 | [
66 | InlineKeyboardButton(
67 | text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'files#{file.file_id}'
68 | ),
69 | ]
70 | for file in files
71 | ]
72 | else:
73 | btn = [
74 | [
75 | InlineKeyboardButton(
76 | text=f"{file.file_name}", callback_data=f'files#{file.file_id}'
77 | ),
78 | InlineKeyboardButton(
79 | text=f"{get_size(file.file_size)}",
80 | callback_data=f'files_#{file.file_id}',
81 | ),
82 | ]
83 | for file in files
84 | ]
85 |
86 | if 0 < offset <= 10:
87 | off_set = 0
88 | elif offset == 0:
89 | off_set = None
90 | else:
91 | off_set = offset - 10
92 | if n_offset == 0:
93 | btn.append(
94 | [InlineKeyboardButton("⏪ BACK", callback_data=f"next_{req}_{key}_{off_set}"),
95 | InlineKeyboardButton(f"📃 Pages {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}",
96 | callback_data="pages")]
97 | )
98 | elif off_set is None:
99 | btn.append(
100 | [InlineKeyboardButton(f"🗓 {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
101 | InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{req}_{key}_{n_offset}")])
102 | else:
103 | btn.append(
104 | [
105 | InlineKeyboardButton("⏪ BACK", callback_data=f"next_{req}_{key}_{off_set}"),
106 | InlineKeyboardButton(f"🗓 {math.ceil(int(offset) / 10) + 1} / {math.ceil(total / 10)}", callback_data="pages"),
107 | InlineKeyboardButton("NEXT ⏩", callback_data=f"next_{req}_{key}_{n_offset}")
108 | ],
109 | )
110 | try:
111 | await query.edit_message_reply_markup(
112 | reply_markup=InlineKeyboardMarkup(btn)
113 | )
114 | except MessageNotModified:
115 | pass
116 | await query.answer()
117 |
118 |
119 | @Client.on_callback_query(filters.regex(r"^spolling"))
120 | async def advantage_spoll_choker(bot, query):
121 | _, user, movie_ = query.data.split('#')
122 | if int(user) != 0 and query.from_user.id != int(user):
123 | return await query.answer("okDa", show_alert=True)
124 | if movie_ == "close_spellcheck":
125 | return await query.message.delete()
126 | movies = SPELL_CHECK.get(query.message.reply_to_message.id)
127 | if not movies:
128 | return await query.answer("You are clicking on an old button which is expired.", show_alert=True)
129 | movie = movies[(int(movie_))]
130 | await query.answer('Checking for Movie in database...')
131 | k = await manual_filters(bot, query.message, text=movie)
132 | if k == False:
133 | files, offset, total_results = await get_search_results(movie, offset=0, filter=True)
134 | if files:
135 | k = (movie, files, offset, total_results)
136 | await auto_filter(bot, query, k)
137 | else:
138 | k = await query.message.edit('This Movie Not Found In DataBase')
139 | await asyncio.sleep(10)
140 | await k.delete()
141 |
142 |
143 | @Client.on_callback_query()
144 | async def cb_handler(client: Client, query: CallbackQuery):
145 | if query.data == "close_data":
146 | await query.message.delete()
147 | elif query.data == "delallconfirm":
148 | userid = query.from_user.id
149 | chat_type = query.message.chat.type
150 |
151 | if chat_type == enums.ChatType.PRIVATE:
152 | grpid = await active_connection(str(userid))
153 | if grpid is not None:
154 | grp_id = grpid
155 | try:
156 | chat = await client.get_chat(grpid)
157 | title = chat.title
158 | except:
159 | await query.message.edit_text("Make sure I'm present in your group!!", quote=True)
160 | return await query.answer('Piracy Is Crime')
161 | else:
162 | await query.message.edit_text(
163 | "I'm not connected to any groups!\nCheck /connections or connect to any groups",
164 | quote=True
165 | )
166 | return await query.answer('Piracy Is Crime')
167 |
168 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
169 | grp_id = query.message.chat.id
170 | title = query.message.chat.title
171 |
172 | else:
173 | return await query.answer('Piracy Is Crime')
174 |
175 | st = await client.get_chat_member(grp_id, userid)
176 | if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS):
177 | await del_all(query.message, grp_id, title)
178 | else:
179 | await query.answer("You need to be Group Owner or an Auth User to do that!", show_alert=True)
180 | elif query.data == "delallcancel":
181 | userid = query.from_user.id
182 | chat_type = query.message.chat.type
183 |
184 | if chat_type == enums.ChatType.PRIVATE:
185 | await query.message.reply_to_message.delete()
186 | await query.message.delete()
187 |
188 | elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
189 | grp_id = query.message.chat.id
190 | st = await client.get_chat_member(grp_id, userid)
191 | if (st.status == enums.ChatMemberStatus.OWNER) or (str(userid) in ADMINS):
192 | await query.message.delete()
193 | try:
194 | await query.message.reply_to_message.delete()
195 | except:
196 | pass
197 | else:
198 | await query.answer("That's not for you!!", show_alert=True)
199 | elif "groupcb" in query.data:
200 | await query.answer()
201 |
202 | group_id = query.data.split(":")[1]
203 |
204 | act = query.data.split(":")[2]
205 | hr = await client.get_chat(int(group_id))
206 | title = hr.title
207 | user_id = query.from_user.id
208 |
209 | if act == "":
210 | stat = "CONNECT"
211 | cb = "connectcb"
212 | else:
213 | stat = "DISCONNECT"
214 | cb = "disconnect"
215 |
216 | keyboard = InlineKeyboardMarkup([
217 | [InlineKeyboardButton(f"{stat}", callback_data=f"{cb}:{group_id}"),
218 | InlineKeyboardButton("DELETE", callback_data=f"deletecb:{group_id}")],
219 | [InlineKeyboardButton("BACK", callback_data="backcb")]
220 | ])
221 |
222 | await query.message.edit_text(
223 | f"Group Name : **{title}**\nGroup ID : `{group_id}`",
224 | reply_markup=keyboard,
225 | parse_mode=enums.ParseMode.MARKDOWN
226 | )
227 | return await query.answer('Piracy Is Crime')
228 | elif "connectcb" in query.data:
229 | await query.answer()
230 |
231 | group_id = query.data.split(":")[1]
232 |
233 | hr = await client.get_chat(int(group_id))
234 |
235 | title = hr.title
236 |
237 | user_id = query.from_user.id
238 |
239 | mkact = await make_active(str(user_id), str(group_id))
240 |
241 | if mkact:
242 | await query.message.edit_text(
243 | f"Connected to **{title}**",
244 | parse_mode=enums.ParseMode.MARKDOWN
245 | )
246 | else:
247 | await query.message.edit_text('Some error occurred!!', parse_mode=enums.ParseMode.MARKDOWN)
248 | return await query.answer('Piracy Is Crime')
249 | elif "disconnect" in query.data:
250 | await query.answer()
251 |
252 | group_id = query.data.split(":")[1]
253 |
254 | hr = await client.get_chat(int(group_id))
255 |
256 | title = hr.title
257 | user_id = query.from_user.id
258 |
259 | mkinact = await make_inactive(str(user_id))
260 |
261 | if mkinact:
262 | await query.message.edit_text(
263 | f"Disconnected from **{title}**",
264 | parse_mode=enums.ParseMode.MARKDOWN
265 | )
266 | else:
267 | await query.message.edit_text(
268 | f"Some error occurred!!",
269 | parse_mode=enums.ParseMode.MARKDOWN
270 | )
271 | return await query.answer('Piracy Is Crime')
272 | elif "deletecb" in query.data:
273 | await query.answer()
274 |
275 | user_id = query.from_user.id
276 | group_id = query.data.split(":")[1]
277 |
278 | delcon = await delete_connection(str(user_id), str(group_id))
279 |
280 | if delcon:
281 | await query.message.edit_text(
282 | "Successfully deleted connection"
283 | )
284 | else:
285 | await query.message.edit_text(
286 | f"Some error occurred!!",
287 | parse_mode=enums.ParseMode.MARKDOWN
288 | )
289 | return await query.answer('Piracy Is Crime')
290 | elif query.data == "backcb":
291 | await query.answer()
292 |
293 | userid = query.from_user.id
294 |
295 | groupids = await all_connections(str(userid))
296 | if groupids is None:
297 | await query.message.edit_text(
298 | "There are no active connections!! Connect to some groups first.",
299 | )
300 | return await query.answer('Piracy Is Crime')
301 | buttons = []
302 | for groupid in groupids:
303 | try:
304 | ttl = await client.get_chat(int(groupid))
305 | title = ttl.title
306 | active = await if_active(str(userid), str(groupid))
307 | act = " - ACTIVE" if active else ""
308 | buttons.append(
309 | [
310 | InlineKeyboardButton(
311 | text=f"{title}{act}", callback_data=f"groupcb:{groupid}:{act}"
312 | )
313 | ]
314 | )
315 | except:
316 | pass
317 | if buttons:
318 | await query.message.edit_text(
319 | "Your connected group details ;\n\n",
320 | reply_markup=InlineKeyboardMarkup(buttons)
321 | )
322 | elif "alertmessage" in query.data:
323 | grp_id = query.message.chat.id
324 | i = query.data.split(":")[1]
325 | keyword = query.data.split(":")[2]
326 | reply_text, btn, alerts, fileid = await find_filter(grp_id, keyword)
327 | if alerts is not None:
328 | alerts = ast.literal_eval(alerts)
329 | alert = alerts[int(i)]
330 | alert = alert.replace("\\n", "\n").replace("\\t", "\t")
331 | await query.answer(alert, show_alert=True)
332 | if query.data.startswith("file"):
333 | ident, file_id = query.data.split("#")
334 | files_ = await get_file_details(file_id)
335 | if not files_:
336 | return await query.answer('No such file exist.')
337 | files = files_[0]
338 | title = files.file_name
339 | size = get_size(files.file_size)
340 | f_caption = files.caption
341 | settings = await get_settings(query.message.chat.id)
342 | if CUSTOM_FILE_CAPTION:
343 | try:
344 | f_caption = CUSTOM_FILE_CAPTION.format(file_name='' if title is None else title,
345 | file_size='' if size is None else size,
346 | file_caption='' if f_caption is None else f_caption)
347 | except Exception as e:
348 | logger.exception(e)
349 | f_caption = f_caption
350 | if f_caption is None:
351 | f_caption = f"{files.file_name}"
352 |
353 | try:
354 | if AUTH_CHANNEL and not await is_subscribed(client, query):
355 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
356 | return
357 | elif settings['botpm']:
358 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
359 | return
360 | else:
361 | await client.send_cached_media(
362 | chat_id=query.from_user.id,
363 | file_id=file_id,
364 | caption=f_caption,
365 | protect_content=True if ident == "filep" else False
366 | )
367 | await query.answer('Check PM, I have sent files in pm', show_alert=True)
368 | except UserIsBlocked:
369 | await query.answer('Unblock the bot mahn !', show_alert=True)
370 | except PeerIdInvalid:
371 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
372 | except Exception as e:
373 | await query.answer(url=f"https://t.me/{temp.U_NAME}?start={ident}_{file_id}")
374 | elif query.data.startswith("checksub"):
375 | if AUTH_CHANNEL and not await is_subscribed(client, query):
376 | await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒", show_alert=True)
377 | return
378 | ident, file_id = query.data.split("#")
379 | files_ = await get_file_details(file_id)
380 | if not files_:
381 | return await query.answer('No such file exist.')
382 | files = files_[0]
383 | title = files.file_name
384 | size = get_size(files.file_size)
385 | f_caption = files.caption
386 | if CUSTOM_FILE_CAPTION:
387 | try:
388 | f_caption = CUSTOM_FILE_CAPTION.format(file_name='' if title is None else title,
389 | file_size='' if size is None else size,
390 | file_caption='' if f_caption is None else f_caption)
391 | except Exception as e:
392 | logger.exception(e)
393 | f_caption = f_caption
394 | if f_caption is None:
395 | f_caption = f"{title}"
396 | await query.answer()
397 | await client.send_cached_media(
398 | chat_id=query.from_user.id,
399 | file_id=file_id,
400 | caption=f_caption,
401 | protect_content=True if ident == 'checksubp' else False
402 | )
403 | elif query.data == "pages":
404 | await query.answer()
405 | elif query.data == "start":
406 | buttons = [[
407 | InlineKeyboardButton('➕ Add Me To Your Groups ➕', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
408 | ], [
409 | InlineKeyboardButton('🔍 Search', switch_inline_query_current_chat=''),
410 | InlineKeyboardButton('🤖 Updates', url='https://t.me/TeamEvamaria')
411 | ], [
412 | InlineKeyboardButton('ℹ️ Help', callback_data='help'),
413 | InlineKeyboardButton('😊 About', callback_data='about')
414 | ]]
415 | reply_markup = InlineKeyboardMarkup(buttons)
416 | await query.message.edit_text(
417 | text=script.START_TXT.format(query.from_user.mention, temp.U_NAME, temp.B_NAME),
418 | reply_markup=reply_markup,
419 | parse_mode=enums.ParseMode.HTML
420 | )
421 | await query.answer('Piracy Is Crime')
422 | elif query.data == "help":
423 | buttons = [[
424 | InlineKeyboardButton('Manual Filter', callback_data='manuelfilter'),
425 | InlineKeyboardButton('Auto Filter', callback_data='autofilter')
426 | ], [
427 | InlineKeyboardButton('Connection', callback_data='coct'),
428 | InlineKeyboardButton('Extra Mods', callback_data='extra')
429 | ], [
430 | InlineKeyboardButton('🏠 Home', callback_data='start'),
431 | InlineKeyboardButton('🔮 Status', callback_data='stats')
432 | ]]
433 | reply_markup = InlineKeyboardMarkup(buttons)
434 | await query.message.edit_text(
435 | text=script.HELP_TXT.format(query.from_user.mention),
436 | reply_markup=reply_markup,
437 | parse_mode=enums.ParseMode.HTML
438 | )
439 | elif query.data == "about":
440 | buttons = [[
441 | InlineKeyboardButton('🤖 Updates', url='https://t.me/TeamEvamaria'),
442 | InlineKeyboardButton('♥️ Source', callback_data='source')
443 | ], [
444 | InlineKeyboardButton('🏠 Home', callback_data='start'),
445 | InlineKeyboardButton('🔐 Close', callback_data='close_data')
446 | ]]
447 | reply_markup = InlineKeyboardMarkup(buttons)
448 | await query.message.edit_text(
449 | text=script.ABOUT_TXT.format(temp.B_NAME),
450 | reply_markup=reply_markup,
451 | parse_mode=enums.ParseMode.HTML
452 | )
453 | elif query.data == "source":
454 | buttons = [[
455 | InlineKeyboardButton('👩🦯 Back', callback_data='about')
456 | ]]
457 | reply_markup = InlineKeyboardMarkup(buttons)
458 | await query.message.edit_text(
459 | text=script.SOURCE_TXT,
460 | reply_markup=reply_markup,
461 | parse_mode=enums.ParseMode.HTML
462 | )
463 | elif query.data == "manuelfilter":
464 | buttons = [[
465 | InlineKeyboardButton('👩🦯 Back', callback_data='help'),
466 | InlineKeyboardButton('⏹️ Buttons', callback_data='button')
467 | ]]
468 | reply_markup = InlineKeyboardMarkup(buttons)
469 | await query.message.edit_text(
470 | text=script.MANUELFILTER_TXT,
471 | reply_markup=reply_markup,
472 | parse_mode=enums.ParseMode.HTML
473 | )
474 | elif query.data == "button":
475 | buttons = [[
476 | InlineKeyboardButton('👩🦯 Back', callback_data='manuelfilter')
477 | ]]
478 | reply_markup = InlineKeyboardMarkup(buttons)
479 | await query.message.edit_text(
480 | text=script.BUTTON_TXT,
481 | reply_markup=reply_markup,
482 | parse_mode=enums.ParseMode.HTML
483 | )
484 | elif query.data == "autofilter":
485 | buttons = [[
486 | InlineKeyboardButton('👩🦯 Back', callback_data='help')
487 | ]]
488 | reply_markup = InlineKeyboardMarkup(buttons)
489 | await query.message.edit_text(
490 | text=script.AUTOFILTER_TXT,
491 | reply_markup=reply_markup,
492 | parse_mode=enums.ParseMode.HTML
493 | )
494 | elif query.data == "coct":
495 | buttons = [[
496 | InlineKeyboardButton('👩🦯 Back', callback_data='help')
497 | ]]
498 | reply_markup = InlineKeyboardMarkup(buttons)
499 | await query.message.edit_text(
500 | text=script.CONNECTION_TXT,
501 | reply_markup=reply_markup,
502 | parse_mode=enums.ParseMode.HTML
503 | )
504 | elif query.data == "extra":
505 | buttons = [[
506 | InlineKeyboardButton('👩🦯 Back', callback_data='help'),
507 | InlineKeyboardButton('👮♂️ Admin', callback_data='admin')
508 | ]]
509 | reply_markup = InlineKeyboardMarkup(buttons)
510 | await query.message.edit_text(
511 | text=script.EXTRAMOD_TXT,
512 | reply_markup=reply_markup,
513 | parse_mode=enums.ParseMode.HTML
514 | )
515 | elif query.data == "admin":
516 | buttons = [[
517 | InlineKeyboardButton('👩🦯 Back', callback_data='extra')
518 | ]]
519 | reply_markup = InlineKeyboardMarkup(buttons)
520 | await query.message.edit_text(
521 | text=script.ADMIN_TXT,
522 | reply_markup=reply_markup,
523 | parse_mode=enums.ParseMode.HTML
524 | )
525 | elif query.data == "stats":
526 | buttons = [[
527 | InlineKeyboardButton('👩🦯 Back', callback_data='help'),
528 | InlineKeyboardButton('♻️', callback_data='rfrsh')
529 | ]]
530 | reply_markup = InlineKeyboardMarkup(buttons)
531 | total = await Media.count_documents()
532 | users = await db.total_users_count()
533 | chats = await db.total_chat_count()
534 | monsize = await db.get_db_size()
535 | free = 536870912 - monsize
536 | monsize = get_size(monsize)
537 | free = get_size(free)
538 | await query.message.edit_text(
539 | text=script.STATUS_TXT.format(total, users, chats, monsize, free),
540 | reply_markup=reply_markup,
541 | parse_mode=enums.ParseMode.HTML
542 | )
543 | elif query.data == "rfrsh":
544 | await query.answer("Fetching MongoDb DataBase")
545 | buttons = [[
546 | InlineKeyboardButton('👩🦯 Back', callback_data='help'),
547 | InlineKeyboardButton('♻️', callback_data='rfrsh')
548 | ]]
549 | reply_markup = InlineKeyboardMarkup(buttons)
550 | total = await Media.count_documents()
551 | users = await db.total_users_count()
552 | chats = await db.total_chat_count()
553 | monsize = await db.get_db_size()
554 | free = 536870912 - monsize
555 | monsize = get_size(monsize)
556 | free = get_size(free)
557 | await query.message.edit_text(
558 | text=script.STATUS_TXT.format(total, users, chats, monsize, free),
559 | reply_markup=reply_markup,
560 | parse_mode=enums.ParseMode.HTML
561 | )
562 | elif query.data.startswith("setgs"):
563 | ident, set_type, status, grp_id = query.data.split("#")
564 | grpid = await active_connection(str(query.from_user.id))
565 |
566 | if str(grp_id) != str(grpid):
567 | await query.message.edit("Your Active Connection Has Been Changed. Go To /settings.")
568 | return await query.answer('Piracy Is Crime')
569 |
570 | if status == "True":
571 | await save_group_settings(grpid, set_type, False)
572 | else:
573 | await save_group_settings(grpid, set_type, True)
574 |
575 | settings = await get_settings(grpid)
576 |
577 | if settings is not None:
578 | buttons = [
579 | [
580 | InlineKeyboardButton('Filter Button',
581 | callback_data=f'setgs#button#{settings["button"]}#{str(grp_id)}'),
582 | InlineKeyboardButton('Single' if settings["button"] else 'Double',
583 | callback_data=f'setgs#button#{settings["button"]}#{str(grp_id)}')
584 | ],
585 | [
586 | InlineKeyboardButton('Bot PM', callback_data=f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}'),
587 | InlineKeyboardButton('✅ Yes' if settings["botpm"] else '❌ No',
588 | callback_data=f'setgs#botpm#{settings["botpm"]}#{str(grp_id)}')
589 | ],
590 | [
591 | InlineKeyboardButton('File Secure',
592 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}'),
593 | InlineKeyboardButton('✅ Yes' if settings["file_secure"] else '❌ No',
594 | callback_data=f'setgs#file_secure#{settings["file_secure"]}#{str(grp_id)}')
595 | ],
596 | [
597 | InlineKeyboardButton('IMDB', callback_data=f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}'),
598 | InlineKeyboardButton('✅ Yes' if settings["imdb"] else '❌ No',
599 | callback_data=f'setgs#imdb#{settings["imdb"]}#{str(grp_id)}')
600 | ],
601 | [
602 | InlineKeyboardButton('Spell Check',
603 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}'),
604 | InlineKeyboardButton('✅ Yes' if settings["spell_check"] else '❌ No',
605 | callback_data=f'setgs#spell_check#{settings["spell_check"]}#{str(grp_id)}')
606 | ],
607 | [
608 | InlineKeyboardButton('Welcome', callback_data=f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}'),
609 | InlineKeyboardButton('✅ Yes' if settings["welcome"] else '❌ No',
610 | callback_data=f'setgs#welcome#{settings["welcome"]}#{str(grp_id)}')
611 | ]
612 | ]
613 | reply_markup = InlineKeyboardMarkup(buttons)
614 | await query.message.edit_reply_markup(reply_markup)
615 | await query.answer('Piracy Is Crime')
616 |
617 |
618 | async def auto_filter(client, msg, spoll=False):
619 | if not spoll:
620 | message = msg
621 | settings = await get_settings(message.chat.id)
622 | if message.text.startswith("/"): return # ignore commands
623 | if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
624 | return
625 | if 2 < len(message.text) < 100:
626 | search = message.text
627 | files, offset, total_results = await get_search_results(search.lower(), offset=0, filter=True)
628 | if not files:
629 | if settings["spell_check"]:
630 | return await advantage_spell_chok(msg)
631 | else:
632 | return
633 | else:
634 | return
635 | else:
636 | settings = await get_settings(msg.message.chat.id)
637 | message = msg.message.reply_to_message # msg will be callback query
638 | search, files, offset, total_results = spoll
639 | pre = 'filep' if settings['file_secure'] else 'file'
640 | if settings["button"]:
641 | btn = [
642 | [
643 | InlineKeyboardButton(
644 | text=f"[{get_size(file.file_size)}] {file.file_name}", callback_data=f'{pre}#{file.file_id}'
645 | ),
646 | ]
647 | for file in files
648 | ]
649 | else:
650 | btn = [
651 | [
652 | InlineKeyboardButton(
653 | text=f"{file.file_name}",
654 | callback_data=f'{pre}#{file.file_id}',
655 | ),
656 | InlineKeyboardButton(
657 | text=f"{get_size(file.file_size)}",
658 | callback_data=f'{pre}#{file.file_id}',
659 | ),
660 | ]
661 | for file in files
662 | ]
663 |
664 | if offset != "":
665 | key = f"{message.chat.id}-{message.id}"
666 | BUTTONS[key] = search
667 | req = message.from_user.id if message.from_user else 0
668 | btn.append(
669 | [InlineKeyboardButton(text=f"🗓 1/{math.ceil(int(total_results) / 10)}", callback_data="pages"),
670 | InlineKeyboardButton(text="NEXT ⏩", callback_data=f"next_{req}_{key}_{offset}")]
671 | )
672 | else:
673 | btn.append(
674 | [InlineKeyboardButton(text="🗓 1/1", callback_data="pages")]
675 | )
676 | imdb = await get_poster(search, file=(files[0]).file_name) if settings["imdb"] else None
677 | TEMPLATE = settings['template']
678 | if imdb:
679 | cap = TEMPLATE.format(
680 | query=search,
681 | title=imdb['title'],
682 | votes=imdb['votes'],
683 | aka=imdb["aka"],
684 | seasons=imdb["seasons"],
685 | box_office=imdb['box_office'],
686 | localized_title=imdb['localized_title'],
687 | kind=imdb['kind'],
688 | imdb_id=imdb["imdb_id"],
689 | cast=imdb["cast"],
690 | runtime=imdb["runtime"],
691 | countries=imdb["countries"],
692 | certificates=imdb["certificates"],
693 | languages=imdb["languages"],
694 | director=imdb["director"],
695 | writer=imdb["writer"],
696 | producer=imdb["producer"],
697 | composer=imdb["composer"],
698 | cinematographer=imdb["cinematographer"],
699 | music_team=imdb["music_team"],
700 | distributors=imdb["distributors"],
701 | release_date=imdb['release_date'],
702 | year=imdb['year'],
703 | genres=imdb['genres'],
704 | poster=imdb['poster'],
705 | plot=imdb['plot'],
706 | rating=imdb['rating'],
707 | url=imdb['url'],
708 | **locals()
709 | )
710 | else:
711 | cap = f"Here is what i found for your query {search}"
712 | if imdb and imdb.get('poster'):
713 | try:
714 | await message.reply_photo(photo=imdb.get('poster'), caption=cap[:1024],
715 | reply_markup=InlineKeyboardMarkup(btn))
716 | except (MediaEmpty, PhotoInvalidDimensions, WebpageMediaEmpty):
717 | pic = imdb.get('poster')
718 | poster = pic.replace('.jpg', "._V1_UX360.jpg")
719 | await message.reply_photo(photo=poster, caption=cap[:1024], reply_markup=InlineKeyboardMarkup(btn))
720 | except Exception as e:
721 | logger.exception(e)
722 | await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
723 | else:
724 | await message.reply_text(cap, reply_markup=InlineKeyboardMarkup(btn))
725 | if spoll:
726 | await msg.message.delete()
727 |
728 |
729 | async def advantage_spell_chok(msg):
730 | query = re.sub(
731 | r"\b(pl(i|e)*?(s|z+|ease|se|ese|(e+)s(e)?)|((send|snd|giv(e)?|gib)(\sme)?)|movie(s)?|new|latest|br((o|u)h?)*|^h(e|a)?(l)*(o)*|mal(ayalam)?|t(h)?amil|file|that|find|und(o)*|kit(t(i|y)?)?o(w)?|thar(u)?(o)*w?|kittum(o)*|aya(k)*(um(o)*)?|full\smovie|any(one)|with\ssubtitle(s)?)",
732 | "", msg.text, flags=re.IGNORECASE) # plis contribute some common words
733 | query = query.strip() + " movie"
734 | g_s = await search_gagala(query)
735 | g_s += await search_gagala(msg.text)
736 | gs_parsed = []
737 | if not g_s:
738 | k = await msg.reply("I couldn't find any movie in that name.")
739 | await asyncio.sleep(8)
740 | await k.delete()
741 | return
742 | regex = re.compile(r".*(imdb|wikipedia).*", re.IGNORECASE) # look for imdb / wiki results
743 | gs = list(filter(regex.match, g_s))
744 | gs_parsed = [re.sub(
745 | r'\b(\-([a-zA-Z-\s])\-\simdb|(\-\s)?imdb|(\-\s)?wikipedia|\(|\)|\-|reviews|full|all|episode(s)?|film|movie|series)',
746 | '', i, flags=re.IGNORECASE) for i in gs]
747 | if not gs_parsed:
748 | reg = re.compile(r"watch(\s[a-zA-Z0-9_\s\-\(\)]*)*\|.*",
749 | re.IGNORECASE) # match something like Watch Niram | Amazon Prime
750 | for mv in g_s:
751 | match = reg.match(mv)
752 | if match:
753 | gs_parsed.append(match.group(1))
754 | user = msg.from_user.id if msg.from_user else 0
755 | movielist = []
756 | gs_parsed = list(dict.fromkeys(gs_parsed)) # removing duplicates https://stackoverflow.com/a/7961425
757 | if len(gs_parsed) > 3:
758 | gs_parsed = gs_parsed[:3]
759 | if gs_parsed:
760 | for mov in gs_parsed:
761 | imdb_s = await get_poster(mov.strip(), bulk=True) # searching each keyword in imdb
762 | if imdb_s:
763 | movielist += [movie.get('title') for movie in imdb_s]
764 | movielist += [(re.sub(r'(\-|\(|\)|_)', '', i, flags=re.IGNORECASE)).strip() for i in gs_parsed]
765 | movielist = list(dict.fromkeys(movielist)) # removing duplicates
766 | if not movielist:
767 | k = await msg.reply("I couldn't find anything related to that. Check your spelling")
768 | await asyncio.sleep(8)
769 | await k.delete()
770 | return
771 | SPELL_CHECK[msg.id] = movielist
772 | btn = [[
773 | InlineKeyboardButton(
774 | text=movie.strip(),
775 | callback_data=f"spolling#{user}#{k}",
776 | )
777 | ] for k, movie in enumerate(movielist)]
778 | btn.append([InlineKeyboardButton(text="Close", callback_data=f'spolling#{user}#close_spellcheck')])
779 | await msg.reply("I couldn't find anything related to that\nDid you mean any one of these?",
780 | reply_markup=InlineKeyboardMarkup(btn))
781 |
782 |
783 | async def manual_filters(client, message, text=False):
784 | group_id = message.chat.id
785 | name = text or message.text
786 | reply_id = message.reply_to_message.id if message.reply_to_message else message.id
787 | keywords = await get_filters(group_id)
788 | for keyword in reversed(sorted(keywords, key=len)):
789 | pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
790 | if re.search(pattern, name, flags=re.IGNORECASE):
791 | reply_text, btn, alert, fileid = await find_filter(group_id, keyword)
792 |
793 | if reply_text:
794 | reply_text = reply_text.replace("\\n", "\n").replace("\\t", "\t")
795 |
796 | if btn is not None:
797 | try:
798 | if fileid == "None":
799 | if btn == "[]":
800 | await client.send_message(group_id, reply_text, disable_web_page_preview=True)
801 | else:
802 | button = eval(btn)
803 | await client.send_message(
804 | group_id,
805 | reply_text,
806 | disable_web_page_preview=True,
807 | reply_markup=InlineKeyboardMarkup(button),
808 | reply_to_message_id=reply_id
809 | )
810 | elif btn == "[]":
811 | await client.send_cached_media(
812 | group_id,
813 | fileid,
814 | caption=reply_text or "",
815 | reply_to_message_id=reply_id
816 | )
817 | else:
818 | button = eval(btn)
819 | await message.reply_cached_media(
820 | fileid,
821 | caption=reply_text or "",
822 | reply_markup=InlineKeyboardMarkup(button),
823 | reply_to_message_id=reply_id
824 | )
825 | except Exception as e:
826 | logger.exception(e)
827 | break
828 | else:
829 | return False
830 |
--------------------------------------------------------------------------------