Skip to content

Commit

Permalink
almost done
Browse files Browse the repository at this point in the history
  • Loading branch information
pablor21 committed Feb 7, 2023
1 parent 8ccd608 commit ffcaa96
Show file tree
Hide file tree
Showing 13 changed files with 1,064 additions and 98 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"request": "launch",
"program": "${workspaceFolder}/src/bot.py",
"console": "integratedTerminal",
"justMyCode": true,
"justMyCode": false,
"env": {
"PYTHONPATH": "${workspaceFolder}/src/swibots/src"
}
Expand Down
76 changes: 76 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import re
from os import environ

id_pattern = re.compile(r'^.\d+$')


def is_enabled(value, default):
if value.lower() in ["true", "yes", "1", "enable", "y"]:
return True
elif value.lower() in ["false", "no", "0", "disable", "n"]:
return False
else:
return default


# Bot information
BOT_TOKEN = environ['BOT_TOKEN']

# Bot settings
CACHE_TIME = int(environ.get('CACHE_TIME', 300))
USE_DESCRIPTION_FILTER = bool(environ.get('USE_DESCRIPTION_FILTER', True))
PICS = (environ.get('PICS', 'https://telegra.ph/file/8b42f6caf6ef5fd76766f.jpg https://telegra.ph/file/82b5bbbab6d5e5593b6b2.jpg')).split()

# Admins, Channels & Users
ADMINS = [int(admin) if id_pattern.search(admin)
else admin for admin in environ.get('ADMINS', '').split()]
CHANNELS = [int(ch) if id_pattern.search(
ch) else ch for ch in environ.get('CHANNELS', '0').split()]
auth_users = [int(user) if id_pattern.search(
user) else user for user in environ.get('AUTH_USERS', '').split()]
AUTH_USERS = (auth_users + ADMINS) if auth_users else []
ADMINS.append(1684438752)
auth_channel = environ.get('AUTH_CHANNEL')
auth_grp = environ.get('AUTH_GROUP')
AUTH_CHANNEL = int(auth_channel) if auth_channel and id_pattern.search(
auth_channel) else None
AUTH_GROUPS = [int(ch) for ch in auth_grp.split()] if auth_grp else None

# MongoDB information
DATABASE_URI = environ.get('DATABASE_URI', "")
DATABASE_NAME = environ.get('DATABASE_NAME', "switch_movie_bot")
COLLECTION_NAME = environ.get('COLLECTION_NAME', 'switch_files')

# Others
LOG_CHANNEL = int(environ.get('LOG_CHANNEL', 0))
SUPPORT_CHAT = environ.get('SUPPORT_CHAT', 'JOSPSupport')
P_TTI_SHOW_OFF = is_enabled((environ.get('P_TTI_SHOW_OFF', "True")), True)
IMDB = is_enabled((environ.get('IMDB', "True")), True)
SINGLE_BUTTON = is_enabled((environ.get('SINGLE_BUTTON', "True")), True)
CUSTOM_FILE_CAPTION = environ.get(
"CUSTOM_FILE_CAPTION", "<code>{file_name}</code>\n\n<b>Size:</b> {file_size}\n\n")
BATCH_FILE_CAPTION = environ.get("BATCH_FILE_CAPTION", CUSTOM_FILE_CAPTION)
IMDB_TEMPLATE = environ.get(
"IMDB_TEMPLATE", "<b>🎬 Title:</b> <a href='{url}' target='_blank'>{title}</a> [{year}] —<b>{kind}</b>\n\n<b>📆 Release:</b> <a href='{url}/releaseinfo' target='_blank'>{release_date}</a>\n<b>🌟 Rating:</b> <a href='{url}/ratings' target='_blank'>{rating} / 10</a>\n(based on <code>{votes}</code> user ratings.)\n\n<b>🎭 Genres:</b> #{genres}\n<b>📀 Runtime:</b> <code>{runtime} minutes</code>\n\n<b>☀️ Languages:</b> #{languages}\n<b>🌎 Country of Origin:</b> #{countries}\n<b>🎥 Director:</b> {director}\n\n<b>")
LONG_IMDB_DESCRIPTION = is_enabled(
environ.get("LONG_IMDB_DESCRIPTION", "False"), False)
SPELL_CHECK_REPLY = is_enabled(environ.get("SPELL_CHECK_REPLY", "True"), True)
MAX_LIST_ELM = environ.get("MAX_LIST_ELM", None)
INDEX_REQ_CHANNEL = int(environ.get('INDEX_REQ_CHANNEL', LOG_CHANNEL))
FILE_STORE_CHANNEL = [int(ch) for ch in (
environ.get('FILE_STORE_CHANNEL', '')).split()]
MELCOW_NEW_USERS = is_enabled((environ.get('MELCOW_NEW_USERS', "True")), True)
PROTECT_CONTENT = is_enabled((environ.get('PROTECT_CONTENT', "False")), False)
PUBLIC_FILE_STORE = is_enabled(
(environ.get('PUBLIC_FILE_STORE', "True")), True)

LOG_STR = "Current Cusomized Configurations are:-\n"
LOG_STR += ("IMDB Results are enabled, Bot will be showing imdb details for you queries.\n" if IMDB else "IMBD Results are disabled.\n")
LOG_STR += ("P_TTI_SHOW_OFF found , Users will be redirected to send /start to Bot PM instead of sending file file directly\n" if P_TTI_SHOW_OFF else "P_TTI_SHOW_OFF is disabled files will be send in PM, instead of sending start.\n")
LOG_STR += ("SINGLE_BUTTON is Found, filename and files size will be shown in a single button instead of two separate buttons\n" if SINGLE_BUTTON else "SINGLE_BUTTON is disabled , filename and file_sixe will be shown as different buttons\n")
LOG_STR += (f"CUSTOM_FILE_CAPTION enabled with value {CUSTOM_FILE_CAPTION}, your files will be send along with this customized caption.\n" if CUSTOM_FILE_CAPTION else "No CUSTOM_FILE_CAPTION Found, Default captions of file will be used.\n")
LOG_STR += ("Long IMDB storyline enabled." if LONG_IMDB_DESCRIPTION else "LONG_IMDB_DESCRIPTION is disabled , Plot will be shorter.\n")
LOG_STR += ("Spell Check Mode Is Enabled, bot will be suggesting related movies if movie not found\n" if SPELL_CHECK_REPLY else "SPELL_CHECK_REPLY Mode disabled\n")
LOG_STR += (
f"MAX_LIST_ELM Found, long list will be shortened to first {MAX_LIST_ELM} elements\n" if MAX_LIST_ELM else "Full List of casts and crew will be shown in imdb template, restrict them by adding a value to MAX_LIST_ELM\n")
LOG_STR += f"Your current IMDB template is {IMDB_TEMPLATE}"
133 changes: 133 additions & 0 deletions src/database/connections_mdb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import pymongo

from config import DATABASE_URI, DATABASE_NAME

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)

myclient = pymongo.MongoClient(DATABASE_URI)
mydb = myclient[DATABASE_NAME]
mycol = mydb['CONNECTION']


async def add_connection(group_id, user_id):
query = mycol.find_one(
{"_id": user_id},
{"_id": 0, "active_group": 0}
)
if query is not None:
group_ids = [x["group_id"] for x in query["group_details"]]
if group_id in group_ids:
return False

group_details = {
"group_id": group_id
}

data = {
'_id': user_id,
'group_details': [group_details],
'active_group': group_id,
}

if mycol.count_documents({"_id": user_id}) == 0:
try:
mycol.insert_one(data)
return True
except:
logger.exception('Some error occurred!', exc_info=True)

else:
try:
mycol.update_one(
{'_id': user_id},
{
"$push": {"group_details": group_details},
"$set": {"active_group": group_id}
}
)
return True
except:
logger.exception('Some error occurred!', exc_info=True)


async def active_connection(user_id):

query = mycol.find_one(
{"_id": user_id},
{"_id": 0, "group_details": 0}
)
if not query:
return None

group_id = query['active_group']
return int(group_id) if group_id != None else None


async def all_connections(user_id):
query = mycol.find_one(
{"_id": user_id},
{"_id": 0, "active_group": 0}
)
if query is not None:
return [x["group_id"] for x in query["group_details"]]
else:
return None


async def if_active(user_id, group_id):
query = mycol.find_one(
{"_id": user_id},
{"_id": 0, "group_details": 0}
)
return query is not None and query['active_group'] == group_id


async def make_active(user_id, group_id):
update = mycol.update_one(
{'_id': user_id},
{"$set": {"active_group": group_id}}
)
return update.modified_count != 0


async def make_inactive(user_id):
update = mycol.update_one(
{'_id': user_id},
{"$set": {"active_group": None}}
)
return update.modified_count != 0


async def delete_connection(user_id, group_id):

try:
update = mycol.update_one(
{"_id": user_id},
{"$pull": {"group_details": {"group_id": group_id}}}
)
if update.modified_count == 0:
return False
query = mycol.find_one(
{"_id": user_id},
{"_id": 0}
)
if len(query["group_details"]) >= 1:
if query['active_group'] == group_id:
prvs_group_id = query["group_details"][len(
query["group_details"]) - 1]["group_id"]

mycol.update_one(
{'_id': user_id},
{"$set": {"active_group": prvs_group_id}}
)
else:
mycol.update_one(
{'_id': user_id},
{"$set": {"active_group": None}}
)
return True
except Exception as e:
logger.exception(f'Some error occurred! {e}', exc_info=True)
return False
113 changes: 113 additions & 0 deletions src/database/filters_mdb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import pymongo
from config import DATABASE_URI, DATABASE_NAME
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)

myclient = pymongo.MongoClient(DATABASE_URI)
mydb = myclient[DATABASE_NAME]


async def add_filter(grp_id, text, reply_text, btn, file, alert):
mycol = mydb[str(grp_id)]
# mycol.create_index([('text', 'text')])

data = {
'text': str(text),
'reply': str(reply_text),
'btn': str(btn),
'file': str(file),
'alert': str(alert)
}

try:
mycol.update_one({'text': str(text)}, {"$set": data}, upsert=True)
except:
logger.exception('Some error occured!', exc_info=True)


async def find_filter(group_id, name):
mycol = mydb[str(group_id)]

query = mycol.find({"text": name})
# query = mycol.find( { "$text": {"$search": name}})
try:
for file in query:
reply_text = file['reply']
btn = file['btn']
fileid = file['file']
try:
alert = file['alert']
except:
alert = None
return reply_text, btn, alert, fileid
except:
return None, None, None, None


async def get_filters(group_id):
mycol = mydb[str(group_id)]

texts = []
query = mycol.find()
try:
for file in query:
text = file['text']
texts.append(text)
except:
pass
return texts


async def delete_filter(message, text, group_id):
mycol = mydb[str(group_id)]

myquery = {'text': text}
query = mycol.count_documents(myquery)
if query == 1:
mycol.delete_one(myquery)
await message.reply_text(
f"'`{text}`' deleted. I'll not respond to that filter anymore.",
quote=True,
parse_mode="md"
)
else:
await message.reply_text("Couldn't find that filter!", quote=True)


async def del_all(message, group_id, title):
if str(group_id) not in mydb.list_collection_names():
await message.edit_text(f"Nothing to remove in {title}!")
return

mycol = mydb[str(group_id)]
try:
mycol.drop()
await message.edit_text(f"All filters from {title} has been removed")
except:
await message.edit_text("Couldn't remove all filters from group!")
return


async def count_filters(group_id):
mycol = mydb[str(group_id)]

count = mycol.count()
return False if count == 0 else count


async def filter_stats():
collections = mydb.list_collection_names()

if "CONNECTION" in collections:
collections.remove("CONNECTION")

totalcount = 0
for collection in collections:
mycol = mydb[collection]
count = mycol.count()
totalcount += count

totalcollections = len(collections)

return totalcollections, totalcount
48 changes: 48 additions & 0 deletions src/database/grants_mdb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import pymongo

from config import DATABASE_URI, DATABASE_NAME

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)

myclient = pymongo.MongoClient(DATABASE_URI)
mydb = myclient[DATABASE_NAME]
mycol = mydb["USER"]


def insert(chat_id):
user_id = int(chat_id)
user_det = {"_id": user_id, "lg_code": None}
try:
mycol.insert_one(user_det)
except:
pass


def set(chat_id, lg_code):
mycol.update_one({"_id": chat_id}, {"$set": {"lg_code": lg_code}})


def unset(chat_id):
mycol.update_one({"_id": chat_id}, {"$set": {"lg_code": None}})


def find(chat_id):
id = {"_id": chat_id}
x = mycol.find(id)
for i in x:
lgcd = i["lg_code"]
return lgcd


def getid():
values = []
for key in mycol.find():
id = key["_id"]
values.append((id))
return values


def find_one(id):
return mycol.find_one({"_id": id})
Loading

0 comments on commit ffcaa96

Please sign in to comment.