Failed Conditions
Branch BonHowi (9d60b2)
by Bartosz
03:20
created

build.cogs.admincog.AdminCog.restart_bot()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
import asyncio
2
import os
3
import sys
4
5
import discord
6
import cogs.cogbase as cogbase
7
from discord.ext import commands
8
from discord_slash import cog_ext, SlashContext
9
from cogs.databasecog import DatabaseCog
10
11
12
class AdminCog(cogbase.BaseCog):
13
    def __init__(self, base):
14
        super().__init__(base)
15
16
    # GENERAL FUNCTIONS
17
    # Check latency
18
    @cog_ext.cog_slash(name="ping", guild_ids=cogbase.GUILD_IDS,
19
                       description="Check bot's latency",
20
                       default_permission=False,
21
                       permissions=cogbase.PERMISSION_MODS)
22
    async def check_ping(self, ctx: SlashContext) -> None:
23
        await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms", delete_after=4.0)
24
25
    # Clear messages
26
    @cog_ext.cog_slash(name="clear", guild_ids=cogbase.GUILD_IDS,
27
                       description="Clear messages on channel",
28
                       default_permission=False,
29
                       permissions=cogbase.PERMISSION_MODS)
30
    async def purge_messages(self, ctx: SlashContext, number_to_delete: int = 1) -> None:
31
        messages = []
32
        await ctx.send(f"Clearing {number_to_delete} messages!", delete_after=3)
33
        async for message in ctx.channel.history(limit=number_to_delete + 1):
34
            messages.append(message)
35
        await ctx.channel.delete_messages(messages)
36
37
        await asyncio.sleep(5)
38
39
    # Disconnect Bot
40
    @cog_ext.cog_slash(name="exit", guild_ids=cogbase.GUILD_IDS,
41
                       description="Turn off the bot",
42
                       default_permission=False,
43
                       permissions=cogbase.PERMISSION_ADMINS)
44
    async def exit_bot(self, ctx: SlashContext) -> None:
45
        await ctx.send(f"Closing Bot", delete_after=1.0)
46
        self.create_log_msg("Exiting Bot")
47
        await asyncio.sleep(3)
48
        await self.bot.close()
49
50
    # WARN FUNCTIONS
51
52
    # Warn user
53
    @cog_ext.cog_slash(name="warn", guild_ids=cogbase.GUILD_IDS,
54
                       description="Warn member",
55
                       default_permission=False,
56
                       permissions=cogbase.PERMISSION_MODS)
57
    async def warn_user(self, ctx: SlashContext, user: discord.User, reason: str) -> None:
58
        await DatabaseCog.db_add_warn(user.id, reason)
59
        await ctx.send(
60
            f"{user.mention} was warned for:\n> {reason}\n")
61
62
    # Get list of user's warns
63
    @cog_ext.cog_slash(name="warns", guild_ids=cogbase.GUILD_IDS,
64
                       description="Get member warns",
65
                       default_permission=False,
66
                       permissions=cogbase.PERMISSION_MODS)
67
    async def user_warns(self, ctx: SlashContext, user: discord.User) -> None:
68
        warns, nr_of_warns = await DatabaseCog.db_get_warns(user.id)
69
        nl = "\n"
70
        message = f"**{user.name}** has been warned **{nr_of_warns}** times\n\n_Reasons_:\n" \
71
                  f"{nl.join(warns)}\n"
72
        await ctx.author.send(message)
73
        await ctx.send(f"{user.name} warns has been sent to DM", hidden=True)
74
75
    # Remove all member's warns
76
    @cog_ext.cog_slash(name="removeWarns", guild_ids=cogbase.GUILD_IDS,
77
                       description="Remove all member's warns",
78
                       default_permission=False,
79
                       permissions=cogbase.PERMISSION_ADMINS)
80
    async def remove_warns(self, ctx: SlashContext, user: discord.User) -> None:
81
        await DatabaseCog.db_remove_warns(user.id)
82
        await ctx.send(f"{user.display_name}'s warns were deleted", hidden=True)
83
84
    # Mute member
85
    @cog_ext.cog_slash(name="mute", guild_ids=cogbase.GUILD_IDS,
86
                       description="Mute member for x minutes",
87
                       default_permission=False,
88
                       permissions=cogbase.PERMISSION_MODS)
89
    async def mute_user(self, ctx: SlashContext, user: discord.User, mute_time: int, reason: str) -> None:
90
        duration: int = mute_time * 60
91
        guild = ctx.guild
92
        muted = discord.utils.get(guild.roles, name="Muted")
93
94
        if not muted:
95
            muted = await guild.create_role(name="Muted")
96
            for channel in guild.channels:
97
                await channel.set_permissions(muted, speak=False, send_messages=False, read_message_history=True,
98
                                              read_messages=False)
99
        await user.add_roles(muted, reason=reason)
100
        await ctx.send(f"{user.mention} Was muted by {ctx.author.name} for {mute_time} min\n"
101
                       f"Reason: {reason}")
102
        await asyncio.sleep(duration)
103
        await user.remove_roles(muted)
104
        await ctx.send(f"{user.mention}'s mute is over", delete_after=30)
105
        await self.bot.send_message(user, "Your mute is over")
106
107
    # KICK FUNCTIONS
108
    @staticmethod
109
    async def operation(ctx: SlashContext, user: discord.Member, operation_t: str, reason: str = None) -> None:
110
        if user == ctx.author:
111
            await ctx.send(f"{user.mention} You can't {operation_t} yourself", delete_after=5.0)
112
        if operation_t == "kick":
113
            await user.kick(reason=reason)
114
        elif operation_t == "ban":
115
            await user.ban(reason=reason)
116
        elif operation_t == "softban":
117
            await user.ban(reason=reason)
118
            await user.unban(reason=reason)
119
        reason_str: str = f"\nReason: {reason}" if reason else ""
120
        await ctx.send(f"{user} was {operation_t}ed{reason_str}")
121
        await user.send(f"You were {operation_t}ed from {ctx.guild.name}{reason_str}")
122
123
    # Kick
124
    @cog_ext.cog_slash(name="kick", guild_ids=cogbase.GUILD_IDS,
125
                       description="Kicks member from the server",
126
                       default_permission=False,
127
                       permissions=cogbase.PERMISSION_MODS)
128
    async def kick(self, ctx: SlashContext, user: discord.Member, *, reason: str = None) -> None:
129
        operation_t: str = "kick"
130
        await self.operation(ctx, user, operation_t, reason)
131
132
    # Ban
133
    @cog_ext.cog_slash(name="ban", guild_ids=cogbase.GUILD_IDS,
134
                       description="Ban member from the server",
135
                       default_permission=False,
136
                       permissions=cogbase.PERMISSION_ADMINS)
137
    async def ban(self, ctx, user: discord.Member, *, reason: str = None) -> None:
138
        operation_t: str = "ban"
139
        await self.operation(ctx, user, operation_t, reason)
140
141
    # Softban
142
    @cog_ext.cog_slash(name="softban", guild_ids=cogbase.GUILD_IDS,
143
                       description="Ban and unban the user, so their messages are deleted",
144
                       default_permission=False,
145
                       permissions=cogbase.PERMISSION_MODS)
146
    async def softban(self, ctx, user: discord.Member, *, reason: str = None) -> None:
147
        operation_t: str = "softban"
148
        await self.operation(ctx, user, operation_t, reason)
149
150
    # OTHER
151
    # Slow mode
152
    @cog_ext.cog_slash(name="slowmode", guild_ids=cogbase.GUILD_IDS,
153
                       description="Enable slowmode on current channel",
154
                       default_permission=False,
155
                       permissions=cogbase.PERMISSION_MODS)
156
    async def slowmode(self, ctx: SlashContext, seconds: int = 0) -> None:
157
        if seconds > 120:
158
            await ctx.send(":no_entry: Amount can't be over 120 seconds")
159
        elif seconds == 0:
160
            await ctx.channel.edit(slowmode_delay=seconds)
161
            a = await ctx.send("Slowmode is off for this channel")
162
            await a.add_reaction("a:redcard:871861842639716472")
163
        else:
164
            if seconds == 1:
165
                numofsecs = "second"
166
            else:
167
                numofsecs = "seconds"
168
            await ctx.channel.edit(slowmode_delay=seconds)
169
            confirm = await ctx.send(
170
                f"{ctx.author.display_name} set the channel slow mode delay to `{seconds}` {numofsecs}\n"
171
                f"To turn this off use /slowmode")
172
            await confirm.add_reaction("a:ResidentWitcher:871872130021736519")
173
174
    # Restart bot
175
    @cog_ext.cog_slash(name="restartBot", guild_ids=cogbase.GUILD_IDS,
176
                       description="Restart bot",
177
                       default_permission=False,
178
                       permissions=cogbase.PERMISSION_MODS)
179
    async def restart_bot(self, ctx: SlashContext):
180
        await ctx.send("Restarting bot")
181
        os.execv(sys.executable, ['python'] + sys.argv)
182
        self.create_log_msg("Bot restarted")
183
184
185
def setup(bot: commands.Bot) -> None:
186
    bot.add_cog(AdminCog(bot))
187