Update utils.py
Browse files
utils.py
CHANGED
|
@@ -34,19 +34,25 @@ class temp(object):
|
|
| 34 |
GP_SPELL = {}
|
| 35 |
|
| 36 |
async def is_subscribed(bot, query):
|
|
|
|
| 37 |
try:
|
| 38 |
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
|
|
|
|
| 39 |
except UserNotParticipant:
|
|
|
|
| 40 |
pass
|
| 41 |
except Exception as e:
|
|
|
|
| 42 |
print(e)
|
| 43 |
else:
|
| 44 |
if user.status != enums.ChatMemberStatus.BANNED:
|
|
|
|
| 45 |
return True
|
|
|
|
| 46 |
return False
|
| 47 |
|
| 48 |
-
|
| 49 |
async def get_poster(query, bulk=False, id=False, file=None):
|
|
|
|
| 50 |
imdb = Cinemagoer()
|
| 51 |
if not id:
|
| 52 |
query = (query.strip()).lower()
|
|
@@ -55,49 +61,68 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 55 |
if year:
|
| 56 |
year = list_to_str(year[:1])
|
| 57 |
title = (query.replace(year, "")).strip()
|
|
|
|
| 58 |
elif file is not None:
|
| 59 |
year = re.findall(r'[1-2]\d{3}', file, re.IGNORECASE)
|
| 60 |
if year:
|
| 61 |
year = list_to_str(year[:1])
|
|
|
|
| 62 |
else:
|
| 63 |
year = None
|
|
|
|
| 64 |
try:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
if not movieid:
|
|
|
|
| 69 |
return None
|
| 70 |
if year:
|
| 71 |
filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
|
| 72 |
if not filtered:
|
| 73 |
filtered = movieid
|
|
|
|
|
|
|
| 74 |
else:
|
| 75 |
filtered = movieid
|
|
|
|
| 76 |
movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
|
| 77 |
if not movieid:
|
| 78 |
movieid = filtered
|
|
|
|
|
|
|
| 79 |
if bulk:
|
|
|
|
| 80 |
return movieid
|
| 81 |
movieid = movieid[0].movieID
|
|
|
|
| 82 |
else:
|
| 83 |
movieid = query
|
|
|
|
| 84 |
movie = imdb.get_movie(movieid)
|
| 85 |
if movie.get("original air date"):
|
| 86 |
date = movie["original air date"]
|
|
|
|
| 87 |
elif movie.get("year"):
|
| 88 |
date = movie.get("year")
|
|
|
|
| 89 |
else:
|
| 90 |
date = "N/A"
|
|
|
|
| 91 |
plot = ""
|
| 92 |
if not LONG_IMDB_DESCRIPTION:
|
| 93 |
plot = movie.get('plot')
|
| 94 |
if plot and len(plot) > 0:
|
| 95 |
plot = plot[0]
|
|
|
|
| 96 |
else:
|
| 97 |
plot = movie.get('plot outline')
|
|
|
|
| 98 |
if plot and len(plot) > 800:
|
| 99 |
plot = plot[0:800] + "..."
|
| 100 |
-
|
| 101 |
return {
|
| 102 |
'title': movie.get('title'),
|
| 103 |
'votes': movie.get('votes'),
|
|
@@ -127,93 +152,128 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 127 |
'rating': str(movie.get("rating")),
|
| 128 |
'url':f'https://www.imdb.com/title/tt{movieid}'
|
| 129 |
}
|
| 130 |
-
|
| 131 |
def list_to_str(k):
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
elif MAX_LIST_ELM:
|
| 135 |
k = k[:int(MAX_LIST_ELM)]
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
else:
|
| 138 |
-
|
|
|
|
|
|
|
| 139 |
|
| 140 |
__repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
|
|
|
|
| 141 |
__version__ = "PROFESSOR-BOT ᴠ4.5.0"
|
|
|
|
| 142 |
__license__ = "GNU GENERAL PUBLIC LICENSE V2"
|
|
|
|
| 143 |
__copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
|
|
|
|
| 144 |
|
| 145 |
async def search_gagala(text):
|
|
|
|
| 146 |
usr_agent = {
|
| 147 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
|
| 148 |
-
|
| 149 |
-
}
|
| 150 |
text = text.replace(" ", '+')
|
| 151 |
url = f'https://www.google.com/search?q={text}'
|
| 152 |
response = requests.get(url, headers=usr_agent)
|
| 153 |
response.raise_for_status()
|
| 154 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 155 |
-
titles = soup.find_all(
|
| 156 |
-
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
async def get_settings(group_id):
|
|
|
|
| 160 |
settings = temp.SETTINGS.get(group_id)
|
| 161 |
if not settings:
|
| 162 |
settings = await db.get_settings(group_id)
|
| 163 |
temp.SETTINGS[group_id] = settings
|
|
|
|
|
|
|
|
|
|
| 164 |
return settings
|
| 165 |
|
| 166 |
async def save_group_settings(group_id, key, value):
|
|
|
|
| 167 |
current = await get_settings(group_id)
|
| 168 |
current[key] = value
|
| 169 |
temp.SETTINGS[group_id] = current
|
| 170 |
await db.update_settings(group_id, current)
|
| 171 |
-
|
|
|
|
| 172 |
def get_size(size):
|
|
|
|
| 173 |
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
|
| 174 |
size = float(size)
|
| 175 |
i = 0
|
| 176 |
while size >= 1024.0 and i < len(units):
|
| 177 |
i += 1
|
| 178 |
size /= 1024.0
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
|
| 182 |
def get_file_id(msg: Message):
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
| 184 |
for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
|
| 185 |
obj = getattr(msg, message_type)
|
| 186 |
if obj:
|
| 187 |
setattr(obj, "message_type", message_type)
|
|
|
|
| 188 |
return obj
|
| 189 |
|
| 190 |
-
|
| 191 |
def extract_user(message: Message) -> Union[int, str]:
|
|
|
|
| 192 |
user_id = None
|
| 193 |
user_first_name = None
|
| 194 |
if message.reply_to_message:
|
| 195 |
user_id = message.reply_to_message.from_user.id
|
| 196 |
user_first_name = message.reply_to_message.from_user.first_name
|
|
|
|
| 197 |
elif len(message.command) > 1:
|
| 198 |
if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
|
| 199 |
required_entity = message.entities[1]
|
| 200 |
user_id = required_entity.user.id
|
| 201 |
user_first_name = required_entity.user.first_name
|
|
|
|
| 202 |
else:
|
| 203 |
user_id = message.command[1]
|
| 204 |
user_first_name = user_id
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
else:
|
| 209 |
user_id = message.from_user.id
|
| 210 |
user_first_name = message.from_user.first_name
|
|
|
|
| 211 |
return (user_id, user_first_name)
|
| 212 |
|
| 213 |
-
|
| 214 |
def split_quotes(text: str) -> List:
|
|
|
|
| 215 |
if not any(text.startswith(char) for char in START_CHAR):
|
| 216 |
-
|
|
|
|
|
|
|
| 217 |
counter = 1 # ignore first char -> is some kind of quote
|
| 218 |
while counter < len(text):
|
| 219 |
if text[counter] == "\\":
|
|
@@ -222,7 +282,9 @@ def split_quotes(text: str) -> List:
|
|
| 222 |
break
|
| 223 |
counter += 1
|
| 224 |
else:
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
# 1 to avoid starting quote, and counter is exclusive so avoids ending
|
| 228 |
key = remove_escapes(text[1:counter].strip())
|
|
@@ -230,10 +292,16 @@ def split_quotes(text: str) -> List:
|
|
| 230 |
rest = text[counter + 1:].strip()
|
| 231 |
if not key:
|
| 232 |
key = text[0] + text[0]
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
def parser(text, keyword, cb_data):
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
| 237 |
buttons = []
|
| 238 |
note_data = ""
|
| 239 |
prev = 0
|
|
@@ -253,23 +321,36 @@ def parser(text, keyword, cb_data):
|
|
| 253 |
# create a thruple with button label, url, and newline status
|
| 254 |
if bool(match.group(5)) and buttons:
|
| 255 |
buttons[-1].append(InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}"))
|
|
|
|
| 256 |
else:
|
| 257 |
buttons.append([InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}")])
|
|
|
|
| 258 |
i += 1
|
| 259 |
alerts.append(match.group(4))
|
|
|
|
| 260 |
elif bool(match.group(5)) and buttons:
|
| 261 |
buttons[-1].append(InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", "")))
|
|
|
|
| 262 |
else:
|
| 263 |
buttons.append([InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", ""))])
|
|
|
|
| 264 |
else:
|
| 265 |
note_data += text[prev:to_check]
|
| 266 |
prev = match.start(1) - 1
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
def remove_escapes(text: str) -> str:
|
|
|
|
| 273 |
res = ""
|
| 274 |
is_escaped = False
|
| 275 |
for counter in range(len(text)):
|
|
@@ -280,11 +361,14 @@ def remove_escapes(text: str) -> str:
|
|
| 280 |
is_escaped = True
|
| 281 |
else:
|
| 282 |
res += text[counter]
|
|
|
|
|
|
|
| 283 |
return res
|
| 284 |
-
|
| 285 |
|
| 286 |
def humanbytes(size):
|
|
|
|
| 287 |
if not size:
|
|
|
|
| 288 |
return ""
|
| 289 |
power = 2**10
|
| 290 |
n = 0
|
|
@@ -292,75 +376,85 @@ def humanbytes(size):
|
|
| 292 |
while size > power:
|
| 293 |
size /= power
|
| 294 |
n += 1
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
periods = [('ᴅ', 86400), ('ʜ', 3600), ('ᴍ', 60), ('ꜱ', 1)]
|
| 299 |
-
result = ''
|
| 300 |
-
for period_name, period_seconds in periods:
|
| 301 |
-
if seconds >= period_seconds:
|
| 302 |
-
period_value, seconds = divmod(seconds, period_seconds)
|
| 303 |
-
result += f'{int(period_value)}{period_name}'
|
| 304 |
return result
|
| 305 |
|
| 306 |
async def get_shortlink(link):
|
|
|
|
| 307 |
url = f'{SHORT_URL}/api'
|
| 308 |
params = {'api': SHORT_API, 'url': link}
|
| 309 |
try:
|
| 310 |
async with aiohttp.ClientSession() as session:
|
| 311 |
async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
|
| 312 |
data = await response.json()
|
|
|
|
| 313 |
if data["status"] == "success":
|
|
|
|
| 314 |
return data['shortenedUrl']
|
| 315 |
else:
|
| 316 |
-
logger.error(f"Error: {data['message']}")
|
| 317 |
return link
|
| 318 |
except Exception as e:
|
| 319 |
-
logger.error(e)
|
| 320 |
return link
|
| 321 |
|
| 322 |
-
|
| 323 |
-
# from Midukki-RoBoT
|
| 324 |
def extract_time(time_val):
|
|
|
|
| 325 |
if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
|
| 326 |
unit = time_val[-1]
|
| 327 |
time_num = time_val[:-1] # type: str
|
| 328 |
if not time_num.isdigit():
|
|
|
|
| 329 |
return None
|
| 330 |
|
| 331 |
if unit == "s":
|
| 332 |
bantime = datetime.now() + timedelta(seconds=int(time_num))
|
|
|
|
| 333 |
elif unit == "m":
|
| 334 |
bantime = datetime.now() + timedelta(minutes=int(time_num))
|
|
|
|
| 335 |
elif unit == "h":
|
| 336 |
bantime = datetime.now() + timedelta(hours=int(time_num))
|
|
|
|
| 337 |
elif unit == "d":
|
| 338 |
bantime = datetime.now() + timedelta(days=int(time_num))
|
|
|
|
| 339 |
else:
|
| 340 |
-
|
| 341 |
return None
|
|
|
|
| 342 |
return bantime
|
| 343 |
else:
|
|
|
|
| 344 |
return None
|
| 345 |
|
| 346 |
-
|
| 347 |
async def admin_check(message: Message) -> bool:
|
| 348 |
-
|
| 349 |
-
if
|
| 350 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
client = message._client
|
| 352 |
chat_id = message.chat.id
|
| 353 |
user_id = message.from_user.id
|
| 354 |
check_status = await client.get_chat_member(chat_id=chat_id,user_id=user_id)
|
| 355 |
admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
|
| 356 |
-
if check_status.status not in admin_strings:
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
async def admin_filter(filt, client, message):
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
|
|
|
| 34 |
GP_SPELL = {}
|
| 35 |
|
| 36 |
async def is_subscribed(bot, query):
|
| 37 |
+
logger.info(f"Checking subscription for user_id: {query.from_user.id} in AUTH_CHANNEL: {AUTH_CHANNEL}")
|
| 38 |
try:
|
| 39 |
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
|
| 40 |
+
logger.debug(f"User {query.from_user.id} is subscribed.")
|
| 41 |
except UserNotParticipant:
|
| 42 |
+
logger.debug(f"User {query.from_user.id} is not subscribed.")
|
| 43 |
pass
|
| 44 |
except Exception as e:
|
| 45 |
+
logger.error(f"Error checking subscription: {e}")
|
| 46 |
print(e)
|
| 47 |
else:
|
| 48 |
if user.status != enums.ChatMemberStatus.BANNED:
|
| 49 |
+
logger.debug(f"User {query.from_user.id} is not banned.")
|
| 50 |
return True
|
| 51 |
+
logger.debug(f"User {query.from_user.id} is not subscribed.")
|
| 52 |
return False
|
| 53 |
|
|
|
|
| 54 |
async def get_poster(query, bulk=False, id=False, file=None):
|
| 55 |
+
logger.info(f"Fetching poster for query: {query}, bulk: {bulk}, id: {id}, file: {file}")
|
| 56 |
imdb = Cinemagoer()
|
| 57 |
if not id:
|
| 58 |
query = (query.strip()).lower()
|
|
|
|
| 61 |
if year:
|
| 62 |
year = list_to_str(year[:1])
|
| 63 |
title = (query.replace(year, "")).strip()
|
| 64 |
+
logger.debug(f"Extracted year: {year}, title: {title}")
|
| 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 |
+
logger.debug(f"Extracted year from file: {year}")
|
| 70 |
else:
|
| 71 |
year = None
|
| 72 |
+
logger.debug("Year not found.")
|
| 73 |
try:
|
| 74 |
+
movieid = imdb.search_movie(title.lower(), results=10)
|
| 75 |
+
logger.debug(f"Found movie IDs: {movieid}")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.error(f"Error searching movie: {e}")
|
| 78 |
+
return None
|
| 79 |
if not movieid:
|
| 80 |
+
logger.debug("No movie IDs found.")
|
| 81 |
return None
|
| 82 |
if year:
|
| 83 |
filtered=list(filter(lambda k: str(k.get('year')) == str(year), movieid))
|
| 84 |
if not filtered:
|
| 85 |
filtered = movieid
|
| 86 |
+
logger.debug("No filtered results. Using original results.")
|
| 87 |
+
logger.debug(f"Filtered results: {filtered}")
|
| 88 |
else:
|
| 89 |
filtered = movieid
|
| 90 |
+
logger.debug("Using original results.")
|
| 91 |
movieid=list(filter(lambda k: k.get('kind') in ['movie', 'tv series'], filtered))
|
| 92 |
if not movieid:
|
| 93 |
movieid = filtered
|
| 94 |
+
logger.debug("No movie or tv series results. Using original results.")
|
| 95 |
+
logger.debug(f"Final movie IDs: {movieid}")
|
| 96 |
if bulk:
|
| 97 |
+
logger.debug("Returning bulk results.")
|
| 98 |
return movieid
|
| 99 |
movieid = movieid[0].movieID
|
| 100 |
+
logger.debug(f"Selected movie ID: {movieid}")
|
| 101 |
else:
|
| 102 |
movieid = query
|
| 103 |
+
logger.debug(f"Using provided movie ID: {movieid}")
|
| 104 |
movie = imdb.get_movie(movieid)
|
| 105 |
if movie.get("original air date"):
|
| 106 |
date = movie["original air date"]
|
| 107 |
+
logger.debug(f"Original air date: {date}")
|
| 108 |
elif movie.get("year"):
|
| 109 |
date = movie.get("year")
|
| 110 |
+
logger.debug(f"Year: {date}")
|
| 111 |
else:
|
| 112 |
date = "N/A"
|
| 113 |
+
logger.debug("Date not found. Setting to N/A.")
|
| 114 |
plot = ""
|
| 115 |
if not LONG_IMDB_DESCRIPTION:
|
| 116 |
plot = movie.get('plot')
|
| 117 |
if plot and len(plot) > 0:
|
| 118 |
plot = plot[0]
|
| 119 |
+
logger.debug(f"Plot: {plot}")
|
| 120 |
else:
|
| 121 |
plot = movie.get('plot outline')
|
| 122 |
+
logger.debug(f"Plot outline: {plot}")
|
| 123 |
if plot and len(plot) > 800:
|
| 124 |
plot = plot[0:800] + "..."
|
| 125 |
+
logger.debug(f"Truncated plot: {plot}")
|
| 126 |
return {
|
| 127 |
'title': movie.get('title'),
|
| 128 |
'votes': movie.get('votes'),
|
|
|
|
| 152 |
'rating': str(movie.get("rating")),
|
| 153 |
'url':f'https://www.imdb.com/title/tt{movieid}'
|
| 154 |
}
|
| 155 |
+
|
| 156 |
def list_to_str(k):
|
| 157 |
+
logger.debug(f"Converting list to string: {k}")
|
| 158 |
+
if not k:
|
| 159 |
+
logger.debug("List is empty. Returning 'N/A'.")
|
| 160 |
+
return "N/A"
|
| 161 |
+
elif len(k) == 1:
|
| 162 |
+
logger.debug(f"List has one element. Returning: {k[0]}")
|
| 163 |
+
return str(k[0])
|
| 164 |
elif MAX_LIST_ELM:
|
| 165 |
k = k[:int(MAX_LIST_ELM)]
|
| 166 |
+
result = ' '.join(f'{elem}, ' for elem in k)
|
| 167 |
+
logger.debug(f"Truncated list to {MAX_LIST_ELM} elements. Returning: {result}")
|
| 168 |
+
return result
|
| 169 |
else:
|
| 170 |
+
result = ' '.join(f'{elem}, ' for elem in k)
|
| 171 |
+
logger.debug(f"Returning full list as string: {result}")
|
| 172 |
+
return result
|
| 173 |
|
| 174 |
__repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
|
| 175 |
+
logger.debug(f"Repository URL: {__repo__}")
|
| 176 |
__version__ = "PROFESSOR-BOT ᴠ4.5.0"
|
| 177 |
+
logger.debug(f"Version: {__version__}")
|
| 178 |
__license__ = "GNU GENERAL PUBLIC LICENSE V2"
|
| 179 |
+
logger.debug(f"License: {__license__}")
|
| 180 |
__copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
|
| 181 |
+
logger.debug(f"Copyright: {__copyright__}")
|
| 182 |
|
| 183 |
async def search_gagala(text):
|
| 184 |
+
logger.info(f"Searching Google for text: {text}")
|
| 185 |
usr_agent = {
|
| 186 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
|
| 187 |
+
}
|
|
|
|
| 188 |
text = text.replace(" ", '+')
|
| 189 |
url = f'https://www.google.com/search?q={text}'
|
| 190 |
response = requests.get(url, headers=usr_agent)
|
| 191 |
response.raise_for_status()
|
| 192 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 193 |
+
titles = soup.find_all('h3')
|
| 194 |
+
result = [title.getText() for title in titles]
|
| 195 |
+
logger.debug(f"Found titles: {result}")
|
| 196 |
+
return result
|
| 197 |
|
| 198 |
async def get_settings(group_id):
|
| 199 |
+
logger.info(f"Getting settings for group_id: {group_id}")
|
| 200 |
settings = temp.SETTINGS.get(group_id)
|
| 201 |
if not settings:
|
| 202 |
settings = await db.get_settings(group_id)
|
| 203 |
temp.SETTINGS[group_id] = settings
|
| 204 |
+
logger.debug(f"Settings retrieved from database: {settings}")
|
| 205 |
+
else:
|
| 206 |
+
logger.debug(f"Settings retrieved from cache: {settings}")
|
| 207 |
return settings
|
| 208 |
|
| 209 |
async def save_group_settings(group_id, key, value):
|
| 210 |
+
logger.info(f"Saving setting {key} with value {value} for group_id: {group_id}")
|
| 211 |
current = await get_settings(group_id)
|
| 212 |
current[key] = value
|
| 213 |
temp.SETTINGS[group_id] = current
|
| 214 |
await db.update_settings(group_id, current)
|
| 215 |
+
logger.debug(f"Updated settings: {current}")
|
| 216 |
+
|
| 217 |
def get_size(size):
|
| 218 |
+
logger.debug(f"Converting size: {size}")
|
| 219 |
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
|
| 220 |
size = float(size)
|
| 221 |
i = 0
|
| 222 |
while size >= 1024.0 and i < len(units):
|
| 223 |
i += 1
|
| 224 |
size /= 1024.0
|
| 225 |
+
result = "%.2f %s" % (size, units[i])
|
| 226 |
+
logger.debug(f"Converted size: {result}")
|
| 227 |
+
return result
|
| 228 |
|
| 229 |
def get_file_id(msg: Message):
|
| 230 |
+
logger.debug(f"Getting file ID from message: {msg}")
|
| 231 |
+
if not msg.media:
|
| 232 |
+
logger.debug("No media in message.")
|
| 233 |
+
return None
|
| 234 |
for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
|
| 235 |
obj = getattr(msg, message_type)
|
| 236 |
if obj:
|
| 237 |
setattr(obj, "message_type", message_type)
|
| 238 |
+
logger.debug(f"Found file ID: {obj.file_id}")
|
| 239 |
return obj
|
| 240 |
|
|
|
|
| 241 |
def extract_user(message: Message) -> Union[int, str]:
|
| 242 |
+
logger.debug(f"Extracting user from message: {message}")
|
| 243 |
user_id = None
|
| 244 |
user_first_name = None
|
| 245 |
if message.reply_to_message:
|
| 246 |
user_id = message.reply_to_message.from_user.id
|
| 247 |
user_first_name = message.reply_to_message.from_user.first_name
|
| 248 |
+
logger.debug(f"User extracted from reply: {user_id}, {user_first_name}")
|
| 249 |
elif len(message.command) > 1:
|
| 250 |
if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
|
| 251 |
required_entity = message.entities[1]
|
| 252 |
user_id = required_entity.user.id
|
| 253 |
user_first_name = required_entity.user.first_name
|
| 254 |
+
logger.debug(f"User extracted from text mention: {user_id}, {user_first_name}")
|
| 255 |
else:
|
| 256 |
user_id = message.command[1]
|
| 257 |
user_first_name = user_id
|
| 258 |
+
logger.debug(f"User extracted from command: {user_id}, {user_first_name}")
|
| 259 |
+
try:
|
| 260 |
+
user_id = int(user_id)
|
| 261 |
+
logger.debug(f"Converted user_id to integer: {user_id}")
|
| 262 |
+
except ValueError:
|
| 263 |
+
logger.debug("Failed to convert user_id to integer.")
|
| 264 |
+
pass
|
| 265 |
else:
|
| 266 |
user_id = message.from_user.id
|
| 267 |
user_first_name = message.from_user.first_name
|
| 268 |
+
logger.debug(f"User extracted from message sender: {user_id}, {user_first_name}")
|
| 269 |
return (user_id, user_first_name)
|
| 270 |
|
|
|
|
| 271 |
def split_quotes(text: str) -> List:
|
| 272 |
+
logger.debug(f"Splitting quotes from text: {text}")
|
| 273 |
if not any(text.startswith(char) for char in START_CHAR):
|
| 274 |
+
result = text.split(None, 1)
|
| 275 |
+
logger.debug(f"No quotes found. Split result: {result}")
|
| 276 |
+
return result
|
| 277 |
counter = 1 # ignore first char -> is some kind of quote
|
| 278 |
while counter < len(text):
|
| 279 |
if text[counter] == "\\":
|
|
|
|
| 282 |
break
|
| 283 |
counter += 1
|
| 284 |
else:
|
| 285 |
+
result = text.split(None, 1)
|
| 286 |
+
logger.debug(f"No closing quote found. Split result: {result}")
|
| 287 |
+
return result
|
| 288 |
|
| 289 |
# 1 to avoid starting quote, and counter is exclusive so avoids ending
|
| 290 |
key = remove_escapes(text[1:counter].strip())
|
|
|
|
| 292 |
rest = text[counter + 1:].strip()
|
| 293 |
if not key:
|
| 294 |
key = text[0] + text[0]
|
| 295 |
+
logger.debug(f"No key found. Using default key: {key}")
|
| 296 |
+
result = list(filter(None, [key, rest]))
|
| 297 |
+
logger.debug(f"Split result: {result}")
|
| 298 |
+
return result
|
| 299 |
|
| 300 |
def parser(text, keyword, cb_data):
|
| 301 |
+
logger.debug(f"Parsing text: {text}, keyword: {keyword}, cb_data: {cb_data}")
|
| 302 |
+
if "buttonalert" in text:
|
| 303 |
+
text = (text.replace("\n", "\\n").replace("\t", "\\t"))
|
| 304 |
+
logger.debug(f"Text after replacing newline and tab: {text}")
|
| 305 |
buttons = []
|
| 306 |
note_data = ""
|
| 307 |
prev = 0
|
|
|
|
| 321 |
# create a thruple with button label, url, and newline status
|
| 322 |
if bool(match.group(5)) and buttons:
|
| 323 |
buttons[-1].append(InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}"))
|
| 324 |
+
logger.debug(f"Added buttonalert button: {match.group(2)}, {match.group(4)}, {match.group(5)}")
|
| 325 |
else:
|
| 326 |
buttons.append([InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}")])
|
| 327 |
+
logger.debug(f"Created buttonalert button: {match.group(2)}, {match.group(4)}, {match.group(5)}")
|
| 328 |
i += 1
|
| 329 |
alerts.append(match.group(4))
|
| 330 |
+
logger.debug(f"Added alert: {match.group(4)}")
|
| 331 |
elif bool(match.group(5)) and buttons:
|
| 332 |
buttons[-1].append(InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", "")))
|
| 333 |
+
logger.debug(f"Added button: {match.group(2)}, {match.group(4)}")
|
| 334 |
else:
|
| 335 |
buttons.append([InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", ""))])
|
| 336 |
+
logger.debug(f"Created button: {match.group(2)}, {match.group(4)}")
|
| 337 |
else:
|
| 338 |
note_data += text[prev:to_check]
|
| 339 |
prev = match.start(1) - 1
|
| 340 |
+
logger.debug(f"Escaped button: {match.group(2)}")
|
| 341 |
+
else:
|
| 342 |
+
note_data += text[prev:]
|
| 343 |
+
logger.debug(f"Note data after parsing: {note_data}")
|
| 344 |
+
try:
|
| 345 |
+
result = (note_data, buttons, alerts)
|
| 346 |
+
logger.debug(f"Parsing successful. Result: {result}")
|
| 347 |
+
return result
|
| 348 |
+
except Exception as e:
|
| 349 |
+
logger.error(f"Parsing failed: {e}")
|
| 350 |
+
return note_data, buttons, None
|
| 351 |
|
| 352 |
def remove_escapes(text: str) -> str:
|
| 353 |
+
logger.debug(f"Removing escapes from text: {text}")
|
| 354 |
res = ""
|
| 355 |
is_escaped = False
|
| 356 |
for counter in range(len(text)):
|
|
|
|
| 361 |
is_escaped = True
|
| 362 |
else:
|
| 363 |
res += text[counter]
|
| 364 |
+
logger.debug(f"Processed character: {text[counter]}, result so far: {res}")
|
| 365 |
+
logger.debug(f"Final result after removing escapes: {res}")
|
| 366 |
return res
|
|
|
|
| 367 |
|
| 368 |
def humanbytes(size):
|
| 369 |
+
logger.debug(f"Converting size to human-readable format: {size}")
|
| 370 |
if not size:
|
| 371 |
+
logger.debug("Size is zero. Returning empty string.")
|
| 372 |
return ""
|
| 373 |
power = 2**10
|
| 374 |
n = 0
|
|
|
|
| 376 |
while size > power:
|
| 377 |
size /= power
|
| 378 |
n += 1
|
| 379 |
+
logger.debug(f"Converted size: {size}, power: {power}, n: {n}")
|
| 380 |
+
result = str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
|
| 381 |
+
logger.debug(f"Human-readable size: {result}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
return result
|
| 383 |
|
| 384 |
async def get_shortlink(link):
|
| 385 |
+
logger.info(f"Generating shortlink for link: {link}")
|
| 386 |
url = f'{SHORT_URL}/api'
|
| 387 |
params = {'api': SHORT_API, 'url': link}
|
| 388 |
try:
|
| 389 |
async with aiohttp.ClientSession() as session:
|
| 390 |
async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
|
| 391 |
data = await response.json()
|
| 392 |
+
logger.debug(f"Shortlink API response: {data}")
|
| 393 |
if data["status"] == "success":
|
| 394 |
+
logger.debug(f"Shortlink generated: {data['shortenedUrl']}")
|
| 395 |
return data['shortenedUrl']
|
| 396 |
else:
|
| 397 |
+
logger.error(f"Error generating shortlink: {data['message']}")
|
| 398 |
return link
|
| 399 |
except Exception as e:
|
| 400 |
+
logger.error(f"Exception generating shortlink: {e}")
|
| 401 |
return link
|
| 402 |
|
|
|
|
|
|
|
| 403 |
def extract_time(time_val):
|
| 404 |
+
logger.debug(f"Extracting time from time_val: {time_val}")
|
| 405 |
if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
|
| 406 |
unit = time_val[-1]
|
| 407 |
time_num = time_val[:-1] # type: str
|
| 408 |
if not time_num.isdigit():
|
| 409 |
+
logger.debug("Time value is not a digit.")
|
| 410 |
return None
|
| 411 |
|
| 412 |
if unit == "s":
|
| 413 |
bantime = datetime.now() + timedelta(seconds=int(time_num))
|
| 414 |
+
logger.debug(f"Bantime set for seconds: {bantime}")
|
| 415 |
elif unit == "m":
|
| 416 |
bantime = datetime.now() + timedelta(minutes=int(time_num))
|
| 417 |
+
logger.debug(f"Bantime set for minutes: {bantime}")
|
| 418 |
elif unit == "h":
|
| 419 |
bantime = datetime.now() + timedelta(hours=int(time_num))
|
| 420 |
+
logger.debug(f"Bantime set for hours: {bantime}")
|
| 421 |
elif unit == "d":
|
| 422 |
bantime = datetime.now() + timedelta(days=int(time_num))
|
| 423 |
+
logger.debug(f"Bantime set for days: {bantime}")
|
| 424 |
else:
|
| 425 |
+
logger.debug("Invalid time unit.")
|
| 426 |
return None
|
| 427 |
+
logger.debug(f"Extracted bantime: {bantime}")
|
| 428 |
return bantime
|
| 429 |
else:
|
| 430 |
+
logger.debug("Time value does not end with s, m, h, or d.")
|
| 431 |
return None
|
| 432 |
|
|
|
|
| 433 |
async def admin_check(message: Message) -> bool:
|
| 434 |
+
logger.info(f"Checking admin status for message: {message}")
|
| 435 |
+
if not message.from_user:
|
| 436 |
+
logger.debug("Message does not have a from_user.")
|
| 437 |
+
return False
|
| 438 |
+
if message.chat.type not in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
|
| 439 |
+
logger.debug("Chat type is not GROUP or SUPERGROUP.")
|
| 440 |
+
return False
|
| 441 |
+
if message.from_user.id in [777000, 1087968824]:
|
| 442 |
+
logger.debug("User is a system user.")
|
| 443 |
+
return True
|
| 444 |
client = message._client
|
| 445 |
chat_id = message.chat.id
|
| 446 |
user_id = message.from_user.id
|
| 447 |
check_status = await client.get_chat_member(chat_id=chat_id,user_id=user_id)
|
| 448 |
admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
|
| 449 |
+
if check_status.status not in admin_strings:
|
| 450 |
+
logger.debug("User is not an admin.")
|
| 451 |
+
return False
|
| 452 |
+
else:
|
| 453 |
+
logger.debug("User is an admin.")
|
| 454 |
+
return True
|
| 455 |
|
| 456 |
async def admin_filter(filt, client, message):
|
| 457 |
+
logger.info(f"Applying admin filter for message: {message}")
|
| 458 |
+
result = await admin_check(message)
|
| 459 |
+
logger.debug(f"Admin filter result: {result}")
|
| 460 |
+
return result
|
|
|
|
|
|
|
|
|