Passed
Branch BonHowi (45c1c7)
by Bartosz
01:21
created

build.main.MyBot.on_message()   A

Complexity

Conditions 5

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 13
rs 9.3333
c 0
b 0
f 0
cc 5
nop 2
1
import json
2
import logging
3
import os
4
from datetime import datetime
5
import discord
6
from discord.ext import commands, tasks
7
from discord_slash import SlashCommand
8
from time import time
9
10
from modules.get_settings import get_settings
11
12
# Create logger
13
logger = logging.getLogger('discord')
14
logger.setLevel(logging.DEBUG)
15
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
16
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
17
logger.addHandler(handler)
18
19
# Set bot privileges
20
intents = discord.Intents.all()
21
22
23
class MyBot(commands.Bot):
24
25
    def __init__(self):
26
        super().__init__(command_prefix="!", intents=intents)
27
28
        dt_string = self.get_current_time()
29
        print(f"({dt_string})\t[{self.__class__.__name__}]: Init")
30
        print(f"({dt_string})\t[{self.__class__.__name__}]: Rate limited: {self.is_ws_ratelimited()}")
31
        self.start_time = time()
32
        self.version = "1.2"
33
34
        self.guild = get_settings("guild")
35
        self.ch_admin_posting = get_settings("CH_ADMIN_POSTING")
36
        self.ch_role_request = get_settings("CH_ROLE_REQUEST")
37
        self.ch_total_members = get_settings("CH_TOTAL_MEMBERS")
38
        self.ch_nightmare_killed = get_settings("CH_NIGHTMARE_KILLED")
39
        self.ch_leaderboards = get_settings("CH_LEADERBOARDS")
40
        self.ch_leaderboards_common = get_settings("CH_LEADERBOARDS_COMMON")
41
        self.ch_leaderboards_event = get_settings("CH_LEADERBOARDS_EVENT")
42
        self.ch_legendary_spot = get_settings("CH_LEGENDARY_SPOT")
43
        self.ch_legendary_nemeton = get_settings("CH_LEGENDARY_NEMETON")
44
        self.ch_rare_spot = get_settings("CH_RARE_SPOT")
45
        self.ch_rare_nemeton = get_settings("CH_RARE_NEMETON")
46
        self.ch_common = get_settings("CH_COMMON")
47
        self.ch_werewolf = get_settings("CH_WEREWOLF")
48
        self.ch_wraiths = get_settings("CH_WRAITHS")
49
        self.ch_nemeton = get_settings("CH_NEMETON")
50
        self.ch_logs = get_settings("CH_LOGS")
51
        self.ch_discussion_en = get_settings("CH_DISCUSSION_EN")
52
        self.ch_spotting_stats = get_settings("CH_SPOTTING_STATS")
53
        self.cat_spotting = get_settings("CAT_SPOTTING")
54
        self.update_ch_commons_loop.start()
55
56
        with open('server_files/config.json', 'r', encoding='utf-8-sig') as fp:
57
            self.config = json.load(fp)
58
59
    # On bot ready
60
    async def on_ready(self) -> None:
61
        await MyBot.change_presence(self, activity=discord.Activity(type=discord.ActivityType.playing,
62
                                                                    name="The Witcher: Monster Slayer"))
63
        dt_string = self.get_current_time()
64
        print(f"({dt_string})\t[{self.__class__.__name__}]: Bot is ready")
65
66
    async def update_member_count(self, ctx) -> int:
67
        true_member_count = len([m for m in ctx.guild.members if not m.bot])
68
        new_name = f"Total members: {true_member_count}"
69
        channel_tm = self.get_channel(self.ch_total_members)
70
        await discord.VoiceChannel.edit(channel_tm, name=new_name)
71
        return true_member_count
72
73
    # On member join
74
    async def on_member_join(self, ctx) -> None:
75
        member_count = await self.update_member_count(ctx)
76
        dt_string = self.get_current_time()
77
        print(f"({dt_string})\t[{self.__class__.__name__}]: {ctx} joined")
78
79
        if (member_count % 100) == 0:
80
            channel = self.get_channel(self.ch_admin_posting)
81
            await channel.send(f"{member_count} members <:POGMARE:872496675434942484>")
82
83
    async def on_member_remove(self, ctx):
84
        await self.update_member_count(ctx)
85
        dt_string = self.get_current_time()
86
        print(f"({dt_string})\t[{self.__class__.__name__}]: {ctx} left")
87
88
    # Manage on message actions
89
    async def on_message(self, ctx) -> None:
90
        # If bot is the message author
91
        if ctx.author.id == self.user.id:
92
            return
93
        if isinstance(ctx.channel, discord.channel.DMChannel) and ctx.author != self.user:
94
            await ctx.channel.send("If you have any questions please ask my creator - BonJowi#0119")
95
96
        # If there is a message with "!" prefix
97
        if ctx.content.startswith("!"):
98
            await ctx.channel.send(
99
                fr"{ctx.author.mention} Please use / instead of ! to use commands on this server!",
100
                delete_after=5.0)
101
            await ctx.delete()
102
103
    # Loop tasks
104
    # Update common spotting channel name
105
    async def update_ch_commons(self) -> None:
106
        with open('./server_files/commons.txt') as f:
107
            try:
108
                commons = f.read().splitlines()
109
            except ValueError:
110
                print(ValueError)
111
112
        new_name = f"common {commons[0]}"
113
        common_ch = self.get_channel(self.ch_common)
114
        await discord.TextChannel.edit(common_ch, name=new_name)
115
        dt_string = self.get_current_time()
116
        print(f"({dt_string})\t[{self.__class__.__name__}]: Common channel name updated: {commons[0]}")
117
118
        await common_ch.send(f"Common changed: **{commons[0]}**")
119
120
        commons.append(commons.pop(commons.index(commons[0])))
121
        with open('./server_files/commons.txt', 'w') as f:
122
            for item in commons:
123
                f.write("%s\n" % item)
124
125
    # Update commons channel name every day at 12:00
126
    @tasks.loop(minutes=60.0)
127
    async def update_ch_commons_loop(self) -> None:
128
        if datetime.utcnow().hour == 14:
129
            await self.update_ch_commons()
130
131
    @update_ch_commons_loop.before_loop
132
    async def before_update_ch_commons(self) -> None:
133
        await self.wait_until_ready()
134
135
    @staticmethod
136
    def get_current_time() -> str:
137
        now = datetime.utcnow()
138
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S") + " UTC"
139
        return dt_string
140
141
142
def main() -> None:
143
    pogmare = MyBot()
144
145
    # Allow slash commands
146
    slash = SlashCommand(pogmare, sync_commands=True, sync_on_cog_reload=False)
147
148
    # Load cogs
149
    for cog in os.listdir("./cogs"):
150
        if cog.endswith("cog.py"):
151
            try:
152
                cog = f"cogs.{cog.replace('.py', '')}"
153
                pogmare.load_extension(cog)
154
            except Exception as e:
155
                print(f"{cog} Could not be loaded")
156
                raise e
157
158
    pogmare.run(get_settings("token"))
159
160
161
if __name__ == "__main__":
162
    main()
163