17 Commits

18 changed files with 380 additions and 187 deletions

View File

@@ -5,6 +5,7 @@ import discord
import discord.member import discord.member
from modules.database import col_users, col_warnings from modules.database import col_users, col_warnings
from modules.utils import config_get
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -51,108 +52,10 @@ class HoloUser:
self.db_id = jav_user["_id"] self.db_id = jav_user["_id"]
# self.xp = jav_user["xp"]
# self.xp_next = jav_user["xp_next"]
# self.level = jav_user["level"]
# self.work_xp = jav_user["work_xp"]
# self.balance = jav_user["balance"]
self.customrole = jav_user["customrole"] self.customrole = jav_user["customrole"]
self.customchannel = jav_user["customchannel"] self.customchannel = jav_user["customchannel"]
# self.married = jav_user["married"]
# self.marriage_request = jav_user["marriage_request"]
# self.marriage_request_sent = jav_user["marriage_request_sent"]
# self.cooldown = jav_user["cooldown"]
self.warnings = self.warns() self.warnings = self.warns()
# def xp_add(self, amount: int = 1) -> None:
# """Add some amount of XP points
# ### Args:
# * `amount` (int, optional): Amount of XP points to give. Defaults to 1.
# """
# self.xp += amount
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "xp": self.xp } })
# def xp_level_up(self) -> None:
# """Add 1 to the current XP level"""
# xp_diff = int(self.xp - self.xp_next)
# xp_next = int(self.xp_next*configGet("multiplier", "leveling")+configGet("addition", "leveling"))
# self.xp = xp_diff
# self.xp_next = xp_next
# self.level += 1
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "xp": xp_diff } })
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "xp_next": xp_next } })
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "level": self.level } })
# def balance_set(self, amount: int) -> None:
# """Set the balance to amount
# ### Args:
# * `amount` (int): Amount of currency to be set
# """
# self.balance = amount
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "balance": self.balance } })
# def balance_add(self, amount: int) -> None:
# """Add amount to the balance
# ### Args:
# * `amount` (int): Amount to be added
# """
# self.balance_set(self.balance+amount)
# def balance_take(self, amount: int) -> bool:
# """Take amount from the balance
# ### Args:
# * `amount` (int): Amount to be taken
# ### Returns:
# * `bool`: True if successful and False if not
# """
# if self.balance >= amount:
# self.balance_set(self.balance-amount)
# return True
# else:
# return False
# #raise NotEnoughMoneyError()
# def balance_transfer(self, amount: int, destination: Union[Any, int]) -> None:
# """Transfer money to another user
# ### Args:
# * `amount` (int): Amount to be transferred
# * `destination` (Union[Any, int]): Destination user of the transfer (should have attribute "id" or be id itself if int)
# ### Raises:
# * `NotEnoughMoneyError`: Not enough money to perform this transaction
# """
# if self.balance >= amount:
# if isinstance(destination, int):
# destination = HoloUser(destination)
# self.balance_take(amount)
# destination.balance_add(amount) # type: ignore
# else:
# raise NotEnoughMoneyError()
# def salary_get(self) -> int:
# """Get the salary level depending on work_xp
# ### Returns:
# * `int`: Amount of money to be earned
# """
# if self.work_xp >= 100:
# return randint(configGet("min", "work", "level", "4"), configGet("max", "work", "level", "4"))
# elif self.work_xp >= 50:
# return randint(configGet("min", "work", "level", "3"), configGet("max", "work", "level", "3"))
# elif self.work_xp > 10:
# return randint(configGet("min", "work", "level", "2"), configGet("max", "work", "level", "2"))
# else:
# return randint(configGet("min", "work", "level", "1"), configGet("max", "work", "level", "1"))
# def work_xp_add(self) -> None:
# self.set("work_xp", self.work_xp+1)
def warns(self) -> int: def warns(self) -> int:
"""Get number of warnings user has """Get number of warnings user has
@@ -181,15 +84,6 @@ class HoloUser:
col_warnings.insert_one(document={"user": self.id, "warns": count}) col_warnings.insert_one(document={"user": self.id, "warns": count})
logger.info(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:
# """Set cooldown start of kind now
# ### Args:
# * `kind` (Literal["work", "daily", "weekly", "monthly", "steal"]): Kind of a cooldown
# """
# self.cooldown[kind] = datetime.now(tz=timezone.utc)
# col_users.update_one(filter={"_id": self.db_id}, update={ "$set": { "cooldown": self.cooldown } })
def set(self, key: str, value: Any) -> None: def set(self, key: str, value: Any) -> None:
"""Set attribute data and save it into database """Set attribute data and save it into database
@@ -205,26 +99,46 @@ class HoloUser:
) )
logger.info(f"Set attribute {key} of user {self.id} to {value}") logger.info(f"Set attribute {key} of user {self.id} to {value}")
async def is_moderator(
self, member: Union[discord.User, discord.Member, discord.member.Member]
) -> bool:
"""Check if user is moderator or council member
### Args:
* `member` (Union[discord.User, discord.Member, discord.member.Member]): Member object
### Returns:
`bool`: `True` if member is a moderator or member of council and `False` if not
"""
if isinstance(member, discord.User):
return False
moderator_role = await config_get("moderators", "roles")
council_role = await config_get("council", "roles")
for role in member.roles:
if role.id == moderator_role or role.id == council_role:
return True
return False
async def is_council(
self, member: Union[discord.User, discord.Member, discord.member.Member]
) -> bool:
"""Check if user is a member of council
### Args:
* `member` (Union[discord.User, discord.Member, discord.member.Member]): Member object
### Returns:
`bool`: `True` if member is a member of council and `False` if not
"""
if isinstance(member, discord.User):
return False
council_role = await config_get("council", "roles")
for role in member.roles:
if role.id == council_role:
return True
return False
# 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:
# """Cancel Oauth2 authorization"""
# col_authorized.find_one_and_delete({"user": self.id})
# def is_authorized(self) -> bool:
# """Check if user provided Oauth2 authorization
# ### Returns:
# * `bool`: True if yes and False if no
# """
# if configGet("mode") == "secure":
# authorized = col_authorized.find_one({"user": self.id})
# if authorized is not None:
# return True
# else:
# return False
# else:
# return True

View File

@@ -3,6 +3,7 @@ import logging
from discord import ApplicationContext, Embed, User, option, slash_command from discord import ApplicationContext, Embed, User, option, slash_command
from discord import utils as ds_utils from discord import utils as ds_utils
from discord.ext import commands from discord.ext import commands
from libbot.pycord.classes import PycordBot
from enums.colors import Color from enums.colors import Color
from modules.scheduled import scheduler from modules.scheduled import scheduler
@@ -13,7 +14,7 @@ logger = logging.getLogger(__name__)
class Admin(commands.Cog): class Admin(commands.Cog):
def __init__(self, client): def __init__(self, client: PycordBot):
self.client = client self.client = client
# @slash_command( # @slash_command(
@@ -83,7 +84,7 @@ class Admin(commands.Cog):
# ) # )
# ) # )
# mod_role = ds_utils.get( # mod_role = ds_utils.get(
# ctx.user.guild.roles, id=await config_get("moderator", "roles") # ctx.user.guild.roles, id=await config_get("moderators", "roles")
# ) # )
# admin_chan = ds_utils.get( # admin_chan = ds_utils.get(
# ctx.user.guild.channels, # ctx.user.guild.channels,
@@ -111,9 +112,12 @@ class Admin(commands.Cog):
amount: int, amount: int,
user: User, user: User,
): ):
if ctx.user.id in await config_get("admins"): if ctx.user.id in self.client.owner_ids:
logging.info( logging.info(
f"User {ctx.user.id} removed {amount} message(s) in {ctx.channel.id}" "User %s removed %s message(s) in %s",
ctx.user.id,
amount,
ctx.channel.id,
) )
await ctx.respond( await ctx.respond(
embed=Embed(description="Видаляю..."), ephemeral=True, delete_after=2.0 embed=Embed(description="Видаляю..."), ephemeral=True, delete_after=2.0
@@ -126,7 +130,8 @@ class Admin(commands.Cog):
) )
else: else:
logging.warning( logging.warning(
f"User {guild_name(ctx.user)} tried to use /clear but permission denied" "User %s tried to use /clear but permission denied",
guild_name(ctx.user),
) )
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@@ -136,7 +141,7 @@ class Admin(commands.Cog):
) )
) )
mod_role = ds_utils.get( mod_role = ds_utils.get(
ctx.user.guild.roles, id=await config_get("moderator", "roles") ctx.user.guild.roles, id=await config_get("moderators", "roles")
) )
admin_chan = ds_utils.get( admin_chan = ds_utils.get(
ctx.user.guild.channels, ctx.user.guild.channels,
@@ -158,8 +163,8 @@ class Admin(commands.Cog):
) )
async def reboot_cmd(self, ctx: ApplicationContext): async def reboot_cmd(self, ctx: ApplicationContext):
await ctx.defer(ephemeral=True) await ctx.defer(ephemeral=True)
if ctx.user.id in await config_get("admins"): if ctx.user.id in self.client.owner_ids:
logging.info(f"Calling shutdown initiated by {guild_name(ctx.user)}") logging.info("Calling shutdown initiated by %s", guild_name(ctx.user))
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Вимикаюсь...", title="Вимикаюсь...",
@@ -171,7 +176,8 @@ class Admin(commands.Cog):
exit() exit()
else: else:
logging.warning( logging.warning(
f"User {guild_name(ctx.user)} tried to use /reboot but permission denied" "User %s tried to use /reboot but permission denied",
guild_name(ctx.user),
) )
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@@ -181,7 +187,7 @@ class Admin(commands.Cog):
) )
) )
mod_role = ds_utils.get( mod_role = ds_utils.get(
ctx.user.guild.roles, id=await config_get("moderator", "roles") ctx.user.guild.roles, id=await config_get("moderators", "roles")
) )
admin_chan = ds_utils.get( admin_chan = ds_utils.get(
ctx.user.guild.channels, ctx.user.guild.channels,
@@ -195,3 +201,7 @@ class Admin(commands.Cog):
color=Color.fail, color=Color.fail,
), ),
) )
def setup(client: PycordBot):
client.add_cog(Admin(client))

View File

@@ -2,6 +2,7 @@ import logging
from discord import Cog, Message from discord import Cog, Message
from discord.ext import commands from discord.ext import commands
from libbot.pycord.classes import PycordBot
from modules.database import col_analytics from modules.database import col_analytics
@@ -9,7 +10,7 @@ logger = logging.getLogger(__name__)
class Analytics(commands.Cog): class Analytics(commands.Cog):
def __init__(self, client): def __init__(self, client: PycordBot):
self.client = client self.client = client
@Cog.listener() @Cog.listener()
@@ -19,10 +20,42 @@ class Analytics(commands.Cog):
and (message.author.bot == False) and (message.author.bot == False)
and (message.author.system == False) and (message.author.system == False)
): ):
col_analytics.insert_one( stickers = []
for sticker in message.stickers:
stickers.append(
{ {
"message": message.content, "id": sticker.id,
"user": message.author.id, "name": sticker.name,
"channel": message.channel.id, "format": sticker.format,
"url": sticker.url,
} }
) )
attachments = []
for attachment in message.attachments:
attachments.append(
{
"content_type": attachment.content_type,
"description": attachment.description,
"filename": attachment.filename,
"is_spoiler": attachment.is_spoiler(),
"size": attachment.size,
"url": attachment.url,
"width": attachment.width,
"height": attachment.height,
}
)
col_analytics.insert_one(
{
"user": message.author.id,
"channel": message.channel.id,
"content": message.content,
"stickers": stickers,
"attachments": attachments,
}
)
def setup(client: PycordBot):
client.add_cog(Analytics(client))

View File

@@ -3,6 +3,7 @@ from discord import utils as ds_utils
from discord.abc import GuildChannel from discord.abc import GuildChannel
from discord.commands import SlashCommandGroup from discord.commands import SlashCommandGroup
from discord.ext import commands from discord.ext import commands
from libbot.pycord.classes import PycordBot
from classes.holo_user import HoloUser from classes.holo_user import HoloUser
from enums.colors import Color from enums.colors import Color
@@ -12,7 +13,7 @@ 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: PycordBot):
self.client = client self.client = client
@commands.Cog.listener() @commands.Cog.listener()
@@ -80,7 +81,7 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Помилка виконання", title="Помилка виконання",
description=f"У вас вже є особистий канал.\nДля редагування каналу є `/customchannel edit` або просто відкрийте меню керування вашим каналом.", description="У вас вже є особистий канал.\nДля редагування каналу є `/customchannel edit` або просто відкрийте меню керування вашим каналом.",
color=Color.fail, color=Color.fail,
) )
) )
@@ -105,7 +106,7 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Канал не знайдено", title="Канал не знайдено",
description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.", description="Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.",
color=Color.fail, color=Color.fail,
) )
) )
@@ -146,7 +147,7 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Канал не знайдено", title="Канал не знайдено",
description=f"Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.", description="Канал, вказаний як ваш, не існує. Можливо, його було вручну видалено раніше.",
color=Color.fail, color=Color.fail,
) )
) )
@@ -156,7 +157,7 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Підтвердження не надано", title="Підтвердження не надано",
description=f"Для підтвердження операції додайте до команди параметр `confirm` зі значенням `True`.", description="Для підтвердження операції додайте до команди параметр `confirm` зі значенням `True`.",
color=Color.fail, color=Color.fail,
) )
) )
@@ -166,7 +167,7 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Канал знищено", title="Канал знищено",
description=f"Ви відмовились від каналу та видалили його.", description="Ви відмовились від каналу та видалили його.",
color=Color.default, color=Color.default,
) )
) )
@@ -175,7 +176,11 @@ class CustomChannels(commands.Cog):
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
title="Помилка виконання", title="Помилка виконання",
description=f"У вас немає особистого каналу.", description="У вас немає особистого каналу.",
color=Color.fail, color=Color.fail,
) )
) )
def setup(client: PycordBot):
client.add_cog(CustomChannels(client))

View File

@@ -7,7 +7,9 @@ from discord import ApplicationContext, Embed, File, option
from discord import utils as ds_utils from discord import utils as ds_utils
from discord.commands import SlashCommandGroup from discord.commands import SlashCommandGroup
from discord.ext import commands from discord.ext import commands
from libbot.pycord.classes import PycordBot
from classes.holo_user import HoloUser
from enums.colors import Color from enums.colors import Color
from modules.database import col_users from modules.database import col_users
from modules.utils import config_get from modules.utils import config_get
@@ -17,7 +19,7 @@ logger = logging.getLogger(__name__)
class Data(commands.Cog): class Data(commands.Cog):
def __init__(self, client): def __init__(self, client: PycordBot):
self.client = client self.client = client
data = SlashCommandGroup("data", "Керування даними користувачів") data = SlashCommandGroup("data", "Керування даними користувачів")
@@ -32,9 +34,12 @@ class Data(commands.Cog):
) )
async def data_export_cmd(self, ctx: ApplicationContext, kind: str): async def data_export_cmd(self, ctx: ApplicationContext, kind: str):
await ctx.defer() await ctx.defer()
if ctx.user.id in await config_get("admins"): holo_user = HoloUser(ctx.author)
if (ctx.user.id in self.client.owner_ids) or (
await holo_user.is_council(ctx.author)
):
logging.info( logging.info(
f"Moderator {guild_name(ctx.user)} exported current users list" "Moderator %s exported current users list", guild_name(ctx.user)
) )
makedirs("tmp", exist_ok=True) makedirs("tmp", exist_ok=True)
uuid = str(uuid4()) uuid = str(uuid4())
@@ -59,7 +64,8 @@ class Data(commands.Cog):
) )
else: else:
logging.info( logging.info(
f"User {guild_name(ctx.user)} tried to use /export but permission denied" "User %s tried to use /export but permission denied",
guild_name(ctx.user),
) )
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@@ -69,7 +75,7 @@ class Data(commands.Cog):
) )
) )
mod_role = ds_utils.get( mod_role = ds_utils.get(
ctx.user.guild.roles, id=await config_get("moderator", "roles") ctx.user.guild.roles, id=await config_get("moderators", "roles")
) )
admin_chan = ds_utils.get( admin_chan = ds_utils.get(
ctx.user.guild.channels, ctx.user.guild.channels,
@@ -94,9 +100,13 @@ class Data(commands.Cog):
) )
async def data_migrate_cmd(self, ctx: ApplicationContext, kind: str): async def data_migrate_cmd(self, ctx: ApplicationContext, kind: str):
await ctx.defer() await ctx.defer()
if ctx.user.id in await config_get("admins"): holo_user = HoloUser(ctx.author)
if (ctx.user.id in self.client.owner_ids) or (
await holo_user.is_council(ctx.author)
):
logging.info( logging.info(
f"Moderator {guild_name(ctx.user)} started migration of all members to the database" "Moderator %s started migration of all members to the database",
guild_name(ctx.user),
) )
if kind == "Користувачі": if kind == "Користувачі":
@@ -114,7 +124,7 @@ class Data(commands.Cog):
col_users.insert_one(document=user) col_users.insert_one(document=user)
logging.info( logging.info(
f"Added DB record for user {member.id} during migration" "Added DB record for user %s during migration", member.id
) )
await ctx.respond( await ctx.respond(
@@ -126,7 +136,8 @@ class Data(commands.Cog):
) )
else: else:
logging.info( logging.info(
f"User {guild_name(ctx.user)} tried to use /migrate but permission denied" "User %s tried to use /migrate but permission denied",
guild_name(ctx.user),
) )
await ctx.respond( await ctx.respond(
embed=Embed( embed=Embed(
@@ -136,7 +147,7 @@ class Data(commands.Cog):
) )
) )
mod_role = ds_utils.get( mod_role = ds_utils.get(
ctx.user.guild.roles, id=await config_get("moderator", "roles") ctx.user.guild.roles, id=await config_get("moderators", "roles")
) )
admin_chan = ds_utils.get( admin_chan = ds_utils.get(
ctx.user.guild.channels, ctx.user.guild.channels,
@@ -150,3 +161,7 @@ class Data(commands.Cog):
color=Color.fail, color=Color.fail,
), ),
) )
def setup(client: PycordBot):
client.add_cog(Data(client))

59
cogs/fun.py Normal file
View File

@@ -0,0 +1,59 @@
import logging
from discord import ApplicationContext, Embed, User, option, slash_command
from discord.ext import commands
from libbot.pycord.classes import PycordBot
from WaifuPicsPython import WaifuAsync
from modules.utils import config_get
from modules.utils_sync import config_get_sync, guild_name
logger = logging.getLogger(__name__)
wafiu_pics = WaifuAsync()
class Fun(commands.Cog):
def __init__(self, client: PycordBot):
self.client = client
@slash_command(
name="action",
description="Провести над користувачем РП дію",
guild_ids=[config_get_sync("guild")],
)
@option(
"type",
description="Тип дії, яку хочете провести з користувачем",
choices=config_get_sync("actions").keys(),
)
@option("user", description="Користувач")
async def action_cmd(self, ctx: ApplicationContext, type: str, user: User):
await ctx.defer()
action = await config_get("category", "actions", type)
action_verb = await config_get("action", "actions", type)
image = await wafiu_pics.sfw(action)
logger.info(
"User %s (%s) %s %s (%s) with image %s",
guild_name(ctx.user),
ctx.user.id,
action_verb,
guild_name(user),
user.id,
image,
)
embed = Embed(
description=f"**{guild_name(ctx.user)}** {action_verb} **{guild_name(user)}**",
color=0x2F3136,
)
embed.set_image(url=image)
await ctx.respond(embed=embed)
def setup(client: PycordBot):
client.add_cog(Fun(client))

View File

@@ -1,13 +1,14 @@
from discord import Member, Message from discord import Member, Message
from discord import utils as ds_utils from discord import utils as ds_utils
from discord.ext import commands from discord.ext import commands
from libbot.pycord.classes import PycordBot
from modules.database import col_users from modules.database import col_users
from modules.utils import config_get from modules.utils import config_get
class Logger(commands.Cog): class Logger(commands.Cog):
def __init__(self, client): def __init__(self, client: PycordBot):
self.client = client self.client = client
@commands.Cog.listener() @commands.Cog.listener()
@@ -60,3 +61,7 @@ class Logger(commands.Cog):
user[key] = defaults[key] user[key] = defaults[key]
col_users.insert_one(document=user) col_users.insert_one(document=user)
def setup(client: PycordBot):
client.add_cog(Logger(client))

View File

@@ -1,8 +1,16 @@
{ {
"token": "", "locale": "en",
"owner": 0, "debug": false,
"guild": 0, "guild": 0,
"admins": [], "bot": {
"owners": [
0
],
"debug_guilds": [
0
],
"bot_token": ""
},
"status": { "status": {
"type": "playing", "type": "playing",
"message": "on your nerves" "message": "on your nerves"
@@ -36,10 +44,45 @@
"voice": {} "voice": {}
}, },
"roles": { "roles": {
"moderator": 0 "council": 0,
"moderators": 0
}, },
"bots": {}, "bots": {},
"messages": { "messages": {
"welcome": "Вітаємо {mention} на сервері HoloUA! Будь ласка, ознайомся з правилами серверу на каналі {rules}. Сподіваємося, тобі тут сподобається!" "welcome": "Вітаємо {mention} на сервері HoloUA! Будь ласка, ознайомся з правилами серверу на каналі {rules}. Сподіваємося, тобі тут сподобається!"
},
"actions": {
"Вкусити": {
"category": "bite",
"action": "робить кусь"
},
"Обійняти": {
"category": "hug",
"action": "обіймає"
},
"Поцілувати": {
"category": "kiss",
"action": "цілує"
},
"Лизнути": {
"category": "lick",
"action": "лиже"
},
"Погладити": {
"category": "pat",
"action": "гладить"
},
"Тикнути": {
"category": "poke",
"action": "тикає в"
},
"Помахати": {
"category": "wave",
"action": "махає"
},
"Підморгнути": {
"category": "wink",
"action": "підморгує"
}
} }
} }

9
locale/en.json Normal file
View File

@@ -0,0 +1,9 @@
{
"metadata": {
"flag": "🇬🇧",
"name": "English",
"codes": [
"en"
]
}
}

9
locale/uk.json Normal file
View File

@@ -0,0 +1,9 @@
{
"metadata": {
"flag": "🇺🇦",
"name": "Українська",
"codes": [
"uk"
]
}
}

19
main.py
View File

@@ -2,11 +2,6 @@ import logging
from discord import Activity, ActivityType from discord import Activity, ActivityType
from cogs.admin import Admin
from cogs.analytics import Analytics
from cogs.custom_channels import CustomChannels
from cogs.data import Data
from cogs.logger import Logger
from modules.client import client from modules.client import client
from modules.scheduled import scheduler from modules.scheduled import scheduler
from modules.utils import config_get from modules.utils import config_get
@@ -30,7 +25,7 @@ except ImportError:
@client.event @client.event
async def on_ready(): async def on_ready():
logger.info(f"Logged in as {client.user}") logger.info("Logged in as %s", client.user)
activity_type = await config_get("type", "status") activity_type = await config_get("type", "status")
activity_message = await config_get("message", "status") activity_message = await config_get("message", "status")
@@ -62,19 +57,17 @@ async def on_ready():
else: else:
return return
logger.info(f"Set activity type to {activity_type} with message {activity_message}") logger.info(
"Set activity type to %s with message %s", activity_type, activity_message
)
def main(): def main():
client.add_cog(Admin(client)) client.load_extension("cogs")
client.add_cog(Analytics(client))
client.add_cog(CustomChannels(client))
client.add_cog(Data(client))
client.add_cog(Logger(client))
try: try:
scheduler.start() scheduler.start()
client.run(config_get_sync("token")) client.run(config_get_sync("bot_token", "bot"))
except KeyboardInterrupt: except KeyboardInterrupt:
scheduler.shutdown() scheduler.shutdown()
exit() exit()

View File

@@ -1,5 +1,6 @@
from discord import Intents, Bot from discord import Intents
from libbot.pycord.classes import PycordBot
intents = Intents().all() intents = Intents().all()
intents.members = True intents.members = True
client = Bot(intents=intents) client = PycordBot(intents=intents)

View File

@@ -25,7 +25,3 @@ for collection in ["users", "warnings", "scheduler", "analytics"]:
col_users = db.get_collection("users") col_users = db.get_collection("users")
col_warnings = db.get_collection("warnings") col_warnings = db.get_collection("warnings")
col_analytics = db.get_collection("analytics") col_analytics = db.get_collection("analytics")
# col_checkouts = db.get_collection("checkouts")
# col_trackings = db.get_collection("trackings")
# col_authorized = db.get_collection("authorized")
# col_transactions = db.get_collection("transactions")

View File

@@ -1,6 +1,6 @@
from typing import Any from typing import Any, Union
from discord import Member from discord import Member, User
from ujson import dumps, loads from ujson import dumps, loads
@@ -36,7 +36,9 @@ def config_set_sync(key: str, value: Any, *path: str) -> None:
return return
def guild_name(member: Member): def guild_name(member: Union[Member, User]) -> str:
if isinstance(member, User):
return member.name
if member.nick == None: if member.nick == None:
return member.name return member.name
else: else:

View File

@@ -1,5 +1,8 @@
aiofiles==23.1.0 aiofiles==23.2.1
apscheduler==3.10.1 apscheduler==3.10.4
py-cord[speed]==2.4.1 pymongo~=4.7.3
pymongo==4.3.3 requests~=2.32.3
ujson==5.7.0 ujson~=5.10.0
WaifuPicsPython==0.2.0
--extra-index-url https://git.end-play.xyz/api/packages/profitroll/pypi/simple
libbot[speed,pycord]==3.2.2

54
validation/analytics.json Normal file
View File

@@ -0,0 +1,54 @@
{
"$jsonSchema": {
"required": [
"user",
"channel",
"content",
"stickers",
"attachments"
],
"properties": {
"user": {
"bsonType": "long",
"description": "Discord ID of user"
},
"channel": {
"bsonType": "int",
"description": "Discord ID of a channel"
},
"content": {
"bsonType": ["null", "string"],
"description": "Text of the message"
},
"stickers": {
"bsonType": "array",
"items": {
"bsonType": "object",
"required": [
"id",
"name",
"format",
"url"
],
"properties": {
"id": {
"bsonType": "int"
},
"name": {
"bsonType": "string"
},
"format": {
"bsonType": "array"
},
"user": {
"bsonType": "string"
}
}
}
},
"attachments": {
"bsonType": "array"
}
}
}
}

24
validation/users.json Normal file
View File

@@ -0,0 +1,24 @@
{
"$jsonSchema": {
"required": [
"user",
"customrole",
"customchannel"
],
"properties": {
"user": {
"bsonType": "long",
"description": "Discord ID of user"
},
"customrole": {
"bsonType": ["null", "long"],
"description": "Discord ID of custom role or 'null' if not set"
},
"customchannel": {
"bsonType": ["null", "long"],
"description": "Discord ID of custom channel or 'null' if not set"
}
}
}
}

18
validation/warnings.json Normal file
View File

@@ -0,0 +1,18 @@
{
"$jsonSchema": {
"required": [
"user",
"warns"
],
"properties": {
"user": {
"bsonType": "long",
"description": "Discord ID of user"
},
"warns": {
"bsonType": "int",
"description": "Number of warnings on count"
}
}
}
}