Formatted with black

This commit is contained in:
Profitroll 2023-05-04 16:14:23 +02:00
parent 83fe753a15
commit cea97f9bad
5 changed files with 149 additions and 52 deletions

View File

@ -11,20 +11,28 @@ try:
except ImportError: except ImportError:
from typing_extensions import Literal from typing_extensions import Literal
class NotEnoughMoneyError(Exception): class NotEnoughMoneyError(Exception):
"""User does not have enough money to do that""" """User does not have enough money to do that"""
pass pass
class UserNotFoundError(Exception): class UserNotFoundError(Exception):
"""HoloUser could not find user with such an ID in database""" """HoloUser could not find user with such an ID in database"""
def __init__(self, user, user_id): def __init__(self, user, user_id):
self.user = user self.user = user
self.user_id = user_id self.user_id = user_id
super().__init__(f"User of type {type(self.user)} with id {self.user_id} was not found") super().__init__(
f"User of type {type(self.user)} with id {self.user_id} was not found"
)
class HoloUser():
def __init__(self, user: Union[discord.User, discord.Member, discord.member.Member, int]) -> None: class HoloUser:
def __init__(
self, user: Union[discord.User, discord.Member, discord.member.Member, int]
) -> None:
"""Get an object that has a proper binding between Discord ID and database """Get an object that has a proper binding between Discord ID and database
### Args: ### Args:
@ -32,10 +40,10 @@ class HoloUser():
### Raises: ### Raises:
* `UserNotFoundError`: User with such ID does not seem to exist in database * `UserNotFoundError`: User with such ID does not seem to exist in database
""" """
if hasattr(user, "id"): if hasattr(user, "id"):
self.id = user.id # type: ignore self.id = user.id # type: ignore
else: else:
self.id = user self.id = user
@ -64,12 +72,12 @@ class HoloUser():
# ### Args: # ### Args:
# * `amount` (int, optional): Amount of XP points to give. Defaults to 1. # * `amount` (int, optional): Amount of XP points to give. Defaults to 1.
# """ # """
# self.xp += amount # self.xp += amount
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "xp": self.xp } }) # col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "xp": self.xp } })
# def xp_level_up(self) -> None: # def xp_level_up(self) -> None:
# """Add 1 to the current XP level""" # """Add 1 to the current XP level"""
# xp_diff = int(self.xp - self.xp_next) # xp_diff = int(self.xp - self.xp_next)
# xp_next = int(self.xp_next*configGet("multiplier", "leveling")+configGet("addition", "leveling")) # xp_next = int(self.xp_next*configGet("multiplier", "leveling")+configGet("addition", "leveling"))
# self.xp = xp_diff # self.xp = xp_diff
@ -84,7 +92,7 @@ class HoloUser():
# ### Args: # ### Args:
# * `amount` (int): Amount of currency to be set # * `amount` (int): Amount of currency to be set
# """ # """
# self.balance = amount # self.balance = amount
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "balance": self.balance } }) # col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "balance": self.balance } })
@ -93,7 +101,7 @@ class HoloUser():
# ### Args: # ### Args:
# * `amount` (int): Amount to be added # * `amount` (int): Amount to be added
# """ # """
# self.balance_set(self.balance+amount) # self.balance_set(self.balance+amount)
# def balance_take(self, amount: int) -> bool: # def balance_take(self, amount: int) -> bool:
@ -104,7 +112,7 @@ class HoloUser():
# ### Returns: # ### Returns:
# * `bool`: True if successful and False if not # * `bool`: True if successful and False if not
# """ # """
# if self.balance >= amount: # if self.balance >= amount:
# self.balance_set(self.balance-amount) # self.balance_set(self.balance-amount)
# return True # return True
@ -121,7 +129,7 @@ class HoloUser():
# ### Raises: # ### Raises:
# * `NotEnoughMoneyError`: Not enough money to perform this transaction # * `NotEnoughMoneyError`: Not enough money to perform this transaction
# """ # """
# if self.balance >= amount: # if self.balance >= amount:
# if isinstance(destination, int): # if isinstance(destination, int):
# destination = HoloUser(destination) # destination = HoloUser(destination)
@ -135,7 +143,7 @@ class HoloUser():
# ### Returns: # ### Returns:
# * `int`: Amount of money to be earned # * `int`: Amount of money to be earned
# """ # """
# if self.work_xp >= 100: # if self.work_xp >= 100:
# return randint(configGet("min", "work", "level", "4"), configGet("max", "work", "level", "4")) # return randint(configGet("min", "work", "level", "4"), configGet("max", "work", "level", "4"))
# elif self.work_xp >= 50: # elif self.work_xp >= 50:
@ -153,7 +161,7 @@ class HoloUser():
### Returns: ### Returns:
* `int`: Number of warnings * `int`: Number of warnings
""" """
warns = col_warnings.find_one({"user": self.id}) warns = col_warnings.find_one({"user": self.id})
if warns == None: if warns == None:
return 0 return 0
@ -165,12 +173,15 @@ class HoloUser():
### Args: ### Args:
* `count` (int, optional): Count of warnings to be added. Defaults to 1. * `count` (int, optional): Count of warnings to be added. Defaults to 1.
""" """
warns = col_warnings.find_one({"user": self.id}) warns = col_warnings.find_one({"user": self.id})
if warns != None: if warns != None:
col_warnings.update_one(filter={"_id": self.db_id}, update={ "$set": { "warns": warns["warns"]+count } }) col_warnings.update_one(
filter={"_id": self.db_id},
update={"$set": {"warns": warns["warns"] + count}},
)
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}") logWrite(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:
@ -178,7 +189,7 @@ class HoloUser():
# ### Args: # ### Args:
# * `kind` (Literal["work", "daily", "weekly", "monthly", "steal"]): Kind of a cooldown # * `kind` (Literal["work", "daily", "weekly", "monthly", "steal"]): Kind of a cooldown
# """ # """
# self.cooldown[kind] = datetime.now(tz=timezone.utc) # self.cooldown[kind] = datetime.now(tz=timezone.utc)
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "cooldown": self.cooldown } }) # col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "cooldown": self.cooldown } })
@ -188,20 +199,22 @@ class HoloUser():
### Args: ### Args:
* `key` (str): Attribute to be changed * `key` (str): Attribute to be changed
* `value` (Any): Value to set * `value` (Any): Value to set
""" """
if not hasattr(self, key): if not hasattr(self, key):
raise AttributeError() raise AttributeError()
setattr(self, key, value) setattr(self, key, value)
col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { key: value } }, upsert=True) col_users.update_one(
filter={"_id": self.db_id}, update={"$set": {key: value}}, upsert=True
)
logWrite(f"Set attribute {key} of user {self.id} to {value}") logWrite(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:
@ -209,7 +222,7 @@ class HoloUser():
# ### Returns: # ### Returns:
# * `bool`: True if yes and False if no # * `bool`: True if yes and False if no
# """ # """
# if configGet("mode") == "secure": # if configGet("mode") == "secure":
# authorized = col_authorized.find_one({"user": self.id}) # authorized = col_authorized.find_one({"user": self.id})
# if authorized is not None: # if authorized is not None:
@ -217,4 +230,4 @@ class HoloUser():
# else: # else:
# return False # return False
# else: # else:
# return True # return True

View File

@ -6,69 +6,152 @@ from enums.colors import Color
from modules.utils import config_get from modules.utils import config_get
from modules.utils_sync import config_get_sync, guild_name from modules.utils_sync import config_get_sync, guild_name
class CustomChannels(commands.Cog):
class CustomChannels(commands.Cog):
def __init__(self, client): def __init__(self, client):
self.client = client self.client = client
customchannel = SlashCommandGroup("customchannel", "Керування особистим каналом") customchannel = SlashCommandGroup("customchannel", "Керування особистим каналом")
@customchannel.command(name="buy", description="Отримати персональний текстовий канал", guild_ids=[config_get_sync("guild")]) @customchannel.command(
name="buy",
description="Отримати персональний текстовий канал",
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(self, ctx: ApplicationContext, name: str, reactions: bool, threads: bool): async def customchannel_buy_cmd(
self, ctx: ApplicationContext, name: str, reactions: bool, threads: bool
):
holo_user_ctx = HoloUser(ctx.user) holo_user_ctx = HoloUser(ctx.user)
if holo_user_ctx.customchannel == None: if holo_user_ctx.customchannel == None:
await ctx.defer() await ctx.defer()
created_channel = await ctx.user.guild.create_text_channel(name=name, created_channel = await ctx.user.guild.create_text_channel(
name=name,
reason=f"Користувач {guild_name(ctx.user)} купив канал", reason=f"Користувач {guild_name(ctx.user)} купив канал",
category=utils.get(ctx.author.guild.categories, id=await config_get("customchannels", "categories")), category=utils.get(
ctx.author.guild.categories,
id=await config_get("customchannels", "categories"),
),
)
await created_channel.set_permissions(
ctx.user.guild.default_role,
send_messages=False,
add_reactions=reactions,
create_public_threads=threads,
create_private_threads=threads,
)
await created_channel.set_permissions(
ctx.user,
attach_files=True,
manage_messages=True,
send_messages=True,
embed_links=True,
manage_channels=True,
) )
await created_channel.set_permissions(ctx.user.guild.default_role, send_messages=False, add_reactions=reactions, create_public_threads=threads, create_private_threads=threads)
await created_channel.set_permissions(ctx.user, attach_files=True, manage_messages=True, send_messages=True, embed_links=True, manage_channels=True)
holo_user_ctx.set("customchannel", created_channel.id) holo_user_ctx.set("customchannel", created_channel.id)
await ctx.respond(embed=Embed(title="Створено канал", description=f"Вітаємо! Ви створили канал {created_channel.mention}. Для керування ним користуйтесь меню налаштувань каналу а також командою `/customchannel edit`", color=Color.success)) await ctx.respond(
embed=Embed(
title="Створено канал",
description=f"Вітаємо! Ви створили канал {created_channel.mention}. Для керування ним користуйтесь меню налаштувань каналу а також командою `/customchannel edit`",
color=Color.success,
)
)
bots = await config_get("bots") bots = await config_get("bots")
for bot in bots: for bot in bots:
await created_channel.set_permissions(utils.get(ctx.user.guild.roles, id=bots[bot]["role"]), view_channel=False) await created_channel.set_permissions(
utils.get(ctx.user.guild.roles, id=bots[bot]["role"]),
view_channel=False,
)
else: else:
await ctx.defer(ephemeral=True) await ctx.defer(ephemeral=True)
await ctx.respond(embed=Embed(title="Помилка виконання", description=f"У вас вже є особистий канал.\nДля редагування каналу є `/customchannel edit` або просто відкрийте меню керування вашим каналом.", color=Color.fail)) await ctx.respond(
embed=Embed(
title="Помилка виконання",
description=f"У вас вже є особистий канал.\nДля редагування каналу є `/customchannel edit` або просто відкрийте меню керування вашим каналом.",
color=Color.fail,
)
)
@customchannel.command(name="edit", description="Змінити параметри особистого каналу", guild_ids=[config_get_sync("guild")]) @customchannel.command(
name="edit",
description="Змінити параметри особистого каналу",
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_edit_cmd(self, ctx: ApplicationContext, name:str, reactions: bool, threads: bool): async def customchannel_edit_cmd(
self, ctx: ApplicationContext, name: str, reactions: bool, threads: bool
):
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 = utils.get(ctx.guild.channels, id=holo_user_ctx.customchannel)
if custom_channel is None: if custom_channel is None:
await ctx.respond(embed=Embed(title="Канал не знайдено", description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.", color=Color.fail)) await ctx.respond(
embed=Embed(
title="Канал не знайдено",
description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.",
color=Color.fail,
)
)
return return
await custom_channel.edit(name=name) await custom_channel.edit(name=name)
await custom_channel.set_permissions(ctx.user.guild.default_role, send_messages=False, add_reactions=reactions, create_public_threads=threads, create_private_threads=threads) await custom_channel.set_permissions(
await ctx.respond(embed=Embed(title="Канал змінено", description=f"Назва каналу тепер `{name}`, реакції `{reactions}` та дозволено треди `{threads}`", color=Color.fail)) ctx.user.guild.default_role,
send_messages=False,
add_reactions=reactions,
create_public_threads=threads,
create_private_threads=threads,
)
await ctx.respond(
embed=Embed(
title="Канал змінено",
description=f"Назва каналу тепер `{name}`, реакції `{reactions}` та дозволено треди `{threads}`",
color=Color.fail,
)
)
@customchannel.command(name="refund", description="Відібрати канал, знищуючи його, та частково повернути кошти", guild_ids=[config_get_sync("guild")]) @customchannel.command(
name="refund",
description="Відібрати канал, знищуючи його, та частково повернути кошти",
guild_ids=[config_get_sync("guild")],
)
async def customchannel_refund_cmd(self, ctx: ApplicationContext): async def customchannel_refund_cmd(self, ctx: ApplicationContext):
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(ctx.guild.channels, id=holo_user_ctx.customchannel) custom_channel = utils.get(
ctx.guild.channels, id=holo_user_ctx.customchannel
)
if custom_channel is None: if custom_channel is None:
await ctx.respond(embed=Embed(title="Канал не знайдено", description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.", color=Color.fail)) await ctx.respond(
embed=Embed(
title="Канал не знайдено",
description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.",
color=Color.fail,
)
)
holo_user_ctx.set("customchannel", None) holo_user_ctx.set("customchannel", None)
return return
await custom_channel.delete(reason="Повернення коштів") await custom_channel.delete(reason="Повернення коштів")
holo_user_ctx.set("customchannel", None) holo_user_ctx.set("customchannel", None)
await ctx.respond(embed=Embed(title="Канал знищено", description=f"Ви відмовились від каналу.", color=Color.default)) await ctx.respond(
embed=Embed(
title="Канал знищено",
description=f"Ви відмовились від каналу.",
color=Color.default,
)
)
else: else:
await ctx.defer(ephemeral=True) await ctx.defer(ephemeral=True)
await ctx.respond(embed=Embed(title="Помилка виконання", description=f"У вас немає особистого каналу.", color=Color.fail)) await ctx.respond(
embed=Embed(
title="Помилка виконання",
description=f"У вас немає особистого каналу.",
color=Color.fail,
)
)

View File

@ -6,12 +6,12 @@ with open("config.json", "r", encoding="utf-8") as f:
f.close() f.close()
db_client = MongoClient( db_client = MongoClient(
'mongodb://{0}:{1}@{2}:{3}/{4}'.format( "mongodb://{0}:{1}@{2}:{3}/{4}".format(
db_config["user"], db_config["user"],
db_config["password"], db_config["password"],
db_config["host"], db_config["host"],
db_config["port"], db_config["port"],
db_config["name"] db_config["name"],
) )
) )
db = db_client.get_database(name=db_config["name"]) db = db_client.get_database(name=db_config["name"])
@ -27,4 +27,4 @@ col_warnings = db.get_collection("warnings")
# col_checkouts = db.get_collection("checkouts") # col_checkouts = db.get_collection("checkouts")
# col_trackings = db.get_collection("trackings") # col_trackings = db.get_collection("trackings")
# col_authorized = db.get_collection("authorized") # col_authorized = db.get_collection("authorized")
# col_transactions = db.get_collection("transactions") # col_transactions = db.get_collection("transactions")

View File

@ -33,4 +33,4 @@ async def config_set(key: str, value: Any, *path: str) -> None:
string += f'["{key}"] = {value}' string += f'["{key}"] = {value}'
exec(string) exec(string)
await json_write(this_dict, "config.json") await json_write(this_dict, "config.json")
return return

View File

@ -35,8 +35,9 @@ def config_set_sync(key: str, value: Any, *path: str) -> None:
json_write_sync(this_dict, "config.json") json_write_sync(this_dict, "config.json")
return return
def guild_name(member: Member): def guild_name(member: Member):
if member.nick == None: if member.nick == None:
return member.name return member.name
else: else:
return member.nick return member.nick