5 Commits

Author SHA1 Message Date
e59b36fcd1 Improved custom channels 2023-05-06 17:09:06 +02:00
6015592df5 Replaced logger 2023-05-06 17:08:52 +02:00
32c7ec7d44 Added logger thats adds users to DB 2023-05-06 17:08:35 +02:00
b3a78816f7 Added new config keys 2023-05-06 17:08:16 +02:00
22a19c27f8 Changed discord.utils import 2023-05-06 15:21:15 +02:00
5 changed files with 105 additions and 23 deletions

View File

@@ -1,4 +1,5 @@
from datetime import datetime, timezone from datetime import datetime, timezone
import logging
from random import randint from random import randint
from typing import Union, Any from typing import Union, Any
import discord import discord
@@ -11,6 +12,8 @@ try:
except ImportError: except ImportError:
from typing_extensions import Literal from typing_extensions import Literal
logger = logging.getLogger(__name__)
class NotEnoughMoneyError(Exception): class NotEnoughMoneyError(Exception):
"""User does not have enough money to do that""" """User does not have enough money to do that"""
@@ -182,7 +185,7 @@ class HoloUser:
) )
else: else:
col_warnings.insert_one(document={"user": self.id, "warns": count}) col_warnings.insert_one(document={"user": self.id, "warns": count})
logWrite(f"User {self.id} was warned {count} times due to: {reason}") logger.info(f"User {self.id} was warned {count} times due to: {reason}")
# def cooldown_go(self, kind: Literal["work", "daily", "weekly", "monthly", "steal"]) -> None: # def cooldown_go(self, kind: Literal["work", "daily", "weekly", "monthly", "steal"]) -> None:
# """Set cooldown start of kind now # """Set cooldown start of kind now
@@ -206,16 +209,16 @@ class HoloUser:
col_users.update_one( col_users.update_one(
filter={"_id": self.db_id}, update={"$set": {key: value}}, upsert=True filter={"_id": self.db_id}, update={"$set": {key: value}}, upsert=True
) )
logWrite(f"Set attribute {key} of user {self.id} to {value}") logger.info(f"Set attribute {key} of user {self.id} to {value}")
def purge(self) -> None: # def purge(self) -> None:
"""Completely remove data from database. Will not remove transactions logs and warnings.""" # """Completely remove data from database. Will not remove transactions logs and warnings."""
col_users.delete_one(filter={"_id": self.db_id}) # col_users.delete_one(filter={"_id": self.db_id})
self.unauthorize() # self.unauthorize()
def unauthorize(self) -> None: # def unauthorize(self) -> None:
"""Cancel Oauth2 authorization""" # """Cancel Oauth2 authorization"""
col_authorized.find_one_and_delete({"user": self.id}) # col_authorized.find_one_and_delete({"user": self.id})
# def is_authorized(self) -> bool: # def is_authorized(self) -> bool:
# """Check if user provided Oauth2 authorization # """Check if user provided Oauth2 authorization

View File

@@ -1,6 +1,8 @@
from discord import ApplicationContext, option, utils, Embed from discord import ApplicationContext, Embed, option
from discord.ext import commands from discord import utils as ds_utils
from discord.commands import SlashCommandGroup from discord.commands import SlashCommandGroup
from discord.ext import commands
from classes.holo_user import HoloUser from classes.holo_user import HoloUser
from enums.colors import Color from enums.colors import Color
from modules.utils import config_get from modules.utils import config_get
@@ -14,14 +16,14 @@ class CustomChannels(commands.Cog):
customchannel = SlashCommandGroup("customchannel", "Керування особистим каналом") customchannel = SlashCommandGroup("customchannel", "Керування особистим каналом")
@customchannel.command( @customchannel.command(
name="buy", name="get",
description="Отримати персональний текстовий канал", description="Отримати персональний текстовий канал",
guild_ids=[config_get_sync("guild")], guild_ids=[config_get_sync("guild")],
) )
@option("name", description="Назва каналу") @option("name", description="Назва каналу")
@option("reactions", description="Дозволити реакції") @option("reactions", description="Дозволити реакції")
@option("threads", description="Дозволити гілки") @option("threads", description="Дозволити гілки")
async def customchannel_buy_cmd( async def customchannel_get_cmd(
self, ctx: ApplicationContext, name: str, reactions: bool, threads: bool self, ctx: ApplicationContext, name: str, reactions: bool, threads: bool
): ):
holo_user_ctx = HoloUser(ctx.user) holo_user_ctx = HoloUser(ctx.user)
@@ -30,8 +32,8 @@ class CustomChannels(commands.Cog):
await ctx.defer() await ctx.defer()
created_channel = await ctx.user.guild.create_text_channel( created_channel = await ctx.user.guild.create_text_channel(
name=name, name=name,
reason=f"Користувач {guild_name(ctx.user)} купив канал", reason=f"Користувач {guild_name(ctx.user)} отримав власний приватний канал",
category=utils.get( category=ds_utils.get(
ctx.author.guild.categories, ctx.author.guild.categories,
id=await config_get("customchannels", "categories"), id=await config_get("customchannels", "categories"),
), ),
@@ -62,7 +64,7 @@ class CustomChannels(commands.Cog):
bots = await config_get("bots") bots = await config_get("bots")
for bot in bots: for bot in bots:
await created_channel.set_permissions( await created_channel.set_permissions(
utils.get(ctx.user.guild.roles, id=bots[bot]["role"]), ds_utils.get(ctx.user.guild.roles, id=bots[bot]["role"]),
view_channel=False, view_channel=False,
) )
else: else:
@@ -88,7 +90,7 @@ class CustomChannels(commands.Cog):
): ):
holo_user_ctx = HoloUser(ctx.user) holo_user_ctx = HoloUser(ctx.user)
custom_channel = utils.get(ctx.guild.channels, id=holo_user_ctx.customchannel) custom_channel = ds_utils.get(ctx.guild.channels, id=holo_user_ctx.customchannel)
if custom_channel is None: if custom_channel is None:
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@@ -115,16 +117,17 @@ class CustomChannels(commands.Cog):
) )
@customchannel.command( @customchannel.command(
name="refund", name="remove",
description="Відібрати канал, знищуючи його, та частково повернути кошти", description="Відібрати канал, знищуючи його, та частково повернути кошти",
guild_ids=[config_get_sync("guild")], guild_ids=[config_get_sync("guild")],
) )
async def customchannel_refund_cmd(self, ctx: ApplicationContext): @option("confirm", description="Підтвердження операції")
async def customchannel_remove_cmd(self, ctx: ApplicationContext, confirm: bool = False):
holo_user_ctx = HoloUser(ctx.user) holo_user_ctx = HoloUser(ctx.user)
if holo_user_ctx.customchannel is not None: if holo_user_ctx.customchannel is not None:
await ctx.defer() await ctx.defer()
custom_channel = utils.get( custom_channel = ds_utils.get(
ctx.guild.channels, id=holo_user_ctx.customchannel ctx.guild.channels, id=holo_user_ctx.customchannel
) )
if custom_channel is None: if custom_channel is None:
@@ -137,12 +140,21 @@ class CustomChannels(commands.Cog):
) )
holo_user_ctx.set("customchannel", None) holo_user_ctx.set("customchannel", None)
return return
await custom_channel.delete(reason="Повернення коштів") if not confirm:
await ctx.respond(
embed=Embed(
title="Підтвердження не надано",
description=f"Для підтвердження операції додайте до команди параметр `confirm` зі значенням `True`.",
color=Color.fail,
)
)
return
await custom_channel.delete(reason="Власник запросив видалення")
holo_user_ctx.set("customchannel", None) holo_user_ctx.set("customchannel", None)
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Канал знищено", title="Канал знищено",
description=f"Ви відмовились від каналу.", description=f"Ви відмовились від каналу та видалили його.",
color=Color.default, color=Color.default,
) )
) )

49
cogs/logger.py Normal file
View File

@@ -0,0 +1,49 @@
from discord import Member, Message
from discord import utils as ds_utils
from discord.ext import commands
from modules.database import col_users
from modules.utils import config_get
class Logger(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message: Message):
if (message.author != self.client.user) and (message.author.bot == False) and (message.author.system == False):
if col_users.find_one({"user": message.author.id}) is None:
user = {}
defaults = await config_get("user", "defaults")
user["user"] = message.author.id
for key in defaults:
user[key] = defaults[key]
col_users.insert_one(document=user)
@commands.Cog.listener()
async def on_member_join(self, member: Member):
welcome_chan = ds_utils.get(self.client.get_guild(await config_get("guild")).channels, id=await config_get("logging", "channels", "text"))
rules_chan = ds_utils.get(self.client.get_guild(await config_get("guild")).channels, id=await config_get("rules", "channels", "text"))
if (member != self.client.user) and (member.bot == False) and (member.system == False):
await welcome_chan.send(content=(await config_get("welcome", "messages")).format(mention=member.mention, rules=rules_chan.mention))
if col_users.find_one({"user": member.id}) is None:
col_users.insert_one(document=user)
user = {}
defaults = await config_get("user", "defaults")
user["user"] = member.id
for key in defaults:
user[key] = defaults[key]

View File

@@ -15,8 +15,24 @@
"size": 512, "size": 512,
"location": "logs" "location": "logs"
}, },
"defaults": {
"user": {
"customrole": null,
"customchannel": null
}
},
"categories": { "categories": {
"customchannels": 0 "customchannels": 0
}, },
"bots": {} "channels": {
"text": {
"rules": 0,
"welcome": 0
},
"voice": {}
},
"bots": {},
"messages": {
"welcome": "Вітаємо {mention} на сервері HoloUA! Будь ласка, ознайомся з правилами серверу на каналі {rules}. Сподіваємося, тобі тут сподобається!"
}
} }

View File

@@ -9,6 +9,7 @@ from modules.utils import config_get
from modules.utils_sync import config_get_sync from modules.utils_sync import config_get_sync
from cogs.custom_channels import CustomChannels from cogs.custom_channels import CustomChannels
from cogs.logger import Logger
logging.basicConfig( logging.basicConfig(
level=logging.INFO, level=logging.INFO,
@@ -36,6 +37,7 @@ async def on_ready():
def main(): def main():
client.add_cog(CustomChannels(client)) client.add_cog(CustomChannels(client))
client.add_cog(Logger(client))
try: try:
scheduler.start() scheduler.start()