Passed
Push — main ( f7b31c...1a3ff0 )
by Bartosz
02:52 queued 01:23
created

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

Complexity

Conditions 4

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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