Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add files via upload (Sourcery refactored) #26

Closed
wants to merge 1 commit into from

Conversation

sourcery-ai[bot]
Copy link

@sourcery-ai sourcery-ai bot commented Nov 2, 2022

Pull Request #25 refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

NOTE: As code is pushed to the original Pull Request, Sourcery will
re-run and update (force-push) this Pull Request with new refactorings as
necessary. If Sourcery finds no refactorings at any point, this Pull Request
will be closed automatically.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the lostb053-patch-1 branch, then run:

git fetch origin sourcery/lostb053-patch-1
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from lostb053 November 2, 2022 15:28
Comment on lines -109 to +124
if ufc is not None:
auser = ufc
else:
auser = user
auser = ufc if ufc is not None else user
find_gc = await DC.find_one({'_id': gid})
if find_gc is not None and 'anime' in find_gc['cmd_list'].split():
return
if len(text) == 1:
k = await message.reply_text(
"""Please give a query to search about
if len(text) == 1:
k = await message.reply_text(
"""Please give a query to search about
example: /anime Ao Haru Ride"""
)
await asyncio.sleep(5)
return await k.delete()
)
await asyncio.sleep(5)
return await k.delete()
query = text[1]
auth = False
vars_ = {"search": query}
if query.isdigit():
vars_ = {"id": int(query)}
if (await AUTH_USERS.find_one({"id": auser})):
auth = True
auth = bool((await AUTH_USERS.find_one({"id": auser})))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function anime_cmd refactored with the following changes:

Comment on lines -179 to +188
if ufc is not None:
auser = ufc
else:
auser = user
auser = ufc if ufc is not None else user
find_gc = await DC.find_one({'_id': gid})
if find_gc is not None and 'manga' in find_gc['cmd_list'].split():
return
if len(text) == 1:
k = await message.reply_text(
"""Please give a query to search about
if len(text) == 1:
k = await message.reply_text(
"""Please give a query to search about
example: /manga The teasing master Takagi san"""
)
await asyncio.sleep(5)
return await k.delete()
)
await asyncio.sleep(5)
return await k.delete()
query = text[1]
qdb = rand_key()
MANGA_DB[qdb] = query
auth = False
if (await AUTH_USERS.find_one({"id": auser})):
auth = True
auth = bool((await AUTH_USERS.find_one({"id": auser})))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function manga_cmd refactored with the following changes:

Comment on lines -259 to +249
if ufc is not None:
auser = ufc
else:
auser = user
auser = ufc if ufc is not None else user
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function character_cmd refactored with the following changes:

Comment on lines -317 to +302
if ufc is not None:
auser = ufc
else:
auser = user
auser = ufc if ufc is not None else user
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function anilist_cmd refactored with the following changes:

Comment on lines -395 to +381
if not len(query) == 2:
k = await message.reply_text(
"""Please give an anilist username to search about
if len(query) != 2:
k = await message.reply_text(
"""Please give an anilist username to search about
example: /user Lostb053"""
)
await asyncio.sleep(5)
return await k.delete()
)
await asyncio.sleep(5)
return await k.delete()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function flex_cmd refactored with the following changes:

  • Simplify logical expression using De Morgan identities [×2] (de-morgan)
  • Replace if statement with if expression (assign-if-exp)

Comment on lines -1274 to +1219
if "-100" in str(user):
auser = await gcc(user)
else:
auser = user
auser = await gcc(user) if "-100" in str(user) else user
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function flex_btn refactored with the following changes:

Comment on lines -1351 to +1293
if "-100" in str(q[5]):
auser = await gcc(q[5])
else:
auser = q[5]
auser = await gcc(q[5]) if "-100" in str(q[5]) else q[5]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function favourites_btn refactored with the following changes:

Comment on lines -1374 to +1313
if "-100" in str(query):
auser = await gcc(query)
else:
auser = query
auser = await gcc(query) if "-100" in str(query) else query
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_user_back_btn refactored with the following changes:

Comment on lines -1429 to +1365
if "-100" in str(user):
auser = await gcc(user)
else:
auser = user
auser = await gcc(user) if "-100" in str(user) else user
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function toggle_favourites_btn refactored with the following changes:

Comment on lines -1771 to +1705
result = result[:940] + "..."
if spoiler is False:
result = f"{result[:940]}..."
if not spoiler:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function additional_info_btn refactored with the following changes:

Comment on lines -1844 to +1779
if result[0] is False:
await cq.answer("No Data Available!!!", show_alert=True)
return
if result[0] is False:
await cq.answer("No Data Available!!!", show_alert=True)
return
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function featured_in_btn refactored with the following changes:

Comment on lines -1923 to +1872
button.append([InlineKeyboardButton(
text=f"{bt}",
callback_data=f"{reqb}_{idm}_0_{qry}_{pg}_{auth}_{user}"
)])
button.append([InlineKeyboardButton(
text="Back",
callback_data=f"page_CHARACTER_{qry}_{pg}_{auth}_{user}"
)])
button.extend(
(
[
InlineKeyboardButton(
text=f"{bt}",
callback_data=f"{reqb}_{idm}_0_{qry}_{pg}_{auth}_{user}",
)
],
[
InlineKeyboardButton(
text="Back",
callback_data=f"page_CHARACTER_{qry}_{pg}_{auth}_{user}",
)
],
)
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function featured_in_switch_btn refactored with the following changes:

Comment on lines -2006 to +1951
pin_msg = f"Auto Pin: OFF"
else:
await collection.insert_one({"_id": gid})
src_status = f"{srcname}: ON"
pin_msg = f"Auto Pin: OFF"
pin_msg = "Auto Pin: OFF"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function headlines_btn refactored with the following changes:

Comment on lines -2109 to +2054
unpin = int(qry)
setting = {"unpin": 0}
else:
now = round(time.time(), -2)
unpin = int(qry)
setting = {"unpin": int(qry), "next_unpin": int(qry)+int(now)}
unpin = int(qry)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function auto_unpin refactored with the following changes:

enable = False if not 'enable' in cmd[0] else True
enable = 'enable' in cmd[0]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function en_dis__able_cmd refactored with the following changes:

Comment on lines +849 to +865
elif int(page)==1:
btns.append([
InlineKeyboardButton(
"Next", callback_data=f"stuani_2_{id_}_{rp}_{qry}_{auth}_{duser}"
)
])
else:
if int(page)==1:
btns.append([
InlineKeyboardButton(
"Next", callback_data=f"stuani_2_{id_}_{rp}_{qry}_{auth}_{duser}"
)
])
else:
btns.append([
InlineKeyboardButton(
"Prev",
callback_data=f"stuani_{int(page)-1}_{id_}_{rp}_{qry}_{auth}_{duser}"
),
InlineKeyboardButton(
"Next",
callback_data=f"stuani_{int(page)+1}_{id_}_{rp}_{qry}_{auth}_{duser}"
)
])
btns.append([
InlineKeyboardButton(
"Prev",
callback_data=f"stuani_{int(page)-1}_{id_}_{rp}_{qry}_{auth}_{duser}"
),
InlineKeyboardButton(
"Next",
callback_data=f"stuani_{int(page)+1}_{id_}_{rp}_{qry}_{auth}_{duser}"
)
])
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_studio_animes refactored with the following changes:

Comment on lines -877 to +887
msg = "**Tags List:**\n\n`"
kek = []
for i in result['data']['MediaTagCollection']:
if text is not None and 'nsfw' in text:
if str(i['isAdult'])!='False':
kek.append(i['name'])
else:
if str(i['isAdult'])=='False':
kek.append(i['name'])
msg += ", ".join(kek)
kek = [
i['name']
for i in result['data']['MediaTagCollection']
if text is not None
and 'nsfw' in text
and str(i['isAdult']) != 'False'
or (text is None or 'nsfw' not in text)
and str(i['isAdult']) == 'False'
]

msg = "**Tags List:**\n\n`" + ", ".join(kek)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_all_tags refactored with the following changes:

Comment on lines -948 to +949
if rc_ls == []:
if not rc_ls:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_recommendations refactored with the following changes:

Comment on lines -975 to +978
return [f"No results Found"]
return ["No results Found"]
nsls = await get_all_tags('nsfw')
nsfw = True if gnr.lower() in nsls.lower() else False
nsfw = gnr.lower() in nsls.lower()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_top_animes refactored with the following changes:

Comment on lines +1105 to -1106
out_ = []
if req == "ANI":
out = "ANIMES:\n\n"
out_ = []
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_featured_in_lists refactored with the following changes:

Comment on lines -1167 to +1184
charlist = []
for char in data["characters"]['edges']:
charlist.append(
f"• `{char['node']['name']['full']}` ({char['role']})"
)
charlist = [
f"• `{char['node']['name']['full']}` ({char['role']})"
for char in data["characters"]['edges']
]

chrctrs = ("\n").join(charlist)
charls = f"{chrctrs}" if len(charlist) != 0 else ""
charls = f"{chrctrs}" if charlist else ""
return pic, charls, data["characters"]['pageInfo']
else:
prqlsql = data.get("relations").get("edges")
ps = ""
for i in prqlsql:
ps += (
ps = "".join(
(
f'• {i["node"]["title"]["romaji"]} '
+f'({i["node"]["type"]}) `{i["relationType"]}`\n'
+ f'({i["node"]["type"]}) `{i["relationType"]}`\n'
)
for i in prqlsql
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_additional_info refactored with the following changes:

Comment on lines -193 to +197
URLS_SUFFIX = [re.search('translate.google.(.*)', url.strip()).group(1) for url in DEFAULT_SERVICE_URLS]
URLS_SUFFIX = [
re.search('translate.google.(.*)', url.strip())[1]
for url in DEFAULT_SERVICE_URLS
]

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 193-193 refactored with the following changes:

Comment on lines -217 to +224
return "{}. Probable cause: {}".format(premise, "timeout")
# if tts.tld != 'com':
# host = _translate_url(tld=tts.tld)
# cause = "Host '{}' is not reachable".format(host)
return f"{premise}. Probable cause: timeout"
# if tts.tld != 'com':
# host = _translate_url(tld=tts.tld)
# cause = "Host '{}' is not reachable".format(host)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function google_new_transError.infer_msg refactored with the following changes:

Comment on lines -267 to +272
url_base = "https://translate.google.{}".format(self.url_suffix)
self.url = url_base + "/_/TranslateWebserverUi/data/batchexecute"
url_base = f"https://translate.google.{self.url_suffix}"
self.url = f"{url_base}/_/TranslateWebserverUi/data/batchexecute"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function google_translator.__init__ refactored with the following changes:

Comment on lines -277 to +281
# text_urldecode = quote(text.strip())
freq_initial = "f.req={}&".format(quote(espaced_rpc))
freq = freq_initial
return freq
return f"f.req={quote(espaced_rpc)}&"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function google_translator._package_rpc refactored with the following changes:

This removes the following comments ( why? ):

# text_urldecode = quote(text.strip())

Comment on lines -370 to -376
th = (
"st" if x == "1"
else "nd" if x == "2"
else "rd" if x == "3"
else "th"
return (
"st" if x == "1" else "nd" if x == "2" else "rd" if x == "3" else "th"
)
return th
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function pos_no refactored with the following changes:

Comment on lines -386 to +383
((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 "")
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_it_rw refactored with the following changes:

Comment on lines -450 to +486
buttons.append([
InlineKeyboardButton(
text="Characters",
callback_data=(
f"char_{result[2][0]}_ANI"
+f"{qry}{pg}_{str(auth)}_1_{user}"
)
),
InlineKeyboardButton(
text="Description",
callback_data=(
f"desc_{result[2][0]}_ANI"
+f"{qry}{pg}_{str(auth)}_{user}"
)
),
InlineKeyboardButton(
text="List Series",
callback_data=(
f"ls_{result[2][0]}_ANI"
+f"{qry}{pg}_{str(auth)}_{user}"
)
),
])
buttons.append(
[
InlineKeyboardButton(
text="Characters",
callback_data=(
f"char_{result[2][0]}_ANI"
+ f"{qry}{pg}_{auth}_1_{user}"
),
),
InlineKeyboardButton(
text="Description",
callback_data=(
f"desc_{result[2][0]}_ANI" + f"{qry}{pg}_{auth}_{user}"
),
),
InlineKeyboardButton(
text="List Series",
callback_data=(
f"ls_{result[2][0]}_ANI" + f"{qry}{pg}_{auth}_{user}"
),
),
]
)

if media == "CHARACTER":
buttons.append([
InlineKeyboardButton(
"Description",
callback_data=(
f"desc_{result[2][0]}_CHAR"
+f"{qry}{pg}_{str(auth)}_{user}"
)
)
])
buttons.append([
InlineKeyboardButton(
"List Series",
callback_data=f"lsc_{result[2][0]}{qry}{pg}_{str(auth)}_{user}"
buttons.extend(
(
[
InlineKeyboardButton(
"Description",
callback_data=f"desc_{result[2][0]}_CHAR"
+ f"{qry}{pg}_{auth}_{user}",
)
],
[
InlineKeyboardButton(
"List Series",
callback_data=f"lsc_{result[2][0]}{qry}{pg}_{auth}_{user}",
)
],
)
])
)

if media == "SCHEDULED":
if result[0]!=0 and result[0]!=6:
if result[0] not in [0, 6]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_btns refactored with the following changes:

Comment on lines -612 to +636
btn.append(
InlineKeyboardButton(
text=(
"Add to Favs" if data[3] is not True
else "Remove from Favs"
btn.extend(
(
InlineKeyboardButton(
text=(
"Add to Favs"
if data[3] is not True
else "Remove from Favs"
),
callback_data=f"fav_{media}_{data[0]}{qry}{pg}_{user}",
),
InlineKeyboardButton(
text="Add to List"
if data[1] is False
else "Update in List",
callback_data=(
f"lsadd_{media}_{data[0]}{qry}{pg}_{user}"
if data[1] is False
else f"lsupdt_{media}_{data[0]}_{data[2]}{qry}{pg}_{user}"
),
),
callback_data=f"fav_{media}_{data[0]}{qry}{pg}_{user}"
)
)
btn.append(InlineKeyboardButton(
text="Add to List" if data[1] is False else "Update in List",
callback_data=(
f"lsadd_{media}_{data[0]}{qry}{pg}_{user}" if data[1] is False
else f"lsupdt_{media}_{data[0]}_{data[2]}{qry}{pg}_{user}"
)
))

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_auth_btns refactored with the following changes:

Comment on lines -674 to +713
if (await PIC_DB.find_one({'_id': link})) is None:
await PIC_DB.insert_one({'_id': link})
if await PIC_DB.find_one({'_id': link}) is not None:
continue
await PIC_DB.insert_one({'_id': link})
try:
me = await user.send_photo("me", f"{link}?a={ts}")
msg = await user.send_photo("me", link)
except ConnectionError:
await asyncio.sleep(5)
me = await user.send_photo("me", f"{link}?a={ts}")
msg = await user.send_photo("me", link)
await asyncio.sleep(7)
dls1 = await user.download_media(
msg.photo,
file_name=DOWN_PATH + link.split("/").pop()+'(1).png',
)
dls2 = await user.download_media(
me.photo,
file_name=DOWN_PATH + link.split("/").pop()+'(2).png',
)
await asyncio.sleep(10)
with open(dls1, 'rb') as p1:
b1 = p1.read()
with open(dls2, 'rb') as p2:
b2 = p2.read()
await user.delete_messages("me", [me.id, msg.id])
if b1!=b2:
try:
me = await user.send_photo("me", link+f"?a={ts}")
msg = await user.send_photo("me", link)
await user.send_message("webpagebot", link)
except ConnectionError:
await asyncio.sleep(5)
me = await user.send_photo("me", link+f"?a={ts}")
msg = await user.send_photo("me", link)
await asyncio.sleep(7)
dls1 = await user.download_media(
msg.photo,
file_name=DOWN_PATH + link.split("/").pop()+'(1).png',
)
dls2 = await user.download_media(
me.photo,
file_name=DOWN_PATH + link.split("/").pop()+'(2).png',
)
await asyncio.sleep(10)
with open(dls1, 'rb') as p1:
b1 = p1.read()
with open(dls2, 'rb') as p2:
b2 = p2.read()
await user.delete_messages("me", [me.id, msg.id])
if b1!=b2:
try:
await user.send_message("webpagebot", link)
except ConnectionError:
await asyncio.sleep(5)
await user.send_message("webpagebot", link)
else:
continue
await user.send_message("webpagebot", link)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function update_pics_cache refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Nov 2, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.35%.

Quality metrics Before After Change
Complexity 21.03 😞 20.13 😞 -0.90 👍
Method Length 181.51 😞 179.84 😞 -1.67 👍
Working memory 14.94 😞 15.04 😞 0.10 👎
Quality 35.36% 😞 35.71% 😞 0.35% 👍
Other metrics Before After Change
Lines 6061 6006 -55
Changed files Quality Before Quality After Quality Change
anibot/plugins/anilist.py 35.40% 😞 35.53% 😞 0.13% 👍
anibot/plugins/bot.py 32.58% 😞 33.36% 😞 0.78% 👍
anibot/plugins/tracemoepy.py 21.30% ⛔ 21.31% ⛔ 0.01% 👍
anibot/plugins/watch.py 55.80% 🙂 54.73% 🙂 -1.07% 👎
anibot/utils/data_parser.py 34.31% 😞 34.40% 😞 0.09% 👍
anibot/utils/google_trans_new.py 39.47% 😞 39.81% 😞 0.34% 👍
anibot/utils/helper.py 39.31% 😞 40.92% 😞 1.61% 👍

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
anibot/utils/helper.py check_user 73 ⛔ 342 ⛔ 4.73% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
anibot/plugins/bot.py en_dis__able_cmd 55 ⛔ 430 ⛔ 22 ⛔ 6.40% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
anibot/plugins/anilist.py update_anilist_btn 92 ⛔ 633 ⛔ 17 ⛔ 6.81% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
anibot/utils/data_parser.py get_anilist 37 ⛔ 767 ⛔ 33 ⛔ 7.11% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
anibot/utils/data_parser.py get_anime 37 ⛔ 762 ⛔ 32 ⛔ 7.21% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Base automatically changed from lostb053-patch-1 to main November 2, 2022 15:42
@sourcery-ai sourcery-ai bot closed this Nov 2, 2022
@sourcery-ai sourcery-ai bot deleted the sourcery/lostb053-patch-1 branch November 2, 2022 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

0 participants