trying to fix

This commit is contained in:
2022-06-29 08:04:24 +03:00
parent 144af6ea0a
commit 25c76bd550
5 changed files with 134 additions and 116 deletions

2
.gitignore vendored
View File

@@ -1,6 +1,6 @@
/tmp/
/audio/*/
/test2.py
/user.db
*.json
*.pyc

12
.idea/discord-bot.iml generated Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="NewModuleRootManager">
<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="sourceFolder" forTests="false" />
</component>
</module>

1
.idea/encodings.xml generated
View File

@@ -3,5 +3,6 @@
<component name="Encoding">
<file url="file://$PROJECT_DIR$/sqlite_python.db" charset="windows-1251" />
<file url="file://$PROJECT_DIR$/test_database.sql" charset="windows-1251" />
<file url="file://$PROJECT_DIR$/user.db" charset="UTF-8" />
</component>
</project>

197
test.py
View File

@@ -4,14 +4,25 @@ import sqlite3
import sys
import threading
from os import walk, path, makedirs, remove, rename, listdir
from typing import List, Union, Any, Dict
import discord
from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, OptionChoice
def determine_prefix(bot, msg):
guild = msg.guild
base = Commands.read_json(guild.id, 'prefix') or DEFAULT_PREFIX # Get bot role
return base
bot_owner = 386629192743256065
DEFAULT_PREFIX = "$" # The prefix you want everyone to have if you don't define your own
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=determine_prefix, guild_subscriptions=True, intents=intents)
inter_client = InteractionClient(bot)
class DB:
@@ -49,8 +60,8 @@ class DB:
DB.work_with_db(sqlite_insert_with_param, data_tuple)
@staticmethod
def add_audio(guildid: int, user: int, audio: str):
sql_update_query = f"""UPDATE "{guildid}" set track = ? where userid = ?"""
def add_audio(guild: int, user: int, audio: str):
sql_update_query = f"""UPDATE "{guild}" set track = ? where userid = ?"""
data_tuple = (audio, user)
DB.work_with_db(sql_update_query, data_tuple)
@@ -72,33 +83,33 @@ class CogsPrepare:
@staticmethod
def cog_list():
cogs_list = []
for filename in listdir('./cogs'):
if filename.endswith('.py'):
cogs_list.append(filename[:-3])
for _filename in listdir('./cogs'):
if _filename.endswith('.py'):
cogs_list.append(_filename[:-3])
return cogs_list
@staticmethod
async def cogs_load():
for filename in CogsPrepare.cog_list():
bot.load_extension(f'cogs.{filename}')
print(f'Load cog {filename}')
for _filename in CogsPrepare.cog_list():
bot.load_extension(f'cogs.{_filename}')
print(f'Load cog {_filename}')
@staticmethod
async def cogs_unload():
for filename in CogsPrepare.cog_list():
bot.unload_extension(f'cogs.{filename}')
print(f'Unload cog {filename}')
for _filename in CogsPrepare.cog_list():
bot.unload_extension(f'cogs.{_filename}')
print(f'Unload cog {_filename}')
@classmethod
@staticmethod
async def work_with_cogs(what_do, cogs):
for filename in cogs:
for _filename in cogs:
if what_do == "load":
bot.load_extension(f'cogs.{filename}')
bot.load_extension(f'cogs.{_filename}')
elif what_do == 'unload':
bot.unload_extension(f'cogs.{filename}')
bot.unload_extension(f'cogs.{_filename}')
elif what_do == 'reload':
bot.reload_extension(f'cogs.{filename}')
logging.info(f'{what_do.capitalize()}ing cog {filename}')
bot.reload_extension(f'cogs.{_filename}')
logging.info(f'{what_do}ing cog {_filename}')
@staticmethod
async def cog_load(ctx, cog):
@@ -116,45 +127,6 @@ class CogsPrepare:
await ctx.send(f'Error: unknown error with {cog}')
threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
DEFAULT_PREFIX = "$" # The prefix you want everyone to have if you don't define your own
if not path.isfile('prefix.json'):
with open('prefix.json', 'w+') as f:
f.write("")
f.close()
def determine_prefix(bot, msg):
guild = msg.guild
base = Commands.read_json(guild.id, 'prefix') or DEFAULT_PREFIX # Get bot role
return base
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=determine_prefix, guild_subscriptions=True, intents=intents)
inter_client = InteractionClient(bot)
for filename in CogsPrepare.cog_list():
try:
bot.load_extension(f'cogs.{filename}')
logging.info(f'Loaded cog {filename}')
except commands.ExtensionNotFound:
logging.error(f"Error: {filename} couldn't be found to load.")
except commands.ExtensionFailed:
logging.error(f'Error: {filename} failed to load properly.')
except commands.ExtensionError:
logging.error(f'Error: unknown error with {filename}')
class Commands:
@staticmethod
async def set_prefix(ctx, prefix: str):
@@ -174,14 +146,13 @@ class Commands:
return files
@staticmethod
async def read_json(guild: int, param):
async def read_json(guild: int, param: str):
parameter = None
try:
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
jsonObject = json.load(fp) # Load the custom prefixes
jsonObject = json.load(fp) # Load the custom prefixes
except TypeError:
jsonObject = {}
print(type(jsonObject))
if guild: # If the guild exists
try:
guild_conf = jsonObject[f"{guild}"]
@@ -195,39 +166,58 @@ class Commands:
return parameter
@staticmethod
async def write_json(guild, param_name, param):
with open('prefix.json', 'r', encoding='utf-8') as fp:
async def write_json(guild: int, param_name: str, param: str or int):
with open('prefix.json', 'r', encoding='utf-8') as _f:
_jsonObject = json.load(_f)
try:
jsonObject: dict = json.load(fp)
except:
jsonObject = {}
print(type(jsonObject))
try:
jsonObject[f"{guild}"][f"{param_name}"] = param
_guild_conf = _jsonObject[f"{guild}"]
except KeyError:
print(jsonObject)
print('--------')
new = {f"{guild}": "{}"}
print(new)
jsonObject.update(new)
try:
json_param = json.load(jsonObject[f"{guild}"])
except KeyError:
json_param = {}
print(type(json_param))
print(param_name)
print(param)
new = {f"{param_name}": f"{param}"}
print(type(json_param))
print(new)
json_param.update(new)
# jsonObject[str(guild)] = json_param
_guild_conf = {}
try:
_param = _guild_conf[f"{param_name}"]
except KeyError:
_param = {}
print(f'json is {_jsonObject}\n type {type(_jsonObject)}'
f' Guild is {guild}\n type {type(_param)}'
f' Param name is {param_name}\n type {type(_param)}'
f' param is {param} type {type(_param)}')
_new_param = {f"{param_name}": f'{param}'}
_new_guild = {f"{guild}": {}}
_jsonObject.update(_new_guild)
_guild_conf = _jsonObject[f"{guild}"]
print(f"Guild conf is: {_guild_conf}")
_param.update(_new_param)
print(f"Param is: {_param}")
_guild_conf.update(_param)
with open("prefix.json", "w") as fl:
json.dump(jsonObject, fl)
fl.close()
with open("prefix.json", "w") as _f:
json.dump(_jsonObject, _f)
_f.close()
threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
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 CogsPrepare.cog_list():
try:
bot.load_extension(f'cogs.{filename}')
logging.info(f'Loaded cog {filename}')
except commands.ExtensionNotFound:
logging.error(f"Error: {filename} couldn't be found to load.")
except commands.ExtensionFailed:
logging.error(f'Error: {filename} failed to load properly.')
except commands.ExtensionError:
logging.error(f'Error: unknown error with {filename}')
@bot.event
async def on_ready():
@@ -315,8 +305,8 @@ async def upload_audio(ctx, user=None):
@bot.command(name="set_prefix")
@commands.has_permissions(administrator=True)
async def command_setprefix(ctx, prefix: str):
await self.Commands.set_prefix(ctx, prefix)
async def command_set_prefix(ctx, prefix: str):
await Commands.set_prefix(ctx, prefix)
@inter_client.slash_command(
@@ -326,33 +316,10 @@ async def command_setprefix(ctx, prefix: str):
Option("prefix", "Specify prefix", OptionType.STRING, required=True),
]
)
async def slash_setprefix(ctx, prefix: str):
async def slash_set_prefix(ctx, prefix: str):
await Commands.set_prefix(ctx, prefix)
# @inter_client.slash_command(
# name="cogs_load",
# description="Load cogs",
# )
# async def slash_cogs_load(ctx):
# if ctx.author.id == bot_owner:
# await CogsPrepare.cogs_load()
# await ctx.reply('Cogs loaded')
# else:
# await ctx.reply('You`re not bot owner')
#
# @inter_client.slash_command(
# name="cogs_unload",
# description="Unload cogs",
# )
# async def slash_cogs_unload(ctx):
# if ctx.author.id == bot_owner:
# await CogsPrepare.cogs_unload()
# await ctx.reply('Cogs unloaded')
# else:
# await ctx.reply('You`re not bot owner')
@inter_client.slash_command(
name="info",
description="Read list of tracks for user",
@@ -429,7 +396,7 @@ async def set_bot_role(ctx, role):
OptionChoice("load", "load"),
OptionChoice("unload", "unload"),
OptionChoice("reload", "reload"),
]
]
),
Option('cog', "Specify cog if need", OptionType.STRING)
]

38
test2.py Normal file
View File

@@ -0,0 +1,38 @@
import json
def write_json(guild: int, param_name: str, param: str or int):
with open('prefix.json', 'r+', encoding='utf-8') as _f:
try:
_jsonObject = json.load(_f)
except json.decoder.JSONDecodeError:
_jsonObject = {}
try:
_guild_conf = _jsonObject[f"{guild}"]
except KeyError:
_guild_conf = {f"{guild}": {}}
print(_jsonObject)
print(_jsonObject)
try:
_param = {f"{param_name}": f"{param}"}
except KeyError:
_param = {f"{param_name}": f"{param}"}
print(_param)
_guild_conf.update(_param)
print(_jsonObject)
_jsonObject.update(_guild_conf)
_guild_conf = _jsonObject[f"{guild}"]
print(_jsonObject)
print(_guild_conf)
print(_param)
with open("prefix.json", "w") as _f:
json.dump(_jsonObject, _f)
_f.close()
write_json(929446191270330452, 'rr', '34')