Passed
Branch BonHowi (26ef6f)
by Bartosz
01:33
created

build.cogs.spotcog.SpotCog.handle_wrong_ping()   A

Complexity

Conditions 3

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 3
nop 2
1
"""
2
Cog with role related commands available in the Bot.
3
4
Current commands:
5
/remove_spot
6
7
"""
8
from datetime import datetime
9
10
import discord
11
from discord.ext import commands, tasks
12
from discord.utils import get
13
import cogs.cogbase as cogbase
14
from cogs.databasecog import DatabaseCog
15
16
monster_type_dict = {0: "rare", 1: "legendary", 2: "event1", 3: "event2", 4: "common"}
17
18
prefix = "/"
19
cords_beginning = ["-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
20
21
22
class SpotCog(cogbase.BaseCog):
23
    def __init__(self, base):
24
        super().__init__(base)
25
        self.peepo_ban_emote: str = ":peepoban:872502800146382898"
26
        self.spotting_channels: list = [self.bot.ch_legendary_spot, self.bot.ch_rare_spot,
27
                                        self.bot.ch_legendary_nemeton, self.bot.ch_rare_nemeton]
28
29
        self.clear_nemeton_channels_loop.start()
30
31
    # Ping monster role
32
    @commands.Cog.listener()
33
    async def on_message(self, ctx) -> None:
34
        if ctx.author.id == self.bot.user.id:
35
            return
36
        # If common spotted
37
        try:
38
            if ctx.channel.id == self.bot.ch_common:
39
                await self.handle_spotted_common(ctx)
40
                return
41
            elif ctx.channel.category and ctx.channel.category.id == self.bot.cat_spotting:
42
                await self.handle_spotted_monster(ctx)
43
                return
44
            # elif ctx.channel.id != self.bot.ch_role_request:
45
            #     await self.handle_wrong_ping(ctx)
46
        except AttributeError:
47
            pass
48
49
        # If monster pinged by member without using bot
50
        channels_not_check = [self.bot.ch_role_request, self.bot.ch_leaderboards, self.bot.ch_leaderboards_common,
51
                              self.bot.ch_leaderboards_event, self.bot.ch_logs, self.bot.ch_spotting_stats]
52
        if ctx.channel.id not in channels_not_check:
53
            await self.handle_wrong_ping(ctx)
54
55
    async def handle_wrong_ping(self, ctx):
56
        guild = self.bot.get_guild(self.bot.guild[0])
57
        guild_roles: list = [role.id for role in ctx.guild.roles]
58
        tagged_roles: list = ([role for role in guild_roles if (str(role) in ctx.content)])
59
        tagged_roles_names = [get(guild.roles, id=role).name for role in tagged_roles]
60
        for monster in self.bot.config["commands"]:
61
            if monster["name"] in tagged_roles_names:
62
                await ctx.channel.send(f"{ctx.author.mention} you have tagged monster without using a bot! "
63
                                       f"Please read #guides and consider it a warning! <{self.peepo_ban_emote}>\n"
64
                                       f"*If you think this message was sent incorrectly please let "
65
                                       f"<@&872189602281193522> know*")
66
67
    @staticmethod
68
    async def handle_spotted_common(ctx) -> None:
69
        if ctx.content[0] in cords_beginning:
70
            await DatabaseCog.db_count_spot(ctx.author.id, "common", "")
71
            await DatabaseCog.db_save_coords(ctx.content, "common")
72
        else:
73
            await ctx.delete()
74
75
    async def handle_spotted_monster(self, ctx) -> None:
76
        if ctx.content.startswith(prefix):
77
            spotted_monster = self.get_monster(ctx, ctx.content.replace(prefix, ""))
78
            if spotted_monster:
79
                monster_type_str = monster_type_dict[spotted_monster["type"]]
80
                if await self.wrong_channel(ctx, spotted_monster, monster_type_str):
81
                    return
82
                role = get(ctx.guild.roles, name=spotted_monster["name"])
83
                await ctx.delete()
84
                await ctx.channel.send(f"{role.mention}")
85
                await DatabaseCog.db_count_spot(ctx.author.id,
86
                                                monster_type_str, spotted_monster["name"])
87
                logs_ch = self.bot.get_channel(self.bot.ch_logs)
88
                await logs_ch.send(f"[PingLog] {ctx.author} ({ctx.author.id}) "
89
                                   f"requested ping for **{spotted_monster['name']}**")
90
            else:
91
                await ctx.delete()
92
                await ctx.channel.send(
93
                    f"{ctx.author.mention} monster not found - are you sure that the name is correct?", delete_after=5)
94
        elif len(ctx.content) > 0 and ctx.content[0] in cords_beginning:
95
            await DatabaseCog.db_save_coords(ctx.content, ctx.channel.name)
96
        elif ctx.channel.id in self.spotting_channels:
97
            await ctx.add_reaction(f"a{self.peepo_ban_emote}")
98
99
    async def wrong_channel(self, ctx, spotted_monster, monster_type_str: str) -> bool:
100
        if ctx.channel.id in self.spotting_channels:
101
            if monster_type_str not in ctx.channel.name:
102
                channel_wild = discord.utils.get(ctx.guild.channels, name=monster_type_str)
103
                correct_channel_wild = channel_wild.id
104
                channel_nemeton = discord.utils.get(ctx.guild.channels, name=f"{monster_type_str}-nemeton")
105
                correct_channel_nemeton = channel_nemeton.id
106
                await ctx.delete()
107
                await ctx.channel.send(
108
                    f"{ctx.author.mention} you posted {spotted_monster['name']} on wrong channel! "
109
                    f"Use <#{correct_channel_wild}> or <#{correct_channel_nemeton}> instead! <{self.peepo_ban_emote}>",
110
                    delete_after=8)
111
                return True
112
            return False
113
114
    @staticmethod
115
    async def clear_channel_messages(channel) -> None:
116
        messages = []
117
        # Can't use datetime.utcnow().date() beacuse discord
118
        today = datetime.utcnow()
119
        today = today.replace(hour=0, minute=0, second=0, microsecond=0)
120
        async for message in channel.history(before=today):
121
            messages.append(message)
122
        await channel.delete_messages(messages)
123
124
    @tasks.loop(hours=3)
125
    async def clear_nemeton_channels_loop(self) -> None:
126
        lege_nemeton = self.bot.get_channel(self.bot.ch_legendary_nemeton)
127
        rare_nemeton = self.bot.get_channel(self.bot.ch_rare_nemeton)
128
        await self.clear_channel_messages(lege_nemeton)
129
        await self.clear_channel_messages(rare_nemeton)
130
        self.create_log_msg("Wiped Nemeton channels")
131
132
    @clear_nemeton_channels_loop.before_loop
133
    async def before_update_leaderboards_loop(self) -> None:
134
        self.create_log_msg(f"Waiting until Bot is ready")
135
        await self.bot.wait_until_ready()
136
137
138
def setup(bot: commands.Bot) -> None:
139
    bot.add_cog(SpotCog(bot))
140