testing cog

This commit is contained in:
2022-06-28 01:37:28 +03:00
parent 7d59b29a37
commit d33ff81770
3 changed files with 49 additions and 43 deletions

1
.gitignore vendored
View File

@@ -11,3 +11,4 @@ gen
/test2.py /test2.py
/user.db /user.db
/*.json /*.json
*.pyc

18
cogs/test.py Normal file
View File

@@ -0,0 +1,18 @@
from discord.ext import commands
class Test_Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot # defining bot as global var in class
@commands.Cog.listener() # this is a decorator for events/listeners
async def on_ready(self):
print('Bot is ready!.')
@commands.command() # this is for making a command
async def ping(self, ctx):
await ctx.send(f'Pong! {round(self.bot.latency * 1000)}')
def setup(bot): # a extension must have a setup function
bot.add_cog(Test_Cog(bot)) # adding a cog

73
test.py
View File

@@ -3,7 +3,7 @@ import logging
import sqlite3 import sqlite3
import sys import sys
import threading import threading
from os import walk, path, makedirs, remove, rename from os import walk, path, makedirs, remove, rename, listdir
from typing import List, Union, Any from typing import List, Union, Any
import discord import discord
@@ -13,7 +13,7 @@ from dislash import InteractionClient, Option, OptionType
class DB: class DB:
@staticmethod @staticmethod
def _prepare_db(guild): def _prepare_db(guild: int):
try: try:
connect = sqlite3.connect('user.db') connect = sqlite3.connect('user.db')
cursor = connect.cursor() cursor = connect.cursor()
@@ -46,23 +46,19 @@ 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, user, audio): def _add_audio(guildid: int, user: int, audio: str):
sql_update_query = f"""UPDATE "{guildid}" set track = ? where userid = ?""" sql_update_query = f"""UPDATE "{guildid}" 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)
@staticmethod @staticmethod
def _read_db(guildid, user): def _read_db(guild: int, user: int):
try: try:
sql_con = sqlite3.connect("user.db") sql_con = sqlite3.connect("user.db")
cursor = sql_con.cursor() cursor = sql_con.cursor()
sql_read = f"""SELECT * FROM "{guildid}" where userid = {user}""" sql_read = f"""SELECT * FROM "{guild}" where userid = {user}"""
cursor.execute(sql_read) cursor.execute(sql_read)
record = cursor.fetchone() record = cursor.fetchone()
# if record[4] is None:
# return "None"
# else:
# return record[4]
return record[4] return record[4]
except sqlite3.Error as error: except sqlite3.Error as error:
@@ -92,47 +88,39 @@ intents.members = True
bot = commands.Bot(command_prefix=determine_prefix, guild_subscriptions=True, intents=intents) bot = commands.Bot(command_prefix=determine_prefix, guild_subscriptions=True, intents=intents)
inter_client = InteractionClient(bot) inter_client = InteractionClient(bot)
for filename in listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
print(f'Load cog {filename[:-3]}')
else:
print(f'Unable to load {filename[:-3]}')
class Commands: class Commands:
@staticmethod
async def set_prefix(ctx, prefix: str): async def set_prefix(ctx, prefix: str):
with open('prefix.json', 'r', encoding='utf-8') as fp: await Commands._write_json(ctx.guild.id, "prefix", prefix)
try:
jsonObject = json.load(fp)
except:
jsonObject = {}
try:
jsonObject[f"{ctx.guild.id}"]["prefix"] = prefix
except KeyError:
guild = jsonObject[f"{ctx.guild.id}"] = {'prefix': ''}
new = {"prefix": prefix}
guild.update(new)
jsonObject[str(ctx.guild.id)] = guild
await ctx.send(f"Prefix set to: `{prefix}`") await ctx.send(f"Prefix set to: `{prefix}`")
with open("prefix.json", "w") as fl: @staticmethod
json.dump(jsonObject, fl) def list_files(_fold: str):
fl.close() fl = []
for filenames in walk(_fold):
def list_files(folder): fl.extend(filenames)
f = []
for filenames in walk(folder):
f.extend(filenames)
break break
f = f[2]
files = {} files = {}
for x in f: for x in fl[2]:
files[x] = x files[x] = x
return files return files
async def _read_json(guild, param): @staticmethod
async def _read_json(guild: int, param):
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:
jsonObject = {} jsonObject = {}
if guild: # If the guild exists if guild: # If the guild exists
@@ -140,30 +128,29 @@ class Commands:
guild_conf = jsonObject[f"{guild}"] guild_conf = jsonObject[f"{guild}"]
try: try:
parameter = guild_conf[f"{param}"] parameter = guild_conf[f"{param}"]
except: except TypeError:
pass pass
except KeyError: except KeyError:
pass pass
fp.close()
return parameter return parameter
@staticmethod
async def _write_json(guild, param_name, param): async def _write_json(guild, param_name, param):
with open('prefix.json', 'r', encoding='utf-8') as fp: with open('prefix.json', 'r', encoding='utf-8') as fp:
try: try:
jsonObject = json.load(fp) jsonObject = json.load(fp)
except: except TypeError:
jsonObject = {} jsonObject = {}
try: try:
jsonObject[f"{guild}"][f"{param_name}"] = param jsonObject[f"{guild}"][f"{param_name}"] = param
except KeyError: except KeyError:
json_param = jsonObject[f"{guild}"] = {f'{param_name}': ''} json_param = jsonObject[f"{guild}"] = {f'{param_name}': ''}
new = {f"{param_name}": param} jsonObject[str(guild)] = json_param.update({f"{param_name}": param})
json_param.update(new)
jsonObject[str(guild)] = json_param
with open("prefix.json", "w") as fl: with open("prefix.json", "w") as fl:
json.dump(jsonObject, fl) json.dump(jsonObject, fl)
fl.close() fl.close()
@bot.event @bot.event
@@ -253,7 +240,7 @@ 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_setprefix(ctx, prefix: str):
await Commands.set_prefix(ctx, prefix) await self.Commands.set_prefix(ctx, prefix)
@inter_client.slash_command( @inter_client.slash_command(