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

Sourcery refactored master branch #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

sourcery-ai[bot]
Copy link

@sourcery-ai sourcery-ai bot commented Jan 12, 2022

Branch master refactored by Sourcery.

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

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 master branch, then run:

git fetch origin sourcery/master
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from reapski January 12, 2022 02:31
data = brotli.decompress(payload)
return data
return brotli.decompress(payload)
Copy link
Author

Choose a reason for hiding this comment

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

Function Wrapper.brdecompress refactored with the following changes:

Comment on lines -42 to +50
if headerModifications not in ({}, None):
editedSession = copy.deepcopy(reqsession)
if "update" in headerModifications:
editedSession.headers.update(headerModifications["update"])
if "remove" in headerModifications:
for header in headerModifications["remove"]:
if header in editedSession.headers:
del editedSession.headers[header]
return editedSession
else:
if headerModifications in ({}, None):
return reqsession
editedSession = copy.deepcopy(reqsession)
if "update" in headerModifications:
editedSession.headers.update(headerModifications["update"])
if "remove" in headerModifications:
for header in headerModifications["remove"]:
if header in editedSession.headers:
del editedSession.headers[header]
return editedSession
Copy link
Author

Choose a reason for hiding this comment

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

Function Wrapper.editedReqSession refactored with the following changes:

Comment on lines -86 to +84
if isinstance(body, dict):
data = {'data': json.dumps(body)}
else:
data = {'data': body}
data = {'data': json.dumps(body)} if isinstance(body, dict) else {'data': body}
Copy link
Author

Choose a reason for hiding this comment

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

Function Wrapper.sendRequest refactored with the following changes:

Comment on lines -607 to +612
if self.Science == "":
self.Science = Science(self.discord, self.s, self.log, None, "0", "") #no sequential data needed for parsing
result = self.Science.UUIDobj.parse(client_uuid)
self.Science = "" #reset
return result
else:
if self.Science != "":
return self.Science.UUIDobj.parse(client_uuid)
self.Science = Science(self.discord, self.s, self.log, None, "0", "") #no sequential data needed for parsing
result = self.Science.UUIDobj.parse(client_uuid)
self.Science = "" #reset
return result
Copy link
Author

Choose a reason for hiding this comment

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

Function Client.parseClientUUID refactored with the following changes:

if color:
string = color + text + '\033[m'
else:
string = text
string = color + text + '\033[m' if color else text
Copy link
Author

Choose a reason for hiding this comment

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

Function Logger.log refactored with the following changes:

@@ -219,7 +219,6 @@ def removeCommand(self, func, exactMatch=True, allMatches=False):
del self._after_message_hooks[commandsCopy.index(func)]
except ValueError:
Logger.log('{} not found in _after_message_hooks.'.format(func), None, self.log)
pass
Copy link
Author

Choose a reason for hiding this comment

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

Function RemoteAuth.removeCommand refactored with the following changes:

Comment on lines -65 to +68
f = {}
for i in self.relationships: #where i is a user id
if self.relationships[i]['type'] == 'friend':
f[i] = self.relationships[i]
return f
return {
i: self.relationships[i]
for i in self.relationships if self.relationships[i]['type'] == 'friend'
}
Copy link
Author

Choose a reason for hiding this comment

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

Function Session.friends refactored with the following changes:

This removes the following comments ( why? ):

#where i is a user id

Comment on lines -78 to +80
b = {}
for i in self.relationships: #where i is a user id
if self.relationships[i]['type'] == 'blocked':
b[i] = self.relationships[i]
return b
return {
i: self.relationships[i]
for i in self.relationships if self.relationships[i]['type'] == 'blocked'
}
Copy link
Author

Choose a reason for hiding this comment

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

Function Session.blocked refactored with the following changes:

This removes the following comments ( why? ):

#where i is a user id

Comment on lines -91 to +93
ifr = {}
for i in self.relationships:
if self.relationships[i]['type'] == 'pending_incoming':
ifr[i] = self.relationships[i]
return ifr
return {
i: self.relationships[i]
for i in self.relationships
if self.relationships[i]['type'] == 'pending_incoming'
}
Copy link
Author

Choose a reason for hiding this comment

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

Function Session.incomingFriendRequests refactored with the following changes:

Comment on lines -104 to +106
ofr = {}
for i in self.relationships:
if self.relationships[i]['type'] == 'pending_outgoing':
ofr[i] = self.relationships[i]
return ofr
return {
i: self.relationships[i]
for i in self.relationships
if self.relationships[i]['type'] == 'pending_outgoing'
}
Copy link
Author

Choose a reason for hiding this comment

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

Function Session.outgoingFriendRequests refactored with the following changes:

Comment on lines -391 to +393
all_categories = {}
for i in self.channelsAndCategories: #https://discord.com/developers/docs/resources/channel#channel-object-channel-types
if self.channelsAndCategories[i]['type'] == 4:
all_categories[i] = self.channelsAndCategories[i]
return all_categories
return {
i: self.channelsAndCategories[i]
for i in self.channelsAndCategories
if self.channelsAndCategories[i]['type'] == 4
}
Copy link
Author

Choose a reason for hiding this comment

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

Function guild.categories refactored with the following changes:

This removes the following comments ( why? ):

#https://discord.com/developers/docs/resources/channel#channel-object-channel-types

Comment on lines -406 to +408
all_channels = {}
for i in self.channelsAndCategories: #https://discord.com/developers/docs/resources/channel#channel-object-channel-types
if self.channelsAndCategories[i]['type'] != 4:
all_channels[i] = self.channelsAndCategories[i]
return all_channels
return {
i: self.channelsAndCategories[i]
for i in self.channelsAndCategories
if self.channelsAndCategories[i]['type'] != 4
}
Copy link
Author

Choose a reason for hiding this comment

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

Function guild.channels refactored with the following changes:

This removes the following comments ( why? ):

#https://discord.com/developers/docs/resources/channel#channel-object-channel-types

Comment on lines -9 to +11
if channelData["type"] in ("dm", "group_dm"): #private_channel
if "recipient_ids" not in channelData and "recipients" in channelData: #should be true, running this check just in case
channelData["recipient_ids"] = [i["id"] for i in channelData["recipients"]]
if (channelData["type"] in ("dm", "group_dm")
and "recipient_ids" not in channelData and "recipients" in channelData): #should be true, running this check just in case
channelData["recipient_ids"] = [i["id"] for i in channelData["recipients"]]
Copy link
Author

Choose a reason for hiding this comment

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

Function ChannelParse.channel_create refactored with the following changes:

This removes the following comments ( why? ):

#private_channel

Comment on lines -18 to +20
if channelData["type"] in ("dm", "group_dm"): #private_channel
if "recipient_ids" not in channelData and "recipients" in channelData:
channelData["recipient_ids"] = [i["id"] for i in channelData["recipients"]]
if (channelData["type"] in ("dm", "group_dm")
and "recipient_ids" not in channelData and "recipients" in channelData):
channelData["recipient_ids"] = [i["id"] for i in channelData["recipients"]]
Copy link
Author

Choose a reason for hiding this comment

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

Function ChannelParse.channel_delete refactored with the following changes:

This removes the following comments ( why? ):

#private_channel

Comment on lines -18 to +22
if keep == None:
if keep is None:
remove = allProperties
elif keep == "all":
remove = []
elif isinstance(keep, list) or isinstance(keep, tuple):
elif isinstance(keep, (list, tuple)):
Copy link
Author

Choose a reason for hiding this comment

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

Function GuildCombo.reformat_member refactored with the following changes:

Comment on lines -43 to +48
if self.analytics_token == None: #if not logged in. ex: bot=discum.Client(token='poop')
headerModifications = {"update":{"X-fingerprint": self.xfingerprint}, "remove": ["Authorization"]}
return Wrapper.sendRequest(self.s, 'post', url, body, headerModifications=headerModifications, log=self.log)
else:
if self.analytics_token is not None:
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
headerModifications = {"update":{"X-fingerprint": self.xfingerprint}, "remove": ["Authorization"]}
return Wrapper.sendRequest(self.s, 'post', url, body, headerModifications=headerModifications, log=self.log)
Copy link
Author

Choose a reason for hiding this comment

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

Function Science.science refactored with the following changes:

This removes the following comments ( why? ):

#if not logged in. ex: bot=discum.Client(token='poop')

Comment on lines -39 to +54
if result.get('mfa') == True and result.get('sms') == False: #sms login not implemented yet
time.sleep(2) #2 seconds is minimal, don't want to look too automated
ticket = result['ticket']
if secret != "":
code = TOTP(secret).generateTOTP()
code = str(code) #just in case an int is inputted
totpUrl = self.discord+"auth/mfa/totp"
totpBody = {
"code": code,
"ticket": ticket,
"login_source": source,
"gift_code_sku_id": gift_code_sku_id
}
totpResponse = Wrapper.sendRequest(self.editedS, 'post', totpUrl, totpBody, log=self.log)
return totpResponse, self.xfingerprint
else:
if result.get('mfa') != True or result.get('sms') != False:
return response, self.xfingerprint
time.sleep(2) #2 seconds is minimal, don't want to look too automated
ticket = result['ticket']
if secret != "":
code = TOTP(secret).generateTOTP()
code = str(code) #just in case an int is inputted
totpUrl = self.discord+"auth/mfa/totp"
totpBody = {
"code": code,
"ticket": ticket,
"login_source": source,
"gift_code_sku_id": gift_code_sku_id
}
totpResponse = Wrapper.sendRequest(self.editedS, 'post', totpUrl, totpBody, log=self.log)
return totpResponse, self.xfingerprint
Copy link
Author

Choose a reason for hiding this comment

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

Function Login.login refactored with the following changes:

This removes the following comments ( why? ):

#sms login not implemented yet

Comment on lines -54 to +55
if locale == None:
sp.pop("system_locale")
if locale is None:
sp.pop("system_locale")
Copy link
Author

Choose a reason for hiding this comment

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

Function SuperProperties.getSuperProperties refactored with the following changes:

if userID == "default":
userID = self.userID
else:
userID = int(userID)

userID = self.userID if userID == "default" else int(userID)
Copy link
Author

Choose a reason for hiding this comment

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

Function Client_UUID.calculate refactored with the following changes:

Comment on lines -46 to +56
unpacked = []
for i in range(6):
unpacked.append(struct.unpack('<i', decoded_client_uuid[4*i:4*i+4])[0])
UUIDdata = {}
unpacked = [
struct.unpack('<i', decoded_client_uuid[4 * i : 4 * i + 4])[0]
for i in range(6)
]

userIDguess = (unpacked[1]<<32) + unpacked[0]
UUIDdata['userID'] = repr(userIDguess if userIDguess%4294967296<=2147483647 else userIDguess+4294967296)
UUIDdata['randomPrefix'] = unpacked[2]
UUIDdata = {
'userID': repr(
userIDguess
if userIDguess % 4294967296 <= 2147483647
else userIDguess + 4294967296
),
'randomPrefix': unpacked[2],
}

Copy link
Author

Choose a reason for hiding this comment

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

Function Client_UUID.parse refactored with the following changes:

if isinstance(c, tuple) or isinstance(c, list):
if isinstance(c, (tuple, list)):
Copy link
Author

Choose a reason for hiding this comment

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

Function Color.get refactored with the following changes:

encodedData = base64.b64encode(binaryData).decode("utf-8")
return encodedData
return base64.b64encode(binaryData).decode("utf-8")
Copy link
Author

Choose a reason for hiding this comment

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

Function ContextProperties.encodeData refactored with the following changes:

Comment on lines -25 to +40
if m['type'] == 'reply':
if 'referenced_message' in m and m['referenced_message']['author']['id'] == bot.gateway.session.user['id'] and 'guild_id' not in m:
time.sleep(1) #instant replies make ppl think ur running a selfbot so...
channelID = m['channel_id']
baseURL = "https://discord.com/api/channels/{}/messages".format(channelID)
POSTedJSON = json.dumps ({"content":"The server Gods have allowed me to grant you the server badge. You are now a server :).","nonce":None,"tts":False,"message_reference":{"guild_id":None,"channel_id":m['channel_id'],"message_id":m['id']},"allowed_mentions":{"parse":["users","roles","everyone"],"replied_user":False}})
try:
bot.s.post(baseURL, data=POSTedJSON)
except:
bot.s.post(baseURL, data=POSTedJSON)
time.sleep(2) #instant replies make ppl think ur running a selfbot so...
if (
m['type'] == 'reply'
and 'referenced_message' in m
and m['referenced_message']['author']['id']
== bot.gateway.session.user['id']
and 'guild_id' not in m
):
time.sleep(1) #instant replies make ppl think ur running a selfbot so...
channelID = m['channel_id']
baseURL = "https://discord.com/api/channels/{}/messages".format(channelID)
POSTedJSON = json.dumps ({"content":"The server Gods have allowed me to grant you the server badge. You are now a server :).","nonce":None,"tts":False,"message_reference":{"guild_id":None,"channel_id":m['channel_id'],"message_id":m['id']},"allowed_mentions":{"parse":["users","roles","everyone"],"replied_user":False}})
try:
bot.s.post(baseURL, data=POSTedJSON)
except:
bot.s.post(baseURL, data=POSTedJSON)
time.sleep(2) #instant replies make ppl think ur running a selfbot so...
Copy link
Author

Choose a reason for hiding this comment

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

Function helloworld refactored with the following changes:

Comment on lines -69 to +87
lastName = sorted(set([re.sub(' +', ' ', j['nick'].lower()) if (j.get('nick') and re.sub(' +', ' ', j.get('nick').lower()).startswith(''.join(bot.qList))) else re.sub(' +', ' ', j['username'].lower()) for j in data]))[-1]
lastName = sorted({
re.sub(' +', ' ', j['nick'].lower()) if
(j.get('nick')
and re.sub(' +', ' ',
j.get('nick').lower()).startswith(''.join(bot.qList))) else
re.sub(' +', ' ', j['username'].lower())
for j in data
})[-1]
try:
option = lastName[len(bot.qList)]
return option
return lastName[len(bot.qList)]
except IndexError:
return None
elif action == 'replace':
if bot.qList[-1] in allchars:
options = allchars[allchars.index(bot.qList[-1])+1:]
if ' ' in options and (len(bot.qList)==1 or (len(bot.qList)>1 and bot.qList[-2]==' ')): #cannot start with a space and cannot have duplicate spaces
options.remove(' ')
return options
else:
if bot.qList[-1] not in allchars:
return None
options = allchars[allchars.index(bot.qList[-1])+1:]
if ' ' in options and (len(bot.qList)==1 or (len(bot.qList)>1 and bot.qList[-2]==' ')): #cannot start with a space and cannot have duplicate spaces
options.remove(' ')
return options
Copy link
Author

Choose a reason for hiding this comment

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

Function calculateOption refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Jan 12, 2022

Sourcery Code Quality Report

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

Quality metrics Before After Change
Complexity 12.88 🙂 11.34 🙂 -1.54 👍
Method Length 39.04 ⭐ 38.62 ⭐ -0.42 👍
Working memory 9.91 😞 9.76 🙂 -0.15 👍
Quality 65.49% 🙂 66.42% 🙂 0.93% 👍
Other metrics Before After Change
Lines 2665 2654 -11
Changed files Quality Before Quality After Quality Change
discum/RESTapiwrap.py 60.31% 🙂 62.94% 🙂 2.63% 👍
discum/discum.py 81.55% ⭐ 81.62% ⭐ 0.07% 👍
discum/logger.py 82.54% ⭐ 84.36% ⭐ 1.82% 👍
discum/gateway/gateway.py 62.14% 🙂 63.37% 🙂 1.23% 👍
discum/gateway/remoteauth.py 71.08% 🙂 71.09% 🙂 0.01% 👍
discum/gateway/session.py 92.65% ⭐ 93.73% ⭐ 1.08% 👍
discum/gateway/channels/parse.py 78.17% ⭐ 80.31% ⭐ 2.14% 👍
discum/gateway/guild/combo.py 26.67% 😞 30.33% 😞 3.66% 👍
discum/gateway/guild/request.py 65.45% 🙂 65.45% 🙂 0.00%
discum/gateway/user/combo.py 74.90% 🙂 75.29% ⭐ 0.39% 👍
discum/messages/messages.py 46.72% 😞 48.58% 😞 1.86% 👍
discum/science/science.py 72.29% 🙂 72.23% 🙂 -0.06% 👎
discum/start/login.py 62.10% 🙂 64.99% 🙂 2.89% 👍
discum/start/superproperties.py 68.23% 🙂 68.23% 🙂 0.00%
discum/utils/client_uuid.py 67.12% 🙂 68.22% 🙂 1.10% 👍
discum/utils/color.py 69.06% 🙂 71.36% 🙂 2.30% 👍
discum/utils/contextproperties.py 64.59% 🙂 63.05% 🙂 -1.54% 👎
examples/TheGiverOfServers.py 43.81% 😞 47.20% 😞 3.39% 👍
examples/searchGuildMembers.py 53.65% 🙂 54.06% 🙂 0.41% 👍

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

File Function Complexity Length Working Memory Quality Recommendation
discum/gateway/guild/combo.py GuildCombo.fetchMembers 107 ⛔ 586 ⛔ 31 ⛔ 1.06% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
discum/messages/messages.py Messages.searchMessages 57 ⛔ 363 ⛔ 23 ⛔ 6.62% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
discum/gateway/guild/combo.py GuildCombo.handleGuildMemberSearches 29 😞 265 ⛔ 25 ⛔ 16.70% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
examples/searchGuildMembers.py bruteForceTest 26 😞 328 ⛔ 17 ⛔ 20.65% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
discum/gateway/gateway.py GatewayServer.sessionUpdates 26 😞 259 ⛔ 15 😞 25.20% 😞 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!

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.

0 participants