Passed
Branch BonHowi (3ad014)
by Bartosz
02:05
created

CommandsCog.update_member_count_command()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 2
dl 0
loc 7
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
    @cog_ext.cog_slash(name="warns", guild_ids=cogbase.GUILD_IDS,
74
                       description="Function for warning users",
75
                       default_permission=False,
76
                       permissions=cogbase.PERMISSION_MODS)
77
    async def _warns(self, ctx: SlashContext, user: discord.User):
78
        warns, nr_of_warns = await DatabaseCog.db_get_warns(user.id)
79
        nl = "\n"
80
        message = f"**{user.name}** has been warned **{nr_of_warns}** times\n\n_Reasons_:\n" \
81
                  f"{nl.join(warns)}\n"
82
        await ctx.author.send(message)
83
        await ctx.send(f"{user.name} warns has been sent to DM", hidden=True)
84
85
    # Remove all member's warns
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
    # Mute member
95
    @cog_ext.cog_slash(name="mute", guild_ids=cogbase.GUILD_IDS,
96
                       description="Mute member for x minutes",
97
                       default_permission=False,
98
                       permissions=cogbase.PERMISSION_MODS)
99
    async def _mute(self, ctx: SlashContext, user: discord.User, time: int, reason: str):
100
        duration = time * 60
101
        guild = ctx.guild
102
        muted = discord.utils.get(guild.roles, name="Muted")
103
104
        if not muted:
105
            muted = await guild.create_role(name="Muted")
106
            for channel in guild.channels:
107
                await channel.set_permissions(muted, speak=False, send_messages=False, read_message_history=True,
108
                                              read_messages=False)
109
        await user.add_roles(muted, reason=reason)
110
        await ctx.send(f"{user.mention} Was muted by {ctx.author.name} for {time} min\n"
111
                       f"Reason: {reason}", delete_after=10)
112
        await asyncio.sleep(duration)
113
        await user.remove_roles(muted)
114
        await ctx.send(f"{ctx.author.mention} mute is over", delete_after=10)
115
116
    # CHANNEL NAMES UPDATES
117
    # Total member channel name
118
    @cog_ext.cog_slash(name="updateTotMem", guild_ids=cogbase.GUILD_IDS,
119
                       description="Update total number of members",
120
                       default_permission=False,
121
                       permissions=cogbase.PERMISSION_MODS)
122
    async def update_member_count_command(self, ctx: SlashContext):
123
        await self.bot.update_member_count(ctx)
124
        await ctx.send(f"Total Members count updated", hidden=True)
125
126
    # Commons channel name
127
    @cog_ext.cog_slash(name="updateCommons", guild_ids=cogbase.GUILD_IDS,
128
                       description="Update common channel name",
129
                       default_permission=False,
130
                       permissions=cogbase.PERMISSION_MODS)
131
    async def update_commons_ch(self, ctx: SlashContext, common: str):
132
        new_name = f"common {common}"
133
        channel = self.bot.get_channel(self.bot.ch_common)
134
        await discord.TextChannel.edit(channel, name=new_name)
135
        await ctx.send(f"Common channel updated", hidden=True)
136
137
    # N-Word spotted channel name
138
    # Doesn't work if used too many times in a short period of time
139
    @cog_ext.cog_slash(name="nword", guild_ids=cogbase.GUILD_IDS,
140
                       description="Change N-Word channel name",
141
                       permissions=cogbase.PERMISSION_ADMINS)
142
    async def rename_nword_channel(self, ctx, status: str):
143
        new_status = status
144
        channel = self.bot.get_channel(self.bot.ch_nightmare_killed)
145
        if new_status in channel.name:
146
            await ctx.send(f"{channel.name} has been changed", hidden=True)
147
        else:
148
            await discord.VoiceChannel.edit(channel, name=f"N-Word spotted: {new_status}")
149
            await ctx.send(f"{channel.name} channel name has been changed", hidden=True)
150
151
    # OTHER
152
153
    # Pull config.json from Google Sheets
154
    @cog_ext.cog_slash(name="pullConfig", guild_ids=cogbase.GUILD_IDS,
155
                       description="Pull config from google sheets",
156
                       default_permission=False,
157
                       permissions=cogbase.PERMISSION_ADMINS)
158
    async def pull_config(self, ctx: SlashContext):
159
        get_config()
160
        with open('server_files/config.json', 'r', encoding='utf-8-sig') as fp:
161
            self.bot.config = json.load(fp)
162
            await self.create_roles(ctx, True)
163
            await self.create_roles(ctx, False)
164
            print(f"[{self.__class__.__name__}]: Finished data pull")
165
        await ctx.send(f"Config.json updated", hidden=True)
166
167
    # Create roles if pull_config gets non existent roles
168
    async def create_roles(self, ctx: SlashContext, common: bool):
169
        milestones = "common_milestones" if common else "total_milestones"
170
        for mon_type in self.bot.config[milestones][0]:
171
            if get(ctx.guild.roles, name=mon_type):
172
                continue
173
            else:
174
                await ctx.guild.create_role(name=mon_type)
175
                print(f"[{self.__class__.__name__}]: {mon_type} role created")
176
177
    # Clear temp spots table in database
178
    @cog_ext.cog_slash(name="clearTempSpots", guild_ids=cogbase.GUILD_IDS,
179
                       description="Clear temp spots table in database",
180
                       permissions=cogbase.PERMISSION_ADMINS)
181
    async def clear_temp_spots_table(self, ctx):
182
        await DatabaseCog.db_clear_spots_temp_table()
183
        await ctx.send(f"Temp spots table was cleared", hidden=True)
184
        await self.reload_cog(ctx, "cogs.databasecog")
185
186
    # Reloads cog, very useful because there is no need to exit the bot after updating cog
187
    async def reload_cog(self, ctx: SlashContext, module: str):
188
        """Reloads a module."""
189
        try:
190
            self.bot.load_extension(f"{module}")
191
            await ctx.send(f'[{module}] loaded', hidden=True)
192
            print(f'[{self.__class__.__name__}]: {module} loaded')
193
        except commands.ExtensionAlreadyLoaded:
194
            self.bot.unload_extension(module)
195
            self.bot.load_extension(module)
196
            await ctx.send(f'[{module}] reloaded', hidden=True)
197
            print(f'[{self.__class__.__name__}]: {module} reloaded')
198
        except commands.ExtensionNotFound:
199
            await ctx.send(f'[{module}] not found', hidden=True)
200
            print(f'[{self.__class__.__name__}]: {module} not found')
201
202
    # Command for reloading specific cog
203
    @cog_ext.cog_slash(name="reloadCog", guild_ids=cogbase.GUILD_IDS,
204
                       description="Reload cog",
205
                       permissions=cogbase.PERMISSION_ADMINS)
206
    async def reload_cog_command(self, ctx: SlashContext, module: str):
207
        await self.reload_cog(ctx, module)
208
209
    # Command for reloading all cogs
210
    @cog_ext.cog_slash(name="reloadAllCogs", guild_ids=cogbase.GUILD_IDS,
211
                       description="Reload cog",
212
                       permissions=cogbase.PERMISSION_ADMINS)
213
    async def reload_all_cogs(self, ctx: SlashContext = None):
214
        for cog in list(self.bot.extensions.keys()):
215
            await self.reload_cog(ctx, cog)
216
        await ctx.send(f'All cogs reloaded', hidden=True)
217
218
219
def setup(bot: commands.Bot):
220
    bot.add_cog(CommandsCog(bot))
221