Passed
Push — main ( 4d254e...b95c28 )
by Bartosz
02:30 queued 01:14
created

build.cogs.commandscog.CommandsCog.reload_cog()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nop 3
dl 0
loc 12
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["milestones"][0]:
123
                if get(ctx.guild.roles, name=mon_type):
124
                    pass
125
                else:
126
                    await ctx.guild.create_role(name=mon_type)
127
                    print(f"[{self.__class__.__name__}]: {mon_type} role created")
128
            print(f"[{self.__class__.__name__}]: Finished data pull")
129
        await ctx.send(f"Config.json updated", hidden=True)
130
131
    # OTHER
132
    @cog_ext.cog_slash(name="clearTempSpots", guild_ids=cogbase.GUILD_IDS,
133
                       description="Clear temp spots table in database",
134
                       permissions=cogbase.PERMISSION_ADMINS)
135
    async def clear_temp_spots_table(self, ctx):
136
        await DatabaseCog.db_clear_spots_temp_table()
137
        await ctx.send(f"Temp spots table was cleared", hidden=True)
138
        await self.reload_cog("cogs.databasecog")
139
140
    # Did BonJowi killed N-Word? (unstable)
141
    # Apparently you can not use this command more often than every x minutes
142
    @cog_ext.cog_slash(name="nword", guild_ids=cogbase.GUILD_IDS,
143
                       description="Change N-Word channel name",
144
                       permissions=cogbase.PERMISSION_ADMINS)
145
    async def rename_nword_channel(self, ctx, status: str):
146
        new_status = status
147
        channel = self.bot.get_channel(self.bot.ch_nightmare_killed)
148
        if new_status in channel.name:
149
            await ctx.send(f"{channel.name} has been changed", hidden=True)
150
            return
151
        else:
152
            await discord.VoiceChannel.edit(channel, name=f"N-Word spotted: {new_status}")
153
            await ctx.send(f"{channel.name} channel name has been changed", hidden=True)
154
155
    # Reloads cog, very useful because there is no need to exit the bot after updating cog
156
    # TODO: load cog if not loaded
157
    async def reload_cog(self, module: str, ctx: SlashContext = None):
158
        """Reloads a module."""
159
        try:
160
            self.bot.unload_extension(module)
161
            self.bot.load_extension(module)
162
        except Exception as e:
163
            # await ctx.send(f'[{module}] not reloaded', hidden=True)
164
            print(f'[{module}] not reloaded')
165
            print(f'{type(e)}: {e}')
166
        else:
167
            # await ctx.send(f'[{module}] reloaded', hidden=True)
168
            print(f'[{module}] reloaded')
169
170
    # Command for reloading specific cog
171
    @cog_ext.cog_slash(name="reloadCog", guild_ids=cogbase.GUILD_IDS,
172
                       description="Reload cog",
173
                       permissions=cogbase.PERMISSION_ADMINS)
174
    async def reload_cog_command(self, module: str, ctx: SlashContext = None):
175
        await self.reload_cog(ctx, module)
176
177
    # Command for reloading all cogs
178
    @cog_ext.cog_slash(name="reloadAllCogs", guild_ids=cogbase.GUILD_IDS,
179
                       description="Reload cog",
180
                       permissions=cogbase.PERMISSION_ADMINS)
181
    async def reload_all_cogs(self, ctx: SlashContext = None):
182
        for cog in list(self.bot.extensions.keys()):
183
            await self.reload_cog(cog)
184
        await ctx.send(f'All cogs reloaded', hidden=True)
185
186
187
def setup(bot: commands.Bot):
188
    bot.add_cog(CommandsCog(bot))
189