most commands moved into cogs

This commit is contained in:
2022-07-02 14:28:22 +03:00
parent 19e1d4226b
commit bab5d68a88
6 changed files with 104 additions and 110 deletions

6
.idea/discord-bot.iml generated
View File

@@ -1,11 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<module version="4"> <module version="4">
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
<excludeFolder url="file://$MODULE_DIR$/audio/386629192743256065" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
</content>
<orderEntry type="jdk" jdkName="Python 3.9 (discord-bot)" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3.9 (discord-bot)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>

View File

@@ -1,5 +1,7 @@
import logging import logging
import lib
from os import path, makedirs, rename, remove
from discord.ext import commands from discord.ext import commands
@@ -11,6 +13,51 @@ class Audio(commands.Cog):
async def on_ready(self): async def on_ready(self):
logging.info(f'Cog {__name__.split(".")[1]} is ready!.') logging.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.command(name="upload_audio")
async def upload_audio(self, ctx, user=None):
user = user or ctx.author
if ctx.author.guild_permissions.administrator or user is ctx.author:
if ctx.message.attachments:
from os import error
if not path.isdir(f'tmp/{user.id}'):
try:
makedirs(f'tmp/{user.id}')
except error as _error:
logging.info(f"Failed to create dir", _error)
if not path.isdir(f'audio/{user.id}'):
try:
makedirs(f'audio/{user.id}')
except error as _error:
logging.info(f"Failed to create dir", _error)
for at in ctx.message.attachments:
import mimetypes
await at.save(f'tmp/{user.id}/{at.filename}')
guess = mimetypes.guess_type(f'tmp/{user.id}/{at.filename}')
if guess[0]:
from pymediainfo import MediaInfo
file = f'tmp/{user.id}/{at.filename}'
duration = round(MediaInfo.parse(file).tracks[0].duration / 1000)
if duration > 15:
await ctx.reply(f'Audio duration is {duration}, but max is 15')
remove(f'tmp/{user.id}/{at.filename}')
else:
a = lib.DB.read_db(ctx.guild.id, user.id)
if a is None:
audiolist = f'{user.id}/{at.filename}'
else:
audiolist = lib.DB.read_db(ctx.guild.id, user.id) + ", " + f'{user.id}/{at.filename}'
lib.DB.add_audio(ctx.guild.id, user.id, audiolist)
rename(f'tmp/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}')
else:
await ctx.reply(f'Failed to find MIME type of {at.filename}', ephemeral=True)
remove(f'tmp/{user.id}/{at.filename}')
else:
await ctx.reply("Has no Attachment", ephemeral=True)
else:
await ctx.reply(f'You`re not admin. You can add audio only for your own account', ephemeral=True)
def setup(bot): # an extension must have a setup function def setup(bot): # an extension must have a setup function
bot.add_cog(Audio(bot)) # adding a cog bot.add_cog(Audio(bot)) # adding a cog

View File

@@ -22,6 +22,32 @@ class General(commands.Cog):
logging.info(f'Cog {__name__.split(".")[1]} is ready!.') logging.info(f'Cog {__name__.split(".")[1]} is ready!.')
@commands.Cog.listener()
async def on_guild_join(self, guild):
for g in guild.members:
lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, guild.id)
@commands.Cog.listener()
async def on_member_join(self, member):
lib.DB.fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)
bot_role = lib.Commands.read_json(member.guild.id, 'bot_role') # Get bot role
guest_role = lib.Commands.read_json(member.guild.id, 'guest_role') # Get guest role
if bot_role and guest_role:
if member.bot == 0:
role = discord.utils.get(member.guild.roles, id=guest_role)
else:
role = discord.utils.get(member.guild.roles, id=bot_role)
logging.info(f"Adding to {member} role {role}")
await member.add_roles(role)
@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member):
sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?"""
data_tuple = (after.nick, before.id)
lib.DB.work_with_db(sql_update_query, data_tuple)
@slash_command( @slash_command(
name="info", name="info",
description="Read list of tracks for user", description="Read list of tracks for user",

View File

@@ -21,7 +21,6 @@ class Bot_info(commands.Cog):
description=f"General information on about bot", description=f"General information on about bot",
) )
emb.add_field(name="Bot ping", value=f'Bot ping: {round(self.bot.latency * 1000)}', inline=True) emb.add_field(name="Bot ping", value=f'Bot ping: {round(self.bot.latency * 1000)}', inline=True)
# emb.add_field(name="Roles list", value=f"{roles}", inline=True)
emb.set_footer(text="Information requested by: {}".format(ctx.author.display_name)) emb.set_footer(text="Information requested by: {}".format(ctx.author.display_name))
await ctx.reply(embed=emb, ephemeral=True) await ctx.reply(embed=emb, ephemeral=True)

28
lib.py
View File

@@ -1,7 +1,9 @@
import json import json
import logging import logging
import sqlite3 import sqlite3
from os import walk, listdir from os import walk, listdir, path
DEFAULT_PREFIX = "$" # The prefix you want everyone to have if you don't define your own
class DB: class DB:
@@ -87,6 +89,13 @@ class CogsPrepare:
class Commands: class Commands:
@staticmethod
def chech_json():
if not path.isfile('prefix.json'):
with open('prefix.json', 'w+') as f:
f.write("")
f.close()
@staticmethod @staticmethod
async def set_prefix(ctx, prefix: str): async def set_prefix(ctx, prefix: str):
await Commands.write_json(ctx.guild.id, "prefix", prefix) await Commands.write_json(ctx.guild.id, "prefix", prefix)
@@ -142,3 +151,20 @@ class Commands:
with open('prefix.json', 'w') as _f: with open('prefix.json', 'w') as _f:
json.dump(_json, _f, indent=4) json.dump(_json, _f, indent=4)
_f.close() _f.close()
@staticmethod
def determine_prefix(bot, msg):
guild = msg.guild
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
parameter = DEFAULT_PREFIX
try:
_json = json.load(fp) # Load the custom prefixes
except error:
_json = {}
if guild: # If the guild exists
try:
parameter = _json[f"{guild.id}"]["prefix"] # Read prefix from json if is setted up
except error:
pass
return parameter

106
test.py
View File

@@ -5,48 +5,22 @@ import threading
import discord import discord
import lib import lib
from os import path, makedirs, remove, rename from os import path
from discord.ext import commands from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, OptionChoice from dislash import InteractionClient, Option, OptionType, OptionChoice
DEFAULT_PREFIX = "$" # The prefix you want everyone to have if you don't define your own
bot_owner = 386629192743256065 bot_owner = 386629192743256065
lib.Commands.chech_json()
def determine_prefix(bot, msg):
guild = msg.guild
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
parameter = DEFAULT_PREFIX
try:
_json = json.load(fp) # Load the custom prefixes
except error:
_json = {}
if guild: # If the guild exists
try:
parameter = _json[f"{guild.id}"]["prefix"] # Read prefix from json if is setted up
except error:
pass
return parameter
intents = discord.Intents.default() intents = discord.Intents.default()
intents.members = True intents.members = True
bot = commands.Bot(command_prefix=determine_prefix, guild_subscriptions=True, intents=intents) bot = commands.Bot(command_prefix=lib.Commands.determine_prefix, guild_subscriptions=True, intents=intents)
inter_client = InteractionClient(bot, sync_commands=True) inter_client = InteractionClient(bot, sync_commands=True)
threading.current_thread().name = "main" threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO', logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s') format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
if not path.isfile('prefix.json'):
with open('prefix.json', 'w+') as f:
f.write("")
f.close()
for filename in lib.CogsPrepare.cog_list(): for filename in lib.CogsPrepare.cog_list():
try: try:
bot.load_extension(f'cogs.{filename}') bot.load_extension(f'cogs.{filename}')
@@ -68,80 +42,6 @@ async def on_ready():
logging.info('We have logged in as {0.user}'.format(bot)) logging.info('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_guild_join(guild):
for g in guild.members:
lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, guild.id)
@bot.event
async def on_member_join(member):
lib.DB.fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)
bot_role = lib.Commands.read_json(member.guild.id, 'bot_role') # Get bot role
guest_role = lib.Commands.read_json(member.guild.id, 'guest_role') # Get guest role
if bot_role and guest_role:
if member.bot == 0:
role = discord.utils.get(member.guild.roles, id=guest_role)
else:
role = discord.utils.get(member.guild.roles, id=bot_role)
logging.info(f"Adding to {member} role {role}")
await member.add_roles(role)
@bot.event
async def on_member_update(before: discord.Member, after: discord.Member):
sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?"""
data_tuple = (after.nick, before.id)
lib.DB.work_with_db(sql_update_query, data_tuple)
@bot.command(name="upload_audio")
async def upload_audio(ctx, user=None):
user = user or ctx.author
if ctx.author.guild_permissions.administrator or user is ctx.author:
if ctx.message.attachments:
from os import error
if not path.isdir(f'tmp/{user.id}'):
try:
makedirs(f'tmp/{user.id}')
except error as _error:
logging.info(f"Failed to create dir", _error)
if not path.isdir(f'audio/{user.id}'):
try:
makedirs(f'audio/{user.id}')
except error as _error:
logging.info(f"Failed to create dir", _error)
for at in ctx.message.attachments:
import mimetypes
await at.save(f'tmp/{user.id}/{at.filename}')
guess = mimetypes.guess_type(f'tmp/{user.id}/{at.filename}')
if guess[0]:
from pymediainfo import MediaInfo
file = f'tmp/{user.id}/{at.filename}'
duration = round(MediaInfo.parse(file).tracks[0].duration / 1000)
if duration > 15:
await ctx.reply(f'Audio duration is {duration}, but max is 15', ephemeral=True)
else:
a = lib.DB.read_db(ctx.guild.id, user.id)
if a is None:
audiolist = f'{user.id}/{at.filename}'
else:
audiolist = lib.DB.read_db(ctx.guild.id, user.id) + ", " + f'{user.id}/{at.filename}'
lib.DB.add_audio(ctx.guild.id, user.id, audiolist)
rename(f'tmp/{user.id}/{at.filename}', f'audio/{user.id}/{at.filename}')
else:
await ctx.reply(f'Failed to find MIME type of {at.filename}', ephemeral=True)
remove(f'tmp/{user.id}/{at.filename}')
else:
await ctx.reply("Has no Attachment", ephemeral=True)
else:
await ctx.reply(f'You`re not admin. You can add audio only for your own account', ephemeral=True)
@inter_client.slash_command( @inter_client.slash_command(
name="cog", name="cog",
description="Work with cogs", description="Work with cogs",