Passed
Branch BonHowi (242417)
by Bartosz
01:38
created

build.cogs.commandscog.MainCog._warns()   B

Complexity

Conditions 6

Size

Total Lines 22
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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