Passed
Push — main ( 98503b...6c3c91 )
by Bartosz
01:17
created

build.cogs.spotcog.SpotCog.count_spot()   D

Complexity

Conditions 12

Size

Total Lines 55
Code Lines 37

Duplication

Lines 55
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 37
dl 55
loc 55
rs 4.8
c 0
b 0
f 0
cc 12
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like build.cogs.spotcog.SpotCog.count_spot() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
Cog with role related commands available in the Bot.
3
4
Current commands:
5
/remove_spot
6
7
"""
8
import json
9
import discord
10
from discord.utils import get
11
from discord.ext import commands
12
from discord_slash import SlashContext, cog_ext
13
from discord_slash.model import SlashCommandPermissionType
14
from discord_slash.utils.manage_commands import create_permission
15
16
from cogs.cogbase import BaseCog
17
from modules.get_settings import get_settings
18
19
guild_ids = get_settings("guild")
20
MODERATION_IDS = get_settings("MOD_ROLES")
21
PERMISSIONS_MODS = {
22
    guild_ids[0]: [
23
        create_permission(MODERATION_IDS[0], SlashCommandPermissionType.ROLE, True),
24
        create_permission(MODERATION_IDS[1], SlashCommandPermissionType.ROLE, True)
25
    ]
26
}
27
28
29 View Code Duplication
class SpotCog(BaseCog):
30
    def __init__(self, base):
31
        super().__init__(base)
32
33
    # Ping monster role
34
    @commands.Cog.listener()
35
    async def on_message(self, ctx):
36
        if ctx.author.id == self.bot.user.id:
37
            return
38
39
        prefix = "/"
40
        cords_beginning = ["-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
41
42
        # If common spotted
43
        if ctx.channel.id == self.bot.CH_COMMON:
44
            if ctx.content[0] in cords_beginning:
45
                await self.count_spot(ctx, 4)
46
            else:
47
                await ctx.delete()
48
49
        elif ctx.channel.category.id == self.bot.CAT_SPOTTING:
50
            if ctx.content.startswith(prefix):
51
                spotted_monster = await self.get_monster(ctx, ctx.content.replace(prefix, ""))
52
                if spotted_monster:
53
                    role = get(ctx.guild.roles, name=spotted_monster["name"])
54
                    await ctx.delete()
55
                    await ctx.channel.send(f"{role.mention}")
56
                    await self.count_spot(ctx, spotted_monster["type"])
57
            elif ctx.content[0] in cords_beginning:  # I think this should be 1st in checking if
58
                return
59
60
            # # If member sends normal message
61
            # else:
62
            #     return
63
            #     await ctx.channel.send(
64
            #         f"{ctx.author.mention} Use {self.bot.get_channel(self.bot.CH_DISCUSSION_EN).mention}",
65
            #         delete_after=5.0)
66
67
    async def count_spot(self, ctx: SlashContext, monster_type: int):
68
        """
69
70
        :param ctx:
71
        :type ctx:
72
        :param monster_type:
73
        :type monster_type:
74
        :return:
75
        :rtype:
76
        """
77
        with open("./json_files/monster_spots.json", encoding="utf-8") as f:
78
            try:
79
                spots = json.load(f)
80
            except ValueError:
81
                spots = {"users": []}
82
                await ctx.channel.send("monster_spots.json created", delete_after=1)
83
84
        if monster_type == 4:
85
            for current_user in spots["users"]:
86
                if current_user["id"] == ctx.author.id:
87
                    current_user["common_spots"] += 1
88
                    break
89
            spots["users"].append({
90
                "id": ctx.author.id,
91
                "name": ctx.author.name,
92
                "lege_spots": 0,
93
                "rare_spots": 0,
94
                "total": 0,
95
                "common_spots": 1
96
            })
97
98
        else:
99
            for current_user in spots["users"]:
100
                if current_user["id"] == ctx.author.id:
101
                    if monster_type == 0:
102
                        current_user["rare_spots"] += 1
103
                    elif monster_type == 1:
104
                        current_user["lege_spots"] += 1
105
                    else:
106
                        print("Wrong monster type(?)")
107
108
                    current_user["total"] = current_user["lege_spots"] * 5 + current_user["rare_spots"]
109
                    break
110
            else:
111
                spots["users"].append({
112
                    "id": ctx.author.id,
113
                    "name": ctx.author.display_name,
114
                    "lege_spots": 0,
115
                    "rare_spots": 0,
116
                    "total": 0,
117
                    "common_spots": 0
118
                })
119
120
        with open("./json_files/monster_spots.json", "w+") as f:
121
            json.dump(spots, f, indent=4)
122
123
    @cog_ext.cog_slash(name="setMemberSpotsCounter", guild_ids=guild_ids,
124
                       description="Function for managing user's warns",
125
                       default_permission=False,
126
                       permissions=PERMISSIONS_MODS)
127
    async def set_spot_count(self, ctx: SlashContext, user: discord.User, monster_type: int, number: int):
128
        """
129
130
        :param ctx:
131
        :type ctx:
132
        :param user:
133
        :type user:
134
        :param monster_type:
135
        :type monster_type:
136
        :param number:
137
        :type number:
138
        :return:
139
        :rtype:
140
        """
141
        if number < 0:
142
            await ctx.channel.send("Nr of spots can't be lower than 0", delete_after=2)
143
            return
144
        with open("./json_files/monster_spots.json", encoding="utf-8") as f:
145
            try:
146
                spots = json.load(f)
147
            except ValueError:
148
                spots = {"users": []}
149
                await ctx.channel.send("monster_spots.json created", delete_after=1)
150
151
        # TODO: Too many ifs? actually this whole function is written in bad way
152
        for current_user in spots["users"]:
153
            if current_user["id"] == user.id:
154
                if monster_type == 0:
155
                    current_user["rare_spots"] = number
156
                elif monster_type == 1:
157
                    current_user["lege_spots"] = number
158
                elif monster_type == 2:
159
                    pass
160
                elif monster_type == 3:
161
                    pass
162
                elif monster_type == 4:
163
                    current_user["common_spots"] = number
164
                else:
165
                    print("Wrong monster type(?)")
166
167
                current_user["total"] = current_user["lege_spots"] * 5 + current_user["rare_spots"]
168
                break
169
170
        with open("./json_files/monster_spots.json", "w+") as f:
171
            json.dump(spots, f, indent=4)
172
        await ctx.channel.send(f"Nr of spots changed for {user.display_name}", delete_after=4)
173
174
175
def setup(bot: commands.Bot):
176
    bot.add_cog(SpotCog(bot))
177