Skip to content

Commit

Permalink
Sourcery refactored
Browse files Browse the repository at this point in the history
Sourcery refactored master branch
  • Loading branch information
Awesome-RJ authored Mar 10, 2022
2 parents 91e7179 + 21f5fd5 commit 6c20eb9
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 77 deletions.
20 changes: 10 additions & 10 deletions Bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@
STATS = []

for module_name in ALL_MODULES:
imported_module = importlib.import_module("Bot.modules." + module_name)
imported_module = importlib.import_module(f"Bot.modules.{module_name}")
if not hasattr(imported_module, "__mod_name__"):
imported_module.__mod_name__ = imported_module.__name__

if not imported_module.__mod_name__.lower() in IMPORTED:
if imported_module.__mod_name__.lower() not in IMPORTED:
IMPORTED[imported_module.__mod_name__.lower()] = imported_module
else:
raise Exception("Can't have two modules with the same name! Please change one")

if hasattr(imported_module, "__help__") and imported_module.__help__:
HELPABLE[imported_module.__mod_name__.lower()] = imported_module

if hasattr(imported_module, "__stats__"):
STATS.append(imported_module)

Expand All @@ -39,10 +39,10 @@ def send_help(chat_id, text, keyboard=None):
)


PM_START_TEXT = f"""
Hewwo, uwu >////<.
Tap on /help to know all my commands!
"""
PM_START_TEXT = (
"""\x1fHewwo, uwu >////<.\x1fTap on /help to know all my commands!\x1f"""
)


HELP_STRINGS = f"""
Hello there! My name is *{dispatcher.bot.first_name}*. The lewdest near you.
Expand Down Expand Up @@ -107,7 +107,7 @@ def error_handler(update, context):
payload += f" \n<b>- User</b>: {mention_html(update.effective_user.id, update.effective_user.first_name)}"
# there are more situations when you don't get a chat
if update.effective_chat:
if update.effective_chat.title == None:
if update.effective_chat.title is None:
payload += f" \n<b>- Chat</b>: <i>Bot PM</i>"
else:
payload += (
Expand Down Expand Up @@ -263,7 +263,7 @@ def main():


if __name__ == "__main__":
LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES))
LOGGER.info(f"Successfully loaded modules: {str(ALL_MODULES)}")
LOGGER.info("Using long polling.")
main()
updater.start_polling(timeout=15, read_latency=4)
Expand Down
2 changes: 1 addition & 1 deletion Bot/modules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ def __list_all_modules():
from os.path import dirname, basename, isfile
import glob
# This generates a list of modules in this folder for the * in __main__ to work.
mod_paths = glob.glob(dirname(__file__) + "/*.py")
mod_paths = glob.glob(f'{dirname(__file__)}/*.py')
return [
basename(f)[:-3] for f in mod_paths if isfile(f)
and f.endswith(".py")
Expand Down
32 changes: 16 additions & 16 deletions Bot/modules/anilist.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
def shorten(description, info="anilist.co"):
msg = ""
if len(description) > 700:
description = description[0:500] + "...."
description = description[:500] + "...."
msg += f"\n*Description*: _{description}_[Read More]({info})"
else:
msg += f"\n*Description*:_{description}_"
Expand All @@ -27,17 +27,18 @@ def shorten(description, info="anilist.co"):
def t(milliseconds: int) -> str:
"""Inputs time in milliseconds, to get beautified time,
as string"""
seconds, milliseconds = divmod(int(milliseconds), 1000)
seconds, milliseconds = divmod(milliseconds, 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = (
((str(days) + " Days, ") if days else "")
+ ((str(hours) + " Hours, ") if hours else "")
+ ((str(minutes) + " Minutes, ") if minutes else "")
+ ((str(seconds) + " Seconds, ") if seconds else "")
+ ((str(milliseconds) + " ms, ") if milliseconds else "")
(f'{str(days)} Days, ' if days else "")
+ (f'{str(hours)} Hours, ' if hours else "")
+ (f'{str(minutes)} Minutes, ' if minutes else "")
+ (f'{str(seconds)} Seconds, ' if seconds else "")
+ (f'{str(milliseconds)} ms, ' if milliseconds else "")
)

return tmp[:-2]


Expand Down Expand Up @@ -186,12 +187,11 @@ def anime(update, context):
else:
search = search[1]
variables = {"search": search}
json = (
if json := (
requests.post(url, json={"query": anime_query, "variables": variables})
.json()["data"]
.get("Media", None)
)
if json:
):
msg = f"*{json['title']['romaji']}*(`{json['title']['native']}`)\n*Type*: {json['format']}\n*Status*: {json['status']}\n*Episodes*: {json.get('episodes', 'N/A')}\n*Duration*: {json.get('duration', 'N/A')} Per Ep.\n*Score*: {json['averageScore']}\n*Genres*: `"
for x in json["genres"]:
msg += f"{x}, "
Expand Down Expand Up @@ -257,18 +257,18 @@ def character(update, context):
return
search = search[1]
variables = {"query": search}
json = (
requests.post(url, json={"query": character_query, "variables": variables})
if json := (
requests.post(
url, json={"query": character_query, "variables": variables}
)
.json()["data"]
.get("Character", None)
)
if json:
):
msg = f"*{json.get('name').get('full')}*(`{json.get('name').get('native')}`)\n"
description = f"{json['description']}"
site_url = json.get("siteUrl")
msg += shorten(description, site_url)
image = json.get("image", None)
if image:
if image := json.get("image", None):
image = image.get("large")
update.effective_message.reply_photo(
photo=image, caption=msg, parse_mode=ParseMode.MARKDOWN
Expand Down
38 changes: 16 additions & 22 deletions Bot/modules/helpers/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,49 +20,43 @@ def split_message(msg: str) -> List[str]:
if len(msg) < MAX_MESSAGE_LENGTH:
return [msg]

else:
lines = msg.splitlines(True)
small_msg = ""
result = []
for line in lines:
if len(small_msg) + len(line) < MAX_MESSAGE_LENGTH:
small_msg += line
else:
result.append(small_msg)
small_msg = line
lines = msg.splitlines(True)
small_msg = ""
result = []
for line in lines:
if len(small_msg) + len(line) < MAX_MESSAGE_LENGTH:
small_msg += line
else:
# Else statement at the end of the for loop, so append the leftover string.
result.append(small_msg)
small_msg = line
# Else statement at the end of the for loop, so append the leftover string.
result.append(small_msg)

return result
return result


def paginate_modules(page_n: int, module_dict: Dict, prefix, chat=None) -> List:
if not chat:
modules = sorted(
modules = sorted(
[
EqInlineKeyboardButton(
x.__mod_name__,
callback_data="{}_module({})".format(
prefix, x.__mod_name__.lower()
callback_data="{}_module({},{})".format(
prefix, chat, x.__mod_name__.lower()
),
)
for x in module_dict.values()
]
)
else:
modules = sorted(
) if chat else sorted(
[
EqInlineKeyboardButton(
x.__mod_name__,
callback_data="{}_module({},{})".format(
prefix, chat, x.__mod_name__.lower()
callback_data="{}_module({})".format(
prefix, x.__mod_name__.lower()
),
)
for x in module_dict.values()
]
)

pairs = []
pair = []

Expand Down
26 changes: 13 additions & 13 deletions Bot/modules/owner_stuff.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,26 @@
def stats(update, context):
uptime = datetime.datetime.fromtimestamp(boot_time()).strftime("%Y-%m-%d %H:%M:%S")
status = "*-------< System >-------*\n"
status += "*System uptime:* " + str(uptime) + "\n"
status += f"*System uptime:* {str(uptime)}" + "\n"

uname = platform.uname()
status += "*System:* " + str(uname.system) + "\n"
status += "*Node name:* " + str(uname.node) + "\n"
status += "*Release:* " + str(uname.release) + "\n"
status += "*Version:* " + str(uname.version) + "\n"
status += "*Machine:* " + str(uname.machine) + "\n"
status += "*Processor:* " + str(uname.processor) + "\n\n"
status += f"*System:* {str(uname.system)}" + "\n"
status += f"*Node name:* {str(uname.node)}" + "\n"
status += f"*Release:* {str(uname.release)}" + "\n"
status += f"*Version:* {str(uname.version)}" + "\n"
status += f"*Machine:* {str(uname.machine)}" + "\n"
status += f"*Processor:* {str(uname.processor)}" + "\n\n"

mem = virtual_memory()
cpu = cpu_percent()
disk = disk_usage("/")
status += "*CPU usage:* " + str(cpu) + " %\n"
status += "*Ram usage:* " + str(mem[2]) + " %\n"
status += "*Storage used:* " + str(disk[3]) + " %\n\n"
status += "*Python version:* " + python_version() + "\n"
status += "*Library version:* " + str(__version__) + "\n"
status += f"*CPU usage:* {str(cpu)}" + " %\n"
status += f"*Ram usage:* {str(mem[2])}" + " %\n"
status += f"*Storage used:* {str(disk[3])}" + " %\n\n"
status += f"*Python version:* {python_version()}" + "\n"
status += f"*Library version:* {str(__version__)}" + "\n"
update.effective_message.reply_text(

"*Chizuru, the lewd one near you*\n" +
"built by [Dank-del](t.me/dank_as_fuck)\n" +
"Built with ❤️ using python-telegram-bot\n\n" + status +
Expand Down
9 changes: 3 additions & 6 deletions Bot/modules/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ def get_readable_time(seconds: int) -> str:

while count < 4:
count += 1
if count < 3:
remainder, result = divmod(seconds, 60)
else:
remainder, result = divmod(seconds, 24)
remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
Expand All @@ -60,7 +57,7 @@ def get_readable_time(seconds: int) -> str:
for x in range(len(time_list)):
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
ping_time += time_list.pop() + ", "
ping_time += f'{time_list.pop()}, '

time_list.reverse()
ping_time += ":".join(time_list)
Expand All @@ -74,7 +71,7 @@ def ping(update: Update, context: CallbackContext):
start_time = time.time()
message = msg.reply_text("Pinging...")
end_time = time.time()
telegram_ping = str(round((end_time - start_time) * 1000, 3)) + " ms"
telegram_ping = f'{str(round((end_time - start_time) * 1000, 3))} ms'
uptime = get_readable_time((time.time() - StartTime))

message.edit_text(
Expand Down
9 changes: 3 additions & 6 deletions Bot/modules/sql/users_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def num_users():

def migrate_chat(old_chat_id, new_chat_id):
with INSERTION_LOCK:
chat = SESSION.query(Chats).get(str(old_chat_id))
if chat:
if chat := SESSION.query(Chats).get(str(old_chat_id)):
chat.chat_id = str(new_chat_id)
SESSION.add(chat)

Expand All @@ -199,8 +198,7 @@ def migrate_chat(old_chat_id, new_chat_id):

def del_user(user_id):
with INSERTION_LOCK:
curr = SESSION.query(Users).get(user_id)
if curr:
if curr := SESSION.query(Users).get(user_id):
SESSION.delete(curr)
SESSION.commit()
return True
Expand All @@ -213,8 +211,7 @@ def del_user(user_id):

def rem_chat(chat_id):
with INSERTION_LOCK:
chat = SESSION.query(Chats).get(str(chat_id))
if chat:
if chat := SESSION.query(Chats).get(str(chat_id)):
SESSION.delete(chat)
SESSION.commit()
else:
Expand Down
4 changes: 1 addition & 3 deletions Bot/modules/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ def get_user_id(username):
return userdat.id

except BadRequest as excp:
if excp.message == "Chat not found":
pass
else:
if excp.message != "Chat not found":
LOGGER.exception("Error extracting user ID")

return None
Expand Down

0 comments on commit 6c20eb9

Please sign in to comment.