Passed
Branch BonHowi (f724c5)
by Bartosz
01:33
created

build.main.MyBot.on_member_remove()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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