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/ /tmp/
/audio/*/ /audio/*/
/test2.py
/user.db /user.db
*.json *.json
*.pyc *.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"> <component name="Encoding">
<file url="file://$PROJECT_DIR$/sqlite_python.db" charset="windows-1251" /> <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$/test_database.sql" charset="windows-1251" />
<file url="file://$PROJECT_DIR$/user.db" charset="UTF-8" />
</component> </component>
</project> </project>

189
test.py
View File

@@ -4,14 +4,25 @@ import sqlite3
import sys import sys
import threading import threading
from os import walk, path, makedirs, remove, rename, listdir from os import walk, path, makedirs, remove, rename, listdir
from typing import List, Union, Any, Dict
import discord import discord
from discord.ext import commands from discord.ext import commands
from dislash import InteractionClient, Option, OptionType, OptionChoice 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 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: class DB:
@@ -49,8 +60,8 @@ class DB:
DB.work_with_db(sqlite_insert_with_param, data_tuple) DB.work_with_db(sqlite_insert_with_param, data_tuple)
@staticmethod @staticmethod
def add_audio(guildid: int, user: int, audio: str): def add_audio(guild: int, user: int, audio: str):
sql_update_query = f"""UPDATE "{guildid}" set track = ? where userid = ?""" sql_update_query = f"""UPDATE "{guild}" set track = ? where userid = ?"""
data_tuple = (audio, user) data_tuple = (audio, user)
DB.work_with_db(sql_update_query, data_tuple) DB.work_with_db(sql_update_query, data_tuple)
@@ -72,33 +83,33 @@ class CogsPrepare:
@staticmethod @staticmethod
def cog_list(): def cog_list():
cogs_list = [] cogs_list = []
for filename in listdir('./cogs'): for _filename in listdir('./cogs'):
if filename.endswith('.py'): if _filename.endswith('.py'):
cogs_list.append(filename[:-3]) cogs_list.append(_filename[:-3])
return cogs_list return cogs_list
@staticmethod @staticmethod
async def cogs_load(): async def cogs_load():
for filename in CogsPrepare.cog_list(): for _filename in CogsPrepare.cog_list():
bot.load_extension(f'cogs.{filename}') bot.load_extension(f'cogs.{_filename}')
print(f'Load cog {filename}') print(f'Load cog {_filename}')
@staticmethod @staticmethod
async def cogs_unload(): async def cogs_unload():
for filename in CogsPrepare.cog_list(): for _filename in CogsPrepare.cog_list():
bot.unload_extension(f'cogs.{filename}') bot.unload_extension(f'cogs.{_filename}')
print(f'Unload cog {filename}') print(f'Unload cog {_filename}')
@classmethod @staticmethod
async def work_with_cogs(what_do, cogs): async def work_with_cogs(what_do, cogs):
for filename in cogs: for _filename in cogs:
if what_do == "load": if what_do == "load":
bot.load_extension(f'cogs.{filename}') bot.load_extension(f'cogs.{_filename}')
elif what_do == 'unload': elif what_do == 'unload':
bot.unload_extension(f'cogs.{filename}') bot.unload_extension(f'cogs.{_filename}')
elif what_do == 'reload': elif what_do == 'reload':
bot.reload_extension(f'cogs.{filename}') bot.reload_extension(f'cogs.{_filename}')
logging.info(f'{what_do.capitalize()}ing cog {filename}') logging.info(f'{what_do}ing cog {_filename}')
@staticmethod @staticmethod
async def cog_load(ctx, cog): async def cog_load(ctx, cog):
@@ -116,45 +127,6 @@ class CogsPrepare:
await ctx.send(f'Error: unknown error with {cog}') 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: class Commands:
@staticmethod @staticmethod
async def set_prefix(ctx, prefix: str): async def set_prefix(ctx, prefix: str):
@@ -174,14 +146,13 @@ class Commands:
return files return files
@staticmethod @staticmethod
async def read_json(guild: int, param): async def read_json(guild: int, param: str):
parameter = None parameter = None
try: try:
with open('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON 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: except TypeError:
jsonObject = {} jsonObject = {}
print(type(jsonObject))
if guild: # If the guild exists if guild: # If the guild exists
try: try:
guild_conf = jsonObject[f"{guild}"] guild_conf = jsonObject[f"{guild}"]
@@ -195,39 +166,58 @@ class Commands:
return parameter return parameter
@staticmethod @staticmethod
async def write_json(guild, param_name, param): async def write_json(guild: int, param_name: str, param: str or int):
with open('prefix.json', 'r', encoding='utf-8') as fp: with open('prefix.json', 'r', encoding='utf-8') as _f:
_jsonObject = json.load(_f)
try: try:
jsonObject: dict = json.load(fp) _guild_conf = _jsonObject[f"{guild}"]
except:
jsonObject = {}
print(type(jsonObject))
try:
jsonObject[f"{guild}"][f"{param_name}"] = param
except KeyError: except KeyError:
print(jsonObject) _guild_conf = {}
print('--------')
new = {f"{guild}": "{}"}
print(new)
jsonObject.update(new)
try: try:
json_param = json.load(jsonObject[f"{guild}"]) _param = _guild_conf[f"{param_name}"]
except KeyError: except KeyError:
json_param = {} _param = {}
print(type(json_param)) print(f'json is {_jsonObject}\n type {type(_jsonObject)}'
print(param_name) f' Guild is {guild}\n type {type(_param)}'
print(param) f' Param name is {param_name}\n type {type(_param)}'
new = {f"{param_name}": f"{param}"} f' param is {param} type {type(_param)}')
print(type(json_param)) _new_param = {f"{param_name}": f'{param}'}
print(new) _new_guild = {f"{guild}": {}}
json_param.update(new) _jsonObject.update(_new_guild)
# jsonObject[str(guild)] = json_param _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: with open("prefix.json", "w") as _f:
json.dump(jsonObject, fl) json.dump(_jsonObject, _f)
fl.close() _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 @bot.event
async def on_ready(): async def on_ready():
@@ -315,8 +305,8 @@ async def upload_audio(ctx, user=None):
@bot.command(name="set_prefix") @bot.command(name="set_prefix")
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
async def command_setprefix(ctx, prefix: str): async def command_set_prefix(ctx, prefix: str):
await self.Commands.set_prefix(ctx, prefix) await Commands.set_prefix(ctx, prefix)
@inter_client.slash_command( @inter_client.slash_command(
@@ -326,33 +316,10 @@ async def command_setprefix(ctx, prefix: str):
Option("prefix", "Specify prefix", OptionType.STRING, required=True), 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) 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( @inter_client.slash_command(
name="info", name="info",
description="Read list of tracks for user", description="Read list of tracks for user",

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')