Passed
Branch BonHowi (f2834f)
by Bartosz
01:31
created

CommandsCog.reload_cog_command()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
"""
2
Cog with general commands available in the Bot.
3
4
Current commands:
5
/ping -     check Bot latency
6
/clear -    clear x messages on the channel
7
/exit | !exit -     end Bot's runtime and disconnect from the server
8
/warn -     warn @user with reason
9
/warns -    send @user warns to author's DM
10
/nword -    Changes N-Word killed channel name  -   UNSTABLE
11
/updatetotmem - Update #TotalMembers channel
12
/updatecommon - Update common spotting channel with new monster name
13
"""
14
import asyncio
15
import json
16
import discord
17
from discord.utils import get
18
19
import cogs.cogbase as cogbase
20
from discord.ext import commands
21
from discord_slash import cog_ext, SlashContext
22
from cogs.databasecog import DatabaseCog
23
from modules.pull_config.pull_config import get_config
24
25
26
class CommandsCog(cogbase.BaseCog):
27
    def __init__(self, base):
28
        super().__init__(base)
29
30
    # GENERAL FUNCTIONS
31
    # Check latency
32
    @cog_ext.cog_slash(name="ping", guild_ids=cogbase.GUILD_IDS,
33
                       description="Test function for checking latency",
34
                       default_permission=False,
35
                       permissions=cogbase.PERMISSION_MODS)
36
    async def _ping(self, ctx: SlashContext):
37
        await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms", delete_after=4.0)
38
39
    # Clear messages
40
    @cog_ext.cog_slash(name="clear", guild_ids=cogbase.GUILD_IDS,
41
                       description="Function for clearing messages on channel",
42
                       default_permission=False,
43
                       permissions=cogbase.PERMISSION_MODS)
44
    async def _purge(self, ctx: SlashContext, number):
45
        num_messages = int(number)
46
        await ctx.channel.purge(limit=num_messages)
47
        await ctx.send(f"Cleared {num_messages} messages!", delete_after=4.0)
48
49
    # Disconnect Bot
50
    @cog_ext.cog_slash(name="exit", guild_ids=cogbase.GUILD_IDS,
51
                       description="Turn off the bot",
52
                       default_permission=False,
53
                       permissions=cogbase.PERMISSION_ADMINS)
54
    async def _exit(self, ctx: SlashContext):
55
        await ctx.send(f"Closing Bot", delete_after=1.0)
56
        print(f"[{self.__class__.__name__}]: Exiting Bot")
57
        await asyncio.sleep(3)
58
        await self.bot.close()
59
60
    # WARN FUNCTIONS
61
    # Warn user
62
    @cog_ext.cog_slash(name="warn", guild_ids=cogbase.GUILD_IDS,
63
                       description="Function for warning users",
64
                       default_permission=False,
65
                       permissions=cogbase.PERMISSION_MODS)
66
    async def _warn(self, ctx: SlashContext, user: discord.User, reason: str):
67
68
        await DatabaseCog.db_add_warn(user.id, reason)
69
        await ctx.send(
70
            f"{user.mention} was warned for:\n*\"{reason}\"*\n")  # f"Number of warns: {len(current_user['reasons'])}")
71
72
    # Get list of user's warns
73
    # Does not work if used too much
74
    @cog_ext.cog_slash(name="warns", guild_ids=cogbase.GUILD_IDS,
75
                       description="Function for warning users",
76
                       default_permission=False,
77
                       permissions=cogbase.PERMISSION_MODS)
78
    async def _warns(self, ctx: SlashContext, user: discord.User):
79
        warns, nr_of_warns = await DatabaseCog.db_get_warns(user.id)
80
        nl = "\n"
81
        message = f"**{user.name}** has been warned **{nr_of_warns}** times\n\n_Reasons_:\n" \
82
                  f"{nl.join(warns)}"
83
        await ctx.author.send(message)
84
        await ctx.send(f"{user.name} warns has been sent to DM", hidden=True)
85
86
    @cog_ext.cog_slash(name="removeWarns", guild_ids=cogbase.GUILD_IDS,
87
                       description="Function for removing user's all warns",
88
                       default_permission=False,
89
                       permissions=cogbase.PERMISSION_ADMINS)
90
    async def remove_warns(self, ctx: SlashContext, user: discord.User):
91
        await DatabaseCog.db_remove_warns(user.id)
92
        await ctx.send(f"{user.display_name}'s warns were deleted", hidden=True)
93
94
    @cog_ext.cog_slash(name="updateTotMem", guild_ids=cogbase.GUILD_IDS,
95
                       description="Update total number of members",
96
                       default_permission=False,
97
                       permissions=cogbase.PERMISSION_MODS)
98
    async def update_member_count_command(self, ctx: SlashContext):
99
        await self.bot.update_member_count(ctx)
100
        await ctx.send(f"Total Members count updated", hidden=True)
101
102
    @cog_ext.cog_slash(name="updateCommons", guild_ids=cogbase.GUILD_IDS,
103
                       description="Update common channel name",
104
                       default_permission=False,
105
                       permissions=cogbase.PERMISSION_MODS)
106
    async def update_commons_ch(self, ctx: SlashContext, common: str):
107
        new_name = f"common-{common}"
108
        channel = self.bot.get_channel(self.bot.ch_common)
109
        await discord.TextChannel.edit(channel, name=new_name)
110
        await ctx.send(f"Common channel updated", hidden=True)
111
112
    # Pull config.json from Google Sheets
113
    @cog_ext.cog_slash(name="pullConfig", guild_ids=cogbase.GUILD_IDS,
114
                       description="Pull config from google sheets",
115
                       default_permission=False,
116
                       permissions=cogbase.PERMISSION_ADMINS)
117
    async def pull_config(self, ctx: SlashContext):
118
        get_config()
119
        with open('server_files/config.json', 'r', encoding='utf-8-sig') as fp:
120
            self.bot.config = json.load(fp)
121
            self.bot.reload_extension("cogs.requestcog")
122
            for mon_type in self.bot.config["total_milestones"][0]:
123
                if get(ctx.guild.roles, name=mon_type):
124
                    continue
125
                else:
126
                    await ctx.guild.create_role(name=mon_type)
127
                    print(f"[{self.__class__.__name__}]: {mon_type} role created")
128
            for mon_type in self.bot.config["common_milestones"][0]:
129
                if get(ctx.guild.roles, name=mon_type):
130
                    continue
131
                else:
132
                    await ctx.guild.create_role(name=mon_type)
133
                    print(f"[{self.__class__.__name__}]: {mon_type} role created")
134
135
            print(f"[{self.__class__.__name__}]: Finished data pull")
136
        await ctx.send(f"Config.json updated", hidden=True)
137
138
    # OTHER
139
    @cog_ext.cog_slash(name="clearTempSpots", guild_ids=cogbase.GUILD_IDS,
140
                       description="Clear temp spots table in database",
141
                       permissions=cogbase.PERMISSION_ADMINS)
142
    async def clear_temp_spots_table(self, ctx):
143
        await DatabaseCog.db_clear_spots_temp_table()
144
        await ctx.send(f"Temp spots table was cleared", hidden=True)
145
        await self.reload_cog(ctx, "cogs.databasecog")
146
147
    # Did BonJowi killed N-Word? (unstable)
148
    # Apparently you can not use this command more often than every x minutes
149
    @cog_ext.cog_slash(name="nword", guild_ids=cogbase.GUILD_IDS,
150
                       description="Change N-Word channel name",
151
                       permissions=cogbase.PERMISSION_ADMINS)
152
    async def rename_nword_channel(self, ctx, status: str):
153
        new_status = status
154
        channel = self.bot.get_channel(self.bot.ch_nightmare_killed)
155
        if new_status in channel.name:
156
            await ctx.send(f"{channel.name} has been changed", hidden=True)
157
        else:
158
            await discord.VoiceChannel.edit(channel, name=f"N-Word spotted: {new_status}")
159
            await ctx.send(f"{channel.name} channel name has been changed", hidden=True)
160
161
    # Reloads cog, very useful because there is no need to exit the bot after updating cog
162
    async def reload_cog(self, ctx: SlashContext, module: str):
163
        """Reloads a module."""
164
        try:
165
            self.bot.load_extension(f"{module}")
166
            await ctx.send(f'[{module}] loaded', hidden=True)
167
            print(f'[{self.__class__.__name__}]: {module} loaded')
168
        except commands.ExtensionAlreadyLoaded:
169
            self.bot.unload_extension(module)
170
            self.bot.load_extension(module)
171
            await ctx.send(f'[{module}] reloaded', hidden=True)
172
            print(f'[{self.__class__.__name__}]: {module} reloaded')
173
        except commands.ExtensionNotFound:
174
            await ctx.send(f'[{module}] not found', hidden=True)
175
            print(f'[{self.__class__.__name__}]: {module} not found')
176
177
    # Command for reloading specific cog
178
    @cog_ext.cog_slash(name="reloadCog", guild_ids=cogbase.GUILD_IDS,
179
                       description="Reload cog",
180
                       permissions=cogbase.PERMISSION_ADMINS)
181
    async def reload_cog_command(self, ctx: SlashContext, module: str):
182
        await self.reload_cog(ctx, module)
183
184
    # Command for reloading all cogs
185
    @cog_ext.cog_slash(name="reloadAllCogs", guild_ids=cogbase.GUILD_IDS,
186
                       description="Reload cog",
187
                       permissions=cogbase.PERMISSION_ADMINS)
188
    async def reload_all_cogs(self, ctx: SlashContext = None):
189
        for cog in list(self.bot.extensions.keys()):
190
            await self.reload_cog(ctx, cog)
191
        await ctx.send(f'All cogs reloaded', hidden=True)
192
193
194
def setup(bot: commands.Bot):
195
    bot.add_cog(CommandsCog(bot))
196