Update utils.py
Browse files
utils.py
CHANGED
|
@@ -6,10 +6,11 @@ from info import AUTH_CHANNEL, LONG_IMDB_DESCRIPTION, MAX_LIST_ELM, SHORT_URL, S
|
|
| 6 |
from imdb import Cinemagoer
|
| 7 |
from typing import Union, List
|
| 8 |
from datetime import datetime, timedelta
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
logger.setLevel(logging.INFO)
|
| 12 |
|
|
|
|
|
|
|
| 13 |
|
| 14 |
BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))")
|
| 15 |
BANNED = {}
|
|
@@ -33,31 +34,21 @@ class temp(object):
|
|
| 33 |
GP_SPELL = {}
|
| 34 |
|
| 35 |
async def is_subscribed(bot, query):
|
| 36 |
-
"""
|
| 37 |
-
Check if a user is subscribed to a specific channel.
|
| 38 |
-
"""
|
| 39 |
-
logger.info(f"Checking if user {query.from_user.id} is subscribed to channel {AUTH_CHANNEL}.")
|
| 40 |
try:
|
| 41 |
user = await bot.get_chat_member(AUTH_CHANNEL, query.from_user.id)
|
| 42 |
-
logger.info(f"User {query.from_user.id} is subscribed to channel {AUTH_CHANNEL}.")
|
| 43 |
except UserNotParticipant:
|
| 44 |
-
logger.
|
| 45 |
pass
|
| 46 |
except Exception as e:
|
| 47 |
logger.error(f"Error checking subscription for user {query.from_user.id}: {e}")
|
| 48 |
print(e)
|
| 49 |
else:
|
| 50 |
if user.status != enums.ChatMemberStatus.BANNED:
|
| 51 |
-
logger.
|
| 52 |
return True
|
| 53 |
-
logger.info(f"User {query.from_user.id} is not subscribed or is banned in channel {AUTH_CHANNEL}.")
|
| 54 |
return False
|
| 55 |
|
| 56 |
async def get_poster(query, bulk=False, id=False, file=None):
|
| 57 |
-
"""
|
| 58 |
-
Fetch movie details from IMDb.
|
| 59 |
-
"""
|
| 60 |
-
logger.info(f"Fetching poster for query: {query}, bulk: {bulk}, id: {id}, file: {file}.")
|
| 61 |
imdb = Cinemagoer()
|
| 62 |
if not id:
|
| 63 |
query = (query.strip()).lower()
|
|
@@ -73,31 +64,27 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 73 |
else:
|
| 74 |
year = None
|
| 75 |
try:
|
| 76 |
-
|
| 77 |
-
logger.info(f"Found {len(movieid)} movie results for title: {title}.")
|
| 78 |
except Exception as e:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
if not movieid:
|
| 82 |
-
logger.
|
| 83 |
return None
|
| 84 |
if year:
|
| 85 |
-
filtered
|
| 86 |
if not filtered:
|
| 87 |
filtered = movieid
|
| 88 |
else:
|
| 89 |
filtered = movieid
|
| 90 |
-
movieid
|
| 91 |
if not movieid:
|
| 92 |
movieid = filtered
|
| 93 |
if bulk:
|
| 94 |
-
|
| 95 |
-
return filtered
|
| 96 |
movieid = movieid[0].movieID
|
| 97 |
-
logger.info(f"Selected movie ID: {movieid}.")
|
| 98 |
else:
|
| 99 |
movieid = query
|
| 100 |
-
logger.info(f"Using provided movie ID: {movieid}.")
|
| 101 |
movie = imdb.get_movie(movieid)
|
| 102 |
if movie.get("original air date"):
|
| 103 |
date = movie["original air date"]
|
|
@@ -115,7 +102,6 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 115 |
if plot and len(plot) > 800:
|
| 116 |
plot = plot[0:800] + "..."
|
| 117 |
|
| 118 |
-
logger.info(f"Movie details fetched: {movie.get('title')}, Year: {date}, Plot: {plot}.")
|
| 119 |
return {
|
| 120 |
'title': movie.get('title'),
|
| 121 |
'votes': movie.get('votes'),
|
|
@@ -131,10 +117,10 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 131 |
"certificates": list_to_str(movie.get("certificates")),
|
| 132 |
"languages": list_to_str(movie.get("languages")),
|
| 133 |
"director": list_to_str(movie.get("director")),
|
| 134 |
-
"writer":
|
| 135 |
-
"producer":
|
| 136 |
-
"composer":
|
| 137 |
-
"cinematographer":
|
| 138 |
"music_team": list_to_str(movie.get("music department")),
|
| 139 |
"distributors": list_to_str(movie.get("distributors")),
|
| 140 |
'release_date': date,
|
|
@@ -143,165 +129,91 @@ async def get_poster(query, bulk=False, id=False, file=None):
|
|
| 143 |
'poster': movie.get('full-size cover url'),
|
| 144 |
'plot': plot,
|
| 145 |
'rating': str(movie.get("rating")),
|
| 146 |
-
'url':
|
| 147 |
}
|
| 148 |
|
| 149 |
def list_to_str(k):
|
| 150 |
-
""
|
| 151 |
-
|
| 152 |
-
"""
|
| 153 |
-
logger.debug(f"Converting list to string: {k}")
|
| 154 |
-
if not k:
|
| 155 |
-
logger.debug("List is empty, returning 'N/A'.")
|
| 156 |
-
return "N/A"
|
| 157 |
-
elif len(k) == 1:
|
| 158 |
-
logger.debug(f"List has one element, returning: {k[0]}")
|
| 159 |
-
return str(k[0])
|
| 160 |
elif MAX_LIST_ELM:
|
| 161 |
k = k[:int(MAX_LIST_ELM)]
|
| 162 |
-
|
| 163 |
-
logger.debug(f"List truncated to {MAX_LIST_ELM} elements, returning: {result}")
|
| 164 |
-
return result
|
| 165 |
else:
|
| 166 |
-
|
| 167 |
-
logger.debug(f"Returning full list as string: {result}")
|
| 168 |
-
return result
|
| 169 |
|
| 170 |
__repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
|
| 171 |
-
logger.info(f"Repository URL set to: {__repo__}")
|
| 172 |
-
|
| 173 |
__version__ = "PROFESSOR-BOT ᴠ4.5.0"
|
| 174 |
-
logger.info(f"Version set to: {__version__}")
|
| 175 |
-
|
| 176 |
__license__ = "GNU GENERAL PUBLIC LICENSE V2"
|
| 177 |
-
logger.info(f"License set to: {__license__}")
|
| 178 |
-
|
| 179 |
__copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
|
| 180 |
-
logger.info(f"Copyright set to: {__copyright__}")
|
| 181 |
|
| 182 |
async def search_gagala(text):
|
| 183 |
-
"""
|
| 184 |
-
Search Google for a given text.
|
| 185 |
-
"""
|
| 186 |
-
logger.info(f"Searching Google for text: {text}")
|
| 187 |
usr_agent = {
|
| 188 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
|
| 189 |
'Chrome/61.0.3163.100 Safari/537.36'
|
| 190 |
-
|
| 191 |
text = text.replace(" ", '+')
|
| 192 |
url = f'https://www.google.com/search?q={text}'
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
response.raise_for_status()
|
| 196 |
-
logger.info(f"Google search successful for text: {text}")
|
| 197 |
-
except Exception as e:
|
| 198 |
-
logger.error(f"Error searching Google: {e}")
|
| 199 |
-
return []
|
| 200 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 201 |
titles = soup.find_all('h3')
|
| 202 |
-
|
| 203 |
-
logger.info(f"Found {len(result)} Google search results.")
|
| 204 |
-
return result
|
| 205 |
|
| 206 |
async def get_settings(group_id):
|
| 207 |
-
"""
|
| 208 |
-
Get settings for a specific group.
|
| 209 |
-
"""
|
| 210 |
-
logger.info(f"Getting settings for group ID: {group_id}")
|
| 211 |
settings = temp.SETTINGS.get(group_id)
|
| 212 |
if not settings:
|
| 213 |
settings = await db.get_settings(group_id)
|
| 214 |
temp.SETTINGS[group_id] = settings
|
| 215 |
-
logger.info(f"Settings retrieved from database for group ID: {group_id}")
|
| 216 |
-
else:
|
| 217 |
-
logger.info(f"Settings retrieved from cache for group ID: {group_id}")
|
| 218 |
return settings
|
| 219 |
|
| 220 |
async def save_group_settings(group_id, key, value):
|
| 221 |
-
"""
|
| 222 |
-
Save settings for a specific group.
|
| 223 |
-
"""
|
| 224 |
-
logger.info(f"Saving setting '{key}' with value '{value}' for group ID: {group_id}")
|
| 225 |
current = await get_settings(group_id)
|
| 226 |
current[key] = value
|
| 227 |
temp.SETTINGS[group_id] = current
|
| 228 |
await db.update_settings(group_id, current)
|
| 229 |
-
|
| 230 |
-
|
| 231 |
def get_size(size):
|
| 232 |
-
"""
|
| 233 |
-
Convert file size in bytes to a human-readable format.
|
| 234 |
-
"""
|
| 235 |
-
logger.debug(f"Converting size {size} bytes to human-readable format.")
|
| 236 |
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
|
| 237 |
size = float(size)
|
| 238 |
i = 0
|
| 239 |
while size >= 1024.0 and i < len(units):
|
| 240 |
i += 1
|
| 241 |
size /= 1024.0
|
| 242 |
-
|
| 243 |
-
logger.debug(f"Converted size to: {result}")
|
| 244 |
-
return result
|
| 245 |
|
| 246 |
def get_file_id(msg: Message):
|
| 247 |
-
|
| 248 |
-
Extract file ID from a message.
|
| 249 |
-
"""
|
| 250 |
-
logger.debug(f"Extracting file ID from message: {msg.id}")
|
| 251 |
-
if not msg.media:
|
| 252 |
-
logger.debug("Message does not contain media.")
|
| 253 |
-
return None
|
| 254 |
for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
|
| 255 |
obj = getattr(msg, message_type)
|
| 256 |
if obj:
|
| 257 |
setattr(obj, "message_type", message_type)
|
| 258 |
-
logger.debug(f"File ID extracted: {obj.file_id}, Type: {message_type}")
|
| 259 |
return obj
|
| 260 |
-
logger.debug("No file ID found in message.")
|
| 261 |
-
return None
|
| 262 |
|
| 263 |
def extract_user(message: Message) -> Union[int, str]:
|
| 264 |
-
"""
|
| 265 |
-
Extract user ID and first name from a message.
|
| 266 |
-
"""
|
| 267 |
-
logger.debug(f"Extracting user from message: {message.id}")
|
| 268 |
user_id = None
|
| 269 |
user_first_name = None
|
| 270 |
if message.reply_to_message:
|
| 271 |
user_id = message.reply_to_message.from_user.id
|
| 272 |
user_first_name = message.reply_to_message.from_user.first_name
|
| 273 |
-
logger.debug(f"User extracted from reply: ID: {user_id}, First Name: {user_first_name}")
|
| 274 |
elif len(message.command) > 1:
|
| 275 |
if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
|
| 276 |
required_entity = message.entities[1]
|
| 277 |
user_id = required_entity.user.id
|
| 278 |
user_first_name = required_entity.user.first_name
|
| 279 |
-
logger.debug(f"User extracted from text mention: ID: {user_id}, First Name: {user_first_name}")
|
| 280 |
else:
|
| 281 |
user_id = message.command[1]
|
| 282 |
user_first_name = user_id
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
except ValueError:
|
| 287 |
-
logger.debug("User ID conversion failed, keeping as string.")
|
| 288 |
-
pass
|
| 289 |
-
logger.debug(f"User extracted from command: ID: {user_id}, First Name: {user_first_name}")
|
| 290 |
else:
|
| 291 |
user_id = message.from_user.id
|
| 292 |
user_first_name = message.from_user.first_name
|
| 293 |
-
logger.debug(f"User extracted from sender: ID: {user_id}, First Name: {user_first_name}")
|
| 294 |
return (user_id, user_first_name)
|
| 295 |
|
| 296 |
def split_quotes(text: str) -> List:
|
| 297 |
-
"""
|
| 298 |
-
Split a quoted text into key and rest.
|
| 299 |
-
"""
|
| 300 |
-
logger.debug(f"Splitting quotes from text: {text}")
|
| 301 |
if not any(text.startswith(char) for char in START_CHAR):
|
| 302 |
-
|
| 303 |
-
logger.debug(f"Text does not start with quote, split into key: {key}, rest: {rest}")
|
| 304 |
-
return [key, rest]
|
| 305 |
counter = 1 # ignore first char -> is some kind of quote
|
| 306 |
while counter < len(text):
|
| 307 |
if text[counter] == "\\":
|
|
@@ -310,9 +222,7 @@ def split_quotes(text: str) -> List:
|
|
| 310 |
break
|
| 311 |
counter += 1
|
| 312 |
else:
|
| 313 |
-
|
| 314 |
-
logger.debug(f"Text does not end with quote, split into key: {key}, rest: {rest}")
|
| 315 |
-
return [key, rest]
|
| 316 |
|
| 317 |
# 1 to avoid starting quote, and counter is exclusive so avoids ending
|
| 318 |
key = remove_escapes(text[1:counter].strip())
|
|
@@ -320,16 +230,10 @@ def split_quotes(text: str) -> List:
|
|
| 320 |
rest = text[counter + 1:].strip()
|
| 321 |
if not key:
|
| 322 |
key = text[0] + text[0]
|
| 323 |
-
logger.debug(f"Text split into key: {key}, rest: {rest}")
|
| 324 |
return list(filter(None, [key, rest]))
|
| 325 |
|
| 326 |
def parser(text, keyword, cb_data):
|
| 327 |
-
"""
|
| 328 |
-
Parse button URLs and alerts from text.
|
| 329 |
-
"""
|
| 330 |
-
logger.debug(f"Parsing text for buttons and alerts: {text}")
|
| 331 |
-
if "buttonalert" in text:
|
| 332 |
-
text = (text.replace("\n", "\\n").replace("\t", "\\t"))
|
| 333 |
buttons = []
|
| 334 |
note_data = ""
|
| 335 |
prev = 0
|
|
@@ -353,30 +257,18 @@ def parser(text, keyword, cb_data):
|
|
| 353 |
buttons.append([InlineKeyboardButton(match.group(2), callback_data=f"{cb_data}:{i}:{keyword}")])
|
| 354 |
i += 1
|
| 355 |
alerts.append(match.group(4))
|
| 356 |
-
logger.debug(f"Button alert added: Label: {match.group(2)}, Callback Data: {cb_data}:{i}:{keyword}")
|
| 357 |
elif bool(match.group(5)) and buttons:
|
| 358 |
buttons[-1].append(InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", "")))
|
| 359 |
-
logger.debug(f"URL button added: Label: {match.group(2)}, URL: {match.group(4)}")
|
| 360 |
else:
|
| 361 |
buttons.append([InlineKeyboardButton(match.group(2), url=match.group(4).replace(" ", ""))])
|
| 362 |
-
logger.debug(f"URL button added: Label: {match.group(2)}, URL: {match.group(4)}")
|
| 363 |
else:
|
| 364 |
note_data += text[prev:to_check]
|
| 365 |
prev = match.start(1) - 1
|
| 366 |
-
else:
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
logger.debug(f"Parsed note data: {note_data}, buttons: {buttons}, alerts: {alerts}")
|
| 370 |
-
return note_data, buttons, alerts
|
| 371 |
-
except Exception as e:
|
| 372 |
-
logger.error(f"Error parsing text: {e}")
|
| 373 |
-
return note_data, buttons, None
|
| 374 |
|
| 375 |
def remove_escapes(text: str) -> str:
|
| 376 |
-
"""
|
| 377 |
-
Remove escape characters from text.
|
| 378 |
-
"""
|
| 379 |
-
logger.debug(f"Removing escapes from text: {text}")
|
| 380 |
res = ""
|
| 381 |
is_escaped = False
|
| 382 |
for counter in range(len(text)):
|
|
@@ -387,16 +279,10 @@ def remove_escapes(text: str) -> str:
|
|
| 387 |
is_escaped = True
|
| 388 |
else:
|
| 389 |
res += text[counter]
|
| 390 |
-
logger.debug(f"Escapes removed, resulting text: {res}")
|
| 391 |
return res
|
| 392 |
|
| 393 |
def humanbytes(size):
|
| 394 |
-
"""
|
| 395 |
-
Convert size in bytes to a human-readable format.
|
| 396 |
-
"""
|
| 397 |
-
logger.debug(f"Converting size {size} bytes to human-readable format.")
|
| 398 |
if not size:
|
| 399 |
-
logger.debug("Size is zero, returning empty string.")
|
| 400 |
return ""
|
| 401 |
power = 2**10
|
| 402 |
n = 0
|
|
@@ -404,29 +290,18 @@ def humanbytes(size):
|
|
| 404 |
while size > power:
|
| 405 |
size /= power
|
| 406 |
n += 1
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
return result
|
| 410 |
-
|
| 411 |
def get_time(seconds):
|
| 412 |
-
"""
|
| 413 |
-
Convert seconds to a human-readable time format.
|
| 414 |
-
"""
|
| 415 |
-
logger.debug(f"Converting {seconds} seconds to human-readable time format.")
|
| 416 |
periods = [('ᴅ', 86400), ('ʜ', 3600), ('ᴍ', 60), ('ꜱ', 1)]
|
| 417 |
result = ''
|
| 418 |
for period_name, period_seconds in periods:
|
| 419 |
if seconds >= period_seconds:
|
| 420 |
period_value, seconds = divmod(seconds, period_seconds)
|
| 421 |
result += f'{int(period_value)}{period_name}'
|
| 422 |
-
logger.debug(f"Converted time to: {result}")
|
| 423 |
return result
|
| 424 |
|
| 425 |
async def get_shortlink(link):
|
| 426 |
-
"""
|
| 427 |
-
Generate a short link using a URL shortener service.
|
| 428 |
-
"""
|
| 429 |
-
logger.info(f"Generating short link for: {link}")
|
| 430 |
url = f'{SHORT_URL}/api'
|
| 431 |
params = {'api': SHORT_API, 'url': link}
|
| 432 |
try:
|
|
@@ -434,26 +309,19 @@ async def get_shortlink(link):
|
|
| 434 |
async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
|
| 435 |
data = await response.json()
|
| 436 |
if data["status"] == "success":
|
| 437 |
-
logger.info(f"Short link generated: {data['shortenedUrl']}")
|
| 438 |
return data['shortenedUrl']
|
| 439 |
else:
|
| 440 |
-
logger.error(f"Error
|
| 441 |
return link
|
| 442 |
except Exception as e:
|
| 443 |
-
logger.error(f"
|
| 444 |
return link
|
| 445 |
|
| 446 |
-
# from Midukki-RoBoT
|
| 447 |
def extract_time(time_val):
|
| 448 |
-
"""
|
| 449 |
-
Extract time from a time value string.
|
| 450 |
-
"""
|
| 451 |
-
logger.debug(f"Extracting time from value: {time_val}")
|
| 452 |
if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
|
| 453 |
unit = time_val[-1]
|
| 454 |
time_num = time_val[:-1] # type: str
|
| 455 |
if not time_num.isdigit():
|
| 456 |
-
logger.debug("Time value is not a digit, returning None.")
|
| 457 |
return None
|
| 458 |
|
| 459 |
if unit == "s":
|
|
@@ -465,48 +333,30 @@ def extract_time(time_val):
|
|
| 465 |
elif unit == "d":
|
| 466 |
bantime = datetime.now() + timedelta(days=int(time_num))
|
| 467 |
else:
|
| 468 |
-
logger.debug("Unknown time unit, returning None.")
|
| 469 |
return None
|
| 470 |
-
logger.debug(f"Extracted time: {bantime}")
|
| 471 |
return bantime
|
| 472 |
else:
|
| 473 |
-
logger.debug("Time value does not end with valid unit, returning None.")
|
| 474 |
return None
|
| 475 |
|
| 476 |
async def admin_check(message: Message) -> bool:
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
logger.debug(f"Checking if user {message.from_user.id} is an admin in chat {message.chat.id}.")
|
| 481 |
-
if not message.from_user:
|
| 482 |
-
logger.debug("Message does not contain a user, returning False.")
|
| 483 |
-
return False
|
| 484 |
-
if message.chat.type not in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
|
| 485 |
-
logger.debug("Chat type is not GROUP or SUPERGROUP, returning False.")
|
| 486 |
-
return False
|
| 487 |
-
if message.from_user.id in [777000, 1087968824]:
|
| 488 |
-
logger.debug("User is a Telegram service account, returning True.")
|
| 489 |
-
return True
|
| 490 |
client = message._client
|
| 491 |
chat_id = message.chat.id
|
| 492 |
user_id = message.from_user.id
|
| 493 |
try:
|
| 494 |
check_status = await client.get_chat_member(chat_id=chat_id, user_id=user_id)
|
| 495 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
except Exception as e:
|
| 497 |
-
logger.error(f"Error checking user
|
| 498 |
-
return False
|
| 499 |
-
admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
|
| 500 |
-
if check_status.status not in admin_strings:
|
| 501 |
-
logger.debug(f"User {user_id} is not an admin, returning False.")
|
| 502 |
return False
|
| 503 |
-
else:
|
| 504 |
-
logger.debug(f"User {user_id} is an admin, returning True.")
|
| 505 |
-
return True
|
| 506 |
|
| 507 |
async def admin_filter(filt, client, message):
|
| 508 |
-
"""
|
| 509 |
-
Filter for admin checks.
|
| 510 |
-
"""
|
| 511 |
-
logger.debug(f"Applying admin filter for message {message.id}.")
|
| 512 |
return await admin_check(message)
|
|
|
|
| 6 |
from imdb import Cinemagoer
|
| 7 |
from typing import Union, List
|
| 8 |
from datetime import datetime, timedelta
|
| 9 |
+
from database.users_chats_db import db
|
| 10 |
+
from bs4 import BeautifulSoup
|
|
|
|
| 11 |
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
logger.setLevel(logging.DEBUG)
|
| 14 |
|
| 15 |
BTN_URL_REGEX = re.compile(r"(\[([^\[]+?)\]\((buttonurl|buttonalert):(?:/{0,2})(.+?)(:same)?\))")
|
| 16 |
BANNED = {}
|
|
|
|
| 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 |
+
logger.debug(f"User {query.from_user.id} is not subscribed to AUTH_CHANNEL")
|
| 41 |
pass
|
| 42 |
except Exception as e:
|
| 43 |
logger.error(f"Error checking subscription for user {query.from_user.id}: {e}")
|
| 44 |
print(e)
|
| 45 |
else:
|
| 46 |
if user.status != enums.ChatMemberStatus.BANNED:
|
| 47 |
+
logger.debug(f"User {query.from_user.id} is subscribed to AUTH_CHANNEL")
|
| 48 |
return True
|
|
|
|
| 49 |
return False
|
| 50 |
|
| 51 |
async def get_poster(query, bulk=False, id=False, file=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
imdb = Cinemagoer()
|
| 53 |
if not id:
|
| 54 |
query = (query.strip()).lower()
|
|
|
|
| 64 |
else:
|
| 65 |
year = None
|
| 66 |
try:
|
| 67 |
+
movieid = imdb.search_movie(title.lower(), results=10)
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
+
logger.error(f"Error searching movie: {e}")
|
| 70 |
+
return None
|
| 71 |
if not movieid:
|
| 72 |
+
logger.debug(f"No movie found for query: {query}")
|
| 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"]
|
|
|
|
| 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'),
|
|
|
|
| 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,
|
|
|
|
| 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 |
|
| 135 |
def list_to_str(k):
|
| 136 |
+
if not k: return "N/A"
|
| 137 |
+
elif len(k) == 1: return str(k[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
elif MAX_LIST_ELM:
|
| 139 |
k = k[:int(MAX_LIST_ELM)]
|
| 140 |
+
return ' '.join(f'{elem}, ' for elem in k)
|
|
|
|
|
|
|
| 141 |
else:
|
| 142 |
+
return ' '.join(f'{elem}, ' for elem in k)
|
|
|
|
|
|
|
| 143 |
|
| 144 |
__repo__ = "https://github.com/MrMKN/PROFESSOR-BOT"
|
|
|
|
|
|
|
| 145 |
__version__ = "PROFESSOR-BOT ᴠ4.5.0"
|
|
|
|
|
|
|
| 146 |
__license__ = "GNU GENERAL PUBLIC LICENSE V2"
|
|
|
|
|
|
|
| 147 |
__copyright__ = "Copyright (C) 2023-present MrMKN <https://github.com/MrMKN>"
|
|
|
|
| 148 |
|
| 149 |
async def search_gagala(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
usr_agent = {
|
| 151 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
|
| 152 |
'Chrome/61.0.3163.100 Safari/537.36'
|
| 153 |
+
}
|
| 154 |
text = text.replace(" ", '+')
|
| 155 |
url = f'https://www.google.com/search?q={text}'
|
| 156 |
+
response = requests.get(url, headers=usr_agent)
|
| 157 |
+
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 159 |
titles = soup.find_all('h3')
|
| 160 |
+
return [title.getText() for title in titles]
|
|
|
|
|
|
|
| 161 |
|
| 162 |
async def get_settings(group_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
settings = temp.SETTINGS.get(group_id)
|
| 164 |
if not settings:
|
| 165 |
settings = await db.get_settings(group_id)
|
| 166 |
temp.SETTINGS[group_id] = settings
|
|
|
|
|
|
|
|
|
|
| 167 |
return settings
|
| 168 |
|
| 169 |
async def save_group_settings(group_id, key, value):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
current = await get_settings(group_id)
|
| 171 |
current[key] = value
|
| 172 |
temp.SETTINGS[group_id] = current
|
| 173 |
await db.update_settings(group_id, current)
|
| 174 |
+
|
|
|
|
| 175 |
def get_size(size):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
|
| 177 |
size = float(size)
|
| 178 |
i = 0
|
| 179 |
while size >= 1024.0 and i < len(units):
|
| 180 |
i += 1
|
| 181 |
size /= 1024.0
|
| 182 |
+
return "%.2f %s" % (size, units[i])
|
|
|
|
|
|
|
| 183 |
|
| 184 |
def get_file_id(msg: Message):
|
| 185 |
+
if not msg.media: return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
for message_type in ("photo", "animation", "audio", "document", "video", "video_note", "voice", "sticker"):
|
| 187 |
obj = getattr(msg, message_type)
|
| 188 |
if obj:
|
| 189 |
setattr(obj, "message_type", message_type)
|
|
|
|
| 190 |
return obj
|
|
|
|
|
|
|
| 191 |
|
| 192 |
def extract_user(message: Message) -> Union[int, str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
user_id = None
|
| 194 |
user_first_name = None
|
| 195 |
if message.reply_to_message:
|
| 196 |
user_id = message.reply_to_message.from_user.id
|
| 197 |
user_first_name = message.reply_to_message.from_user.first_name
|
|
|
|
| 198 |
elif len(message.command) > 1:
|
| 199 |
if (len(message.entities) > 1 and message.entities[1].type == enums.MessageEntityType.TEXT_MENTION):
|
| 200 |
required_entity = message.entities[1]
|
| 201 |
user_id = required_entity.user.id
|
| 202 |
user_first_name = required_entity.user.first_name
|
|
|
|
| 203 |
else:
|
| 204 |
user_id = message.command[1]
|
| 205 |
user_first_name = user_id
|
| 206 |
+
try:
|
| 207 |
+
user_id = int(user_id)
|
| 208 |
+
except ValueError: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
else:
|
| 210 |
user_id = message.from_user.id
|
| 211 |
user_first_name = message.from_user.first_name
|
|
|
|
| 212 |
return (user_id, user_first_name)
|
| 213 |
|
| 214 |
def split_quotes(text: str) -> List:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
if not any(text.startswith(char) for char in START_CHAR):
|
| 216 |
+
return text.split(None, 1)
|
|
|
|
|
|
|
| 217 |
counter = 1 # ignore first char -> is some kind of quote
|
| 218 |
while counter < len(text):
|
| 219 |
if text[counter] == "\\":
|
|
|
|
| 222 |
break
|
| 223 |
counter += 1
|
| 224 |
else:
|
| 225 |
+
return text.split(None, 1)
|
|
|
|
|
|
|
| 226 |
|
| 227 |
# 1 to avoid starting quote, and counter is exclusive so avoids ending
|
| 228 |
key = remove_escapes(text[1:counter].strip())
|
|
|
|
| 230 |
rest = text[counter + 1:].strip()
|
| 231 |
if not key:
|
| 232 |
key = text[0] + text[0]
|
|
|
|
| 233 |
return list(filter(None, [key, rest]))
|
| 234 |
|
| 235 |
def parser(text, keyword, cb_data):
|
| 236 |
+
if "buttonalert" in text: text = (text.replace("\n", "\\n").replace("\t", "\\t"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
buttons = []
|
| 238 |
note_data = ""
|
| 239 |
prev = 0
|
|
|
|
| 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 |
+
else: note_data += text[prev:]
|
| 268 |
+
try: return note_data, buttons, alerts
|
| 269 |
+
except: return note_data, buttons, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
def remove_escapes(text: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
res = ""
|
| 273 |
is_escaped = False
|
| 274 |
for counter in range(len(text)):
|
|
|
|
| 279 |
is_escaped = True
|
| 280 |
else:
|
| 281 |
res += text[counter]
|
|
|
|
| 282 |
return res
|
| 283 |
|
| 284 |
def humanbytes(size):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
if not size:
|
|
|
|
| 286 |
return ""
|
| 287 |
power = 2**10
|
| 288 |
n = 0
|
|
|
|
| 290 |
while size > power:
|
| 291 |
size /= power
|
| 292 |
n += 1
|
| 293 |
+
return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
|
| 294 |
+
|
|
|
|
|
|
|
| 295 |
def get_time(seconds):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
periods = [('ᴅ', 86400), ('ʜ', 3600), ('ᴍ', 60), ('ꜱ', 1)]
|
| 297 |
result = ''
|
| 298 |
for period_name, period_seconds in periods:
|
| 299 |
if seconds >= period_seconds:
|
| 300 |
period_value, seconds = divmod(seconds, period_seconds)
|
| 301 |
result += f'{int(period_value)}{period_name}'
|
|
|
|
| 302 |
return result
|
| 303 |
|
| 304 |
async def get_shortlink(link):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
url = f'{SHORT_URL}/api'
|
| 306 |
params = {'api': SHORT_API, 'url': link}
|
| 307 |
try:
|
|
|
|
| 309 |
async with session.get(url, params=params, raise_for_status=True, ssl=False) as response:
|
| 310 |
data = await response.json()
|
| 311 |
if data["status"] == "success":
|
|
|
|
| 312 |
return data['shortenedUrl']
|
| 313 |
else:
|
| 314 |
+
logger.error(f"Error: {data['message']}")
|
| 315 |
return link
|
| 316 |
except Exception as e:
|
| 317 |
+
logger.error(f"Error getting shortlink: {e}")
|
| 318 |
return link
|
| 319 |
|
|
|
|
| 320 |
def extract_time(time_val):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
if any(time_val.endswith(unit) for unit in ("s", "m", "h", "d")):
|
| 322 |
unit = time_val[-1]
|
| 323 |
time_num = time_val[:-1] # type: str
|
| 324 |
if not time_num.isdigit():
|
|
|
|
| 325 |
return None
|
| 326 |
|
| 327 |
if unit == "s":
|
|
|
|
| 333 |
elif unit == "d":
|
| 334 |
bantime = datetime.now() + timedelta(days=int(time_num))
|
| 335 |
else:
|
|
|
|
| 336 |
return None
|
|
|
|
| 337 |
return bantime
|
| 338 |
else:
|
|
|
|
| 339 |
return None
|
| 340 |
|
| 341 |
async def admin_check(message: Message) -> bool:
|
| 342 |
+
if not message.from_user: return False
|
| 343 |
+
if message.chat.type not in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]: return False
|
| 344 |
+
if message.from_user.id in [777000, 1087968824]: return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
client = message._client
|
| 346 |
chat_id = message.chat.id
|
| 347 |
user_id = message.from_user.id
|
| 348 |
try:
|
| 349 |
check_status = await client.get_chat_member(chat_id=chat_id, user_id=user_id)
|
| 350 |
+
admin_strings = [enums.ChatMemberStatus.OWNER, enums.ChatMemberStatus.ADMINISTRATOR]
|
| 351 |
+
if check_status.status not in admin_strings:
|
| 352 |
+
logger.debug(f"User {user_id} is not an admin in chat {chat_id}")
|
| 353 |
+
return False
|
| 354 |
+
else:
|
| 355 |
+
logger.debug(f"User {user_id} is an admin in chat {chat_id}")
|
| 356 |
+
return True
|
| 357 |
except Exception as e:
|
| 358 |
+
logger.error(f"Error checking admin status for user {user_id} in chat {chat_id}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
return False
|
|
|
|
|
|
|
|
|
|
| 360 |
|
| 361 |
async def admin_filter(filt, client, message):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
return await admin_check(message)
|