Passed
Push — main ( 8a79dd...88058c )
by Bartosz
02:44 queued 01:26
created

build.cogs.commandscog.MainCog._ping()   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nop 2
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 modules.pull_config.pull_config import get_config
21
22
23
class MainCog(cogbase.BaseCog):
24
    def __init__(self, base):
25
        super().__init__(base)
26
27
    # GENERAL FUNCTIONS
28
    # Check latency
29
    @cog_ext.cog_slash(name="ping", guild_ids=cogbase.GUILD_IDS,
30
                       description="Test function for checking latency",
31
                       default_permission=False,
32
                       permissions=cogbase.PERMISSION_MODS)
33
    async def _ping(self, ctx: SlashContext):
34
        await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms", delete_after=4.0)
35
36
    # Clear messages
37
    @cog_ext.cog_slash(name="clear", guild_ids=cogbase.GUILD_IDS,
38
                       description="Function for clearing messages on channel",
39
                       default_permission=False,
40
                       permissions=cogbase.PERMISSION_MODS)
41
    async def _purge(self, ctx: SlashContext, number):
42
        num_messages = int(number)
43
        await ctx.channel.purge(limit=num_messages)
44
        await ctx.send(f"Cleared {num_messages} messages!", delete_after=4.0)
45
46
    # Disconnect Bot
47
    @cog_ext.cog_slash(name="exit", guild_ids=cogbase.GUILD_IDS,
48
                       description="Turn off the bot",
49
                       default_permission=False,
50
                       permissions=cogbase.PERMISSION_MODS)
51
    async def _exit(self, ctx: SlashContext):
52
        await ctx.send(f"Closing Bot", delete_after=1.0)
53
        print("[INFO]: Exiting Bot")
54
        await asyncio.sleep(3)
55
        await self.bot.close()
56
57
    # WARN FUNCTIONS
58
    # Warn user
59
    @cog_ext.cog_slash(name="warn", guild_ids=cogbase.GUILD_IDS,
60
                       description="Function for warning users",
61
                       default_permission=False,
62
                       permissions=cogbase.PERMISSION_MODS)
63
    async def _warn(self, ctx: SlashContext, user: discord.User, reason: str):
64
        with open('./server_files/warns.json', encoding='utf-8') as f:
65
            try:
66
                report = json.load(f)
67
            except ValueError:
68
                report = {'users': []}
69
70
        warned = False
71
        reason = ''.join(reason)
72
        for current_user in report['users']:
73
            if current_user['id'] == user.id:
74
                current_user['reasons'].append(reason)
75
                warned = True
76
                await ctx.send(f"{user.mention} was warned for:\n\"{reason}\"\n"
77
                               f"Number of warns: {len(current_user['reasons'])}")
78
                break
79
        if not warned:
80
            report['users'].append({
81
                'id': user.id,
82
                'name': user.display_name,
83
                'reasons': [reason, ]
84
            })
85
            # TODO: Improve 'reasons' format(or not?)
86
            await ctx.send(f"{user.mention} was warned for:\n\"{reason}\"\n")
87
88
        with open('./server_files/warns.json', 'w+') as f:
89
            json.dump(report, f, indent=4)
90
91
    # Get list of user's warns
92
    # Does not work if used too much
93
    @cog_ext.cog_slash(name="warns", guild_ids=cogbase.GUILD_IDS,
94
                       description="Function for warning users",
95
                       default_permission=False,
96
                       permissions=cogbase.PERMISSION_MODS)
97
    async def _warns(self, ctx: SlashContext, user: discord.User):
98
        with open('./server_files/warns.json', encoding='utf-8') as f:
99
            try:
100
                report = json.load(f)
101
            except ValueError:
102
                report = {'users': []}
103
104
        for current_user in report['users']:
105
            if user.id == current_user['id']:
106
                message = f"{user.name} has been warned {len(current_user['reasons'])} times\nReasons:\n " \
107
                          f"{','.join(current_user['reasons'])}"
108
                # TODO: Improve 'reasons' message formatting
109
                await ctx.author.send(message)
110
                await ctx.send(f"{user.name} warns has been sent to DM", hidden=True)
111
                break
112
        else:
113
            await ctx.author.send(f"{user.name} has never been warned")
114
            await ctx.send(f"{user.name} warns has been sent to DM", hidden=True)
115
116
    @cog_ext.cog_slash(name="removeWarns", guild_ids=cogbase.GUILD_IDS,
117
                       description="Function for managing user's warns",
118
                       default_permission=False,
119
                       permissions=cogbase.PERMISSION_MODS)
120
    async def remove_warns(self, ctx: SlashContext, user: discord.User, nr_to_delete: int):
121
        if nr_to_delete < 0:
122
            await ctx.send(f"Really? Negative nr?", hidden=True)
123
            return
124
125
        with open('./server_files/warns.json', encoding='utf-8') as f:
126
            try:
127
                report = json.load(f)
128
            except ValueError:
129
                report = {'users': []}
130
131
        warns_removed = False
132
        for current_user in report['users']:
133
            if current_user['id'] == user.id:
134
                current_user['reasons'] = current_user['reasons'][:-nr_to_delete or None]
135
                await ctx.send(f"{user.display_name}'s last {nr_to_delete} warns were deleted", delete_after=5.0)
136
                warns_removed = True
137
                break
138
        if not warns_removed:
139
            await ctx.send(f"{user.display_name} did not have any warns", delete_after=5.0)
140
141
        with open('./server_files/warns.json', 'w+') as f:
142
            json.dump(report, f, indent=4)
143
144
    @cog_ext.cog_slash(name="updateTotMem", guild_ids=cogbase.GUILD_IDS,
145
                       description="Update total number of members",
146
                       default_permission=False,
147
                       permissions=cogbase.PERMISSION_MODS)
148
    async def update_member_count_command(self, ctx: SlashContext):
149
        await self.bot.update_member_count(ctx)
150
        await ctx.send(f"Total Members count updated", hidden=True)
151
152
    @cog_ext.cog_slash(name="updateCommons", guild_ids=cogbase.GUILD_IDS,
153
                       description="Update common channel name",
154
                       default_permission=False,
155
                       permissions=cogbase.PERMISSION_MODS)
156
    async def update_commons_ch(self, ctx: SlashContext, common: str):
157
        new_name = f"common-{common}"
158
        channel = self.bot.get_channel(self.bot.ch_common)
159
        await discord.TextChannel.edit(channel, name=new_name)
160
        await ctx.send(f"Common channel updated", hidden=True)
161
162
    # Pull config.json from Google Sheets
163
    @cog_ext.cog_slash(name="pullConfig", guild_ids=cogbase.GUILD_IDS,
164
                       description="Pull config from google sheets",
165
                       default_permission=False,
166
                       permissions=cogbase.PERMISSION_BONJOWI)
167
    async def pull_config(self, ctx: SlashContext):
168
        get_config()
169
        with open('server_files/config.json', 'r', encoding='utf-8-sig') as fp:
170
            self.bot.config = json.load(fp)
171
            self.bot.reload_extension("cogs.rolecog")
172
        await ctx.send(f"Config.json updated", hidden=True)
173
174
    # OTHER
175
176
    # Did BonJowi killed N-Word? (unstable)
177
    # Apparently you can not use this command more often than every x minutes
178
    @cog_ext.cog_slash(name="nword", guild_ids=cogbase.GUILD_IDS,
179
                       description="Change N-Word channel name",
180
                       permissions=cogbase.PERMISSION_BONJOWI)
181
    async def rename_nword_channel(self, ctx, status: str):
182
        new_status = status
183
        channel = self.bot.get_channel(self.bot.ch_nightmare_killed)
184
        if new_status in channel.name:
185
            await ctx.send(f"{channel.name} has been changed", hidden=True)
186
            return
187
        else:
188
            await discord.VoiceChannel.edit(channel, name=f"N-Word spotted: {new_status}")
189
            await ctx.send(f"{channel.name} channel name has been changed", hidden=True)
190
191
    # async def rename_nword_channel(self, ctx):
192
    #     channel = self.bot.get_channel(CH_NWORD_KILLED)
193
    #     if "YES" in channel.name:
194
    #         new_status = "NO"
195
    #     elif "NO" in channel.name:
196
    #         new_status = "YES"
197
    #     else:
198
    #         return
199
    #     # new_status = "YES" if "NO" in channel.name else "NO" if "YES" in channel.name else ""
200
    #     print(type(new_status))
201
    #     print(new_status)
202
    #     await discord.VoiceChannel.edit(channel, name=f"N-Word killed: {new_status}")
203
    #     await ctx.send(f"{channel.name} channel name has been changed", hidden=True)
204
205
    # Disconnect Bot using "!" prefix (For safety reasons in case Slash commands are not working
206
    @commands.command(name="ex", pass_context=True, aliases=["e", "exit"])
207
    async def exit_bot(self, ctx):
208
        print("[INFO]: Exiting Bot")
209
        await ctx.send(f"Closing Bot")
210
        await self.bot.close()
211
212
213
def setup(bot: commands.Bot):
214
    bot.add_cog(MainCog(bot))
215