Passed
Push — main ( 8a79dd...88058c )
by Bartosz
02:44 queued 01:26
created

build.main.MyBot.update_ch_commons()   A

Complexity

Conditions 5

Size

Total Lines 16
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 16
rs 9.2333
c 0
b 0
f 0
cc 5
nop 1
1
import inspect
2
import os
3
import logging
4
import json
5
import discord
6
from discord.ext import commands, tasks
7
from discord_slash import SlashCommand
8
from modules.get_settings import get_settings
9
from datetime import datetime
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
    # Init
25
    def __init__(self):
26
        super().__init__(command_prefix="!", intents=intents)
27
        print("[INFO]: Init Bot")
28
        self.guild = get_settings("guild")
29
        self.ch_role_request = get_settings("CH_ROLE_REQUEST")
30
        self.ch_total_members = get_settings("CH_TOTAL_MEMBERS")
31
        self.ch_nightmare_killed = get_settings("CH_NIGHTMARE_KILLED")
32
        self.ch_common = get_settings("CH_COMMON")
33
        self.ch_logs = get_settings("CH_LOGS")
34
        self.ch_discussion_en = get_settings("CH_DISCUSSION_EN")
35
        self.cat_spotting = get_settings("CAT_SPOTTING")
36
        self.update_ch_commons_loop.start()
37
38
        with open('server_files/config.json', 'r', encoding='utf-8-sig') as fp:
39
            # fp.encoding = 'utf-8-sig'
40
            self.config = json.load(fp)
41
42
    # On Client Start
43
    async def on_ready(self):
44
        await MyBot.change_presence(self, activity=discord.Activity(type=discord.ActivityType.playing,
45
                                                                    name="The Witcher: Monster Slayer"))
46
        print("[INFO]: Bot now online")
47
48
    async def update_member_count(self, ctx):
49
        true_member_count = len([m for m in ctx.guild.members if not m.bot])
50
        new_name = f"Total members: {true_member_count}"
51
        channel = self.get_channel(self.ch_total_members)
52
        await discord.VoiceChannel.edit(channel, name=new_name)
53
54
    # On member join
55
    async def on_member_join(self, ctx):
56
        await self.update_member_count(ctx)
57
        print(f"Someone joined")
58
59
    # Manage on message actions
60
    async def on_message(self, ctx):
61
        if ctx.author.id == self.user.id:
62
            return
63
64
        # If not on role-request channel
65
        if ctx.content.startswith("!") and ctx.channel.id != self.ch_role_request:
66
            await ctx.channel.send(
67
                fr"{ctx.author.mention} Please use / instead of ! to use commands on the server!",
68
                delete_after=5.0)
69
            await ctx.delete()
70
71
    # Loop tasks
72
    # Update common spotting channel name
73
    async def update_ch_commons(self):
74
        with open('./server_files/commons.txt') as f:
75
            try:
76
                commons = f.read().splitlines()
77
            except ValueError:
78
                print(ValueError)
79
80
        new_name = f"common-{commons[0]}"
81
        channel = self.get_channel(self.ch_common)
82
        await discord.TextChannel.edit(channel, name=new_name)
83
        print(f"[{self.__class__.__name__}]: Common channel name updated: {new_name}")
84
85
        commons.append(commons.pop(commons.index(commons[0])))
86
        with open('./server_files/commons.txt', 'w') as f:
87
            for item in commons:
88
                f.write("%s\n" % item)
89
90
    @tasks.loop(minutes=60.0)
91
    async def update_ch_commons_loop(self):
92
        if datetime.now().hour == 12:
93
            print("enter")
94
            await self.update_ch_commons()
95
96
    @update_ch_commons_loop.before_loop
97
    async def before_update_ch_commons(self):
98
        await self.wait_until_ready()
99
100
101
def main():
102
    pogmare = MyBot()
103
    print(f"[INFO]: Rate limited: {pogmare.is_ws_ratelimited()}")
104
105
    # Allow slash commands
106
    slash = SlashCommand(pogmare, sync_commands=True, sync_on_cog_reload=False)
107
108
    # Load cogs
109
    for cog in os.listdir("./cogs"):
110
        if cog.endswith("cog.py"):
111
            try:
112
                cog = f"cogs.{cog.replace('.py', '')}"
113
                pogmare.load_extension(cog)
114
            except Exception as e:
115
                print(f"{cog} Could not be loaded")
116
                raise e
117
118
    pogmare.run(get_settings("token"))
119
120
121
if __name__ == "__main__":
122
    main()
123