Passed
Branch BonHowi (faf5f7)
by Bartosz
01:26
created

build.main.MyBot.create_main_log_msg()   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 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
        self.create_main_log_msg(f"\n --------------- STARTING BOT ---------------")
29
        self.create_main_log_msg(f"Init")
30
        self.create_main_log_msg(f"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
    def create_main_log_msg(self, message: str) -> None:
60
        dt_string = self.get_current_time()
61
        log: str = f"({dt_string})\t[{self.__class__.__name__}]: {message}"
62
        print(log)
63
        logs_txt_dir: str = "logs/logs.txt"
64
        file_object = open(logs_txt_dir, "a+")
65
        file_object.write(f"{log}\n")
66
        file_object.close()
67
68
    # On bot ready
69
    async def on_ready(self) -> None:
70
        await MyBot.change_presence(self, activity=discord.Activity(type=discord.ActivityType.playing,
71
                                                                    name="The Witcher: Monster Slayer"))
72
        self.create_main_log_msg("Bot is ready")
73
74
    async def update_member_count(self, ctx) -> int:
75
        true_member_count = len([m for m in ctx.guild.members if not m.bot])
76
        new_name = f"Total members: {true_member_count}"
77
        channel_tm = self.get_channel(self.ch_total_members)
78
        await discord.VoiceChannel.edit(channel_tm, name=new_name)
79
        return true_member_count
80
81
    # On member join
82
    async def on_member_join(self, ctx) -> None:
83
        member_count = await self.update_member_count(ctx)
84
        self.create_main_log_msg(f"{ctx} joined")
85
86
        if (member_count % 100) == 0:
87
            channel = self.get_channel(self.ch_admin_posting)
88
            await channel.send(f"{member_count} members <:POGMARE:872496675434942484>")
89
90
    async def on_member_remove(self, ctx):
91
        await self.update_member_count(ctx)
92
        self.create_main_log_msg(f"{ctx} left")
93
94
    # Manage on message actions
95
    async def on_message(self, ctx) -> None:
96
        # If bot is the message author
97
        if ctx.author.id == self.user.id:
98
            return
99
        if isinstance(ctx.channel, discord.channel.DMChannel) and ctx.author != self.user:
100
            await ctx.channel.send("If you have any questions please ask my creator - BonJowi#0119")
101
102
        # If there is a message with "!" prefix
103
        if ctx.content.startswith("!"):
104
            await ctx.channel.send(
105
                fr"{ctx.author.mention} Please use / instead of ! to use commands on this server!",
106
                delete_after=5.0)
107
            await ctx.delete()
108
109
    # Loop tasks
110
    # Update common spotting channel name
111
    async def update_ch_commons(self) -> None:
112
        with open('./server_files/commons.txt') as f:
113
            try:
114
                commons = f.read().splitlines()
115
            except ValueError:
116
                print(ValueError)
117
118
        new_name = f"common {commons[0]}"
119
        common_ch = self.get_channel(self.ch_common)
120
        await discord.TextChannel.edit(common_ch, name=new_name)
121
        self.create_main_log_msg(f"Common channel name updated: {commons[0]}")
122
        await common_ch.send(f"Common changed: **{commons[0]}**")
123
124
        commons.append(commons.pop(commons.index(commons[0])))
125
        with open('./server_files/commons.txt', 'w') as f:
126
            for item in commons:
127
                f.write("%s\n" % item)
128
129
    # Update commons channel name every day at 12:00
130
    @tasks.loop(minutes=60.0)
131
    async def update_ch_commons_loop(self) -> None:
132
        if datetime.utcnow().hour == 14:
133
            await self.update_ch_commons()
134
135
    @update_ch_commons_loop.before_loop
136
    async def before_update_ch_commons(self) -> None:
137
        await self.wait_until_ready()
138
139
    @staticmethod
140
    def get_current_time() -> str:
141
        now = datetime.utcnow()
142
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S") + " UTC"
143
        return dt_string
144
145
146
def main() -> None:
147
    pogmare = MyBot()
148
149
    # Allow slash commands
150
    slash = SlashCommand(pogmare, sync_commands=True, sync_on_cog_reload=False)
151
152
    # Load cogs
153
    for cog in os.listdir("./cogs"):
154
        if cog.endswith("cog.py"):
155
            try:
156
                cog = f"cogs.{cog.replace('.py', '')}"
157
                pogmare.load_extension(cog)
158
            except Exception as e:
159
                print(f"{cog} Could not be loaded")
160
                raise e
161
162
    pogmare.run(get_settings("token"))
163
164
165
if __name__ == "__main__":
166
    main()
167