[refactor]: Clear some trash

This commit is contained in:
Sweetbread 2023-05-15 17:29:09 +03:00
parent c8bd9d21a5
commit f8de6d54a2
12 changed files with 18 additions and 352 deletions

91
bot.py
View File

@ -33,9 +33,9 @@ import requests
import subprocess import subprocess
import Levenshtein import Levenshtein
import DiscordUtils import DiscordUtils
from cogs.emojis import * from utils.emojis import *
from cogs.checks import * from utils.checks import *
from cogs.translate import * from utils.translate import *
from cogs.music import * from cogs.music import *
TOKEN = getenv('NATSUKO_TOKEN') TOKEN = getenv('NATSUKO_TOKEN')
my_id = 710089471835504672 my_id = 710089471835504672
@ -127,31 +127,13 @@ async def prefixes(bot, message):
commands.when_mentioned_or(prefs[str(message.guild.id)] if not check() else prefs["default"])(bot, message) commands.when_mentioned_or(prefs[str(message.guild.id)] if not check() else prefs["default"])(bot, message)
intents=discord.Intents.all() intents=discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix=prefixes, help_command=None, intents=intents) bot = commands.Bot(command_prefix=prefixes, help_command=None, intents=intents)
# bot = commands.Bot(command_prefix=prefixes, intents=discord.Intents.all())
bot.code_lines = 0
bot.code_size = 0
#code_lines = 0 # num_lines = sum(1 for line in open('bot.py'))
#code_size = 0 # getsize("bot.py")
max_cog_name_len = max([len(cog) for cog in os.listdir('./cogs') if cog.endswith('.py')])
bot.add_check(is_not_black) bot.add_check(is_not_black)
# bot.add_check(is_white)
bot.owner_id = 459823895256498186 bot.owner_id = 459823895256498186
my_roles = []
privat_channels = []
last_DM = bot.owner_id
last_channel = bot.get_channel(745689950460051546)
notification = {}
players = {}
@bot.event @bot.event
async def on_ready(): async def on_ready():
@ -164,21 +146,9 @@ async def on_ready():
for cog in os.listdir('./cogs'): for cog in os.listdir('./cogs'):
if cog.endswith('.py'): if cog.endswith('.py'):
try: logger.info(f"Загрузка {cog}...")
logger.info(f"Загрузка {cog.capitalize()}...")
await bot.load_extension(f'cogs.{cog.replace(".py", "")}') await bot.load_extension(f'cogs.{cog.replace(".py", "")}')
code_lines_ = num_lines = sum(1 for _ in open("cogs/"+cog))
code_size_ = getsize("cogs/"+cog)
bot.code_lines += code_lines_
bot.code_size += code_size_
logger.info(f"> {cog.capitalize()} загружен{' '*(max_cog_name_len-len(cog))}\tСтрок: {code_lines_}\tРазмер: {code_size_}")
except Exception as e:
logger.debug(repr(e))
logger.info(f"{bot.code_lines}\t{bot.code_size}")
db.members.update_one({"id": 459823895256498186}, {"$set": {"access_level": "secret"}}) db.members.update_one({"id": 459823895256498186}, {"$set": {"access_level": "secret"}})
if os.path.isfile('reboot'): if os.path.isfile('reboot'):
@ -481,57 +451,4 @@ async def change_prefix(ctx, prefix):
dump(prefs, f) dump(prefs, f)
@bot.command()
async def wait(ctx, *, params):
events = ['typing', 'message', 'member_update']
params = json.loads(params)
event = params.pop('event')
if event in events:
def check(element):
out = True
for param in params.keys():
if '.' in param:
param_ = param.split('.')
else:
param_ = [param]
for i in param_:
if i in dir(element):
element = getattr(element, i)
else:
out = False
if element != params[param]: out = False
return out
await bot.wait_for(event, check=check)
await ctx.send(ctx.message.author.mention)
if event == "member_update":
def check(before, element):
out = True
for param in params.keys():
if '.' in param:
param_ = param.split('.')
else:
param_ = [param]
for i in param_:
if i in dir(element):
element = getattr(element, i)
else:
out = False
if element != params[param]: out = False
return out
await bot.wait_for(event, check=check)
await ctx.send(ctx.message.author.mention)
@logger.catch
def main():
bot.run(TOKEN) bot.run(TOKEN)
main()

View File

@ -6,7 +6,7 @@ from typing import Optional
from discord.utils import get from discord.utils import get
from cogs.emojis import check_mark, XX from utils.emojis import check_mark, XX
class DM(commands.Cog, name="ЛС"): class DM(commands.Cog, name="ЛС"):

View File

@ -15,7 +15,7 @@ from discord.app_commands import TranslationContextLocation as trans_loc
from datetime import datetime from datetime import datetime
from matplotlib import ticker from matplotlib import ticker
from matplotlib import pyplot as plt from matplotlib import pyplot as plt
from cogs.emojis import chocolate from utils.emojis import chocolate
class Economic(commands.Cog, name="Экономика"): class Economic(commands.Cog, name="Экономика"):
def __init__(self, bot): def __init__(self, bot):

View File

@ -4,7 +4,7 @@ import discord
from discord.ext import commands from discord.ext import commands
from datetime import timedelta from datetime import timedelta
from cogs.translate import * from utils.translate import *
from bot import db from bot import db
@ -152,4 +152,4 @@ class Logs(commands.Cog, name="Логи"):
async def setup(bot): async def setup(bot):
await bot.add_cog(Logs(bot)) ... # await bot.add_cog(Logs(bot))

View File

@ -2,9 +2,9 @@ import discord
from discord.ext import commands from discord.ext import commands
from discord.utils import get from discord.utils import get
from cogs.checks import is_white from utils.checks import is_white
import asyncio import asyncio
from cogs.emojis import check_mark from utils.emojis import check_mark
from bot import db from bot import db

View File

@ -1,3 +1,4 @@
import PIL import PIL
from PIL import Image from PIL import Image
async def setup(bot): ...

View File

@ -1,40 +0,0 @@
import discord
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands, tasks
from os import listdir
from os.path import splitext, join
dir = "Stickers"
class Stickers(commands.Cog, name="Стикеры"):
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["sl"])
@app_commands.guilds(discord.Object(822157545622863902))
async def sticker_list(self, ctx):
if ctx.guild is not None:
color = ctx.guild.me.color
if color == discord.Color.default():
color = discord.Color(0xaaffaa)
else:
color = discord.Color(0xaaffaa)
list_ = listdir(dir)
embed = discord.Embed(title="Стикеры", description="\n".join([f"{i+1}: {list_[i]}" for i in range(len(list_))]), color=color)
await ctx.send(embed=embed)
@app_commands.command(name="sticker", description="Отправляет стикер")
@app_commands.guilds(discord.Object(822157545622863902))
@app_commands.describe(sticker="Стикер")
@app_commands.choices(sticker=[Choice(name=splitext(i)[0], value=i) for i in listdir(dir)])
async def send_sticker(self, inter, sticker: Choice[str]):
with open(join(dir, sticker.value), 'rb') as f:
await inter.response.send_message(file=discord.File(f))
async def setup(bot):
await bot.add_cog(Stickers(bot))

View File

@ -1,212 +0,0 @@
import json
import os
import re
from random import randint, choice
import Levenshtein
import discord
from discord.ext import commands
from discord import app_commands
from discord.app_commands import locale_str as _T
from cogs.checks import is_secret
from bot import db
meow = ['Мяу', '?', ':Р', ':3', '^___^', '(o・ω・o)', '(≧◡≦)']
vase_error = ['По техническим причинам падение вазы невозможно по причинам '
'отсутствия этих самых ваз\n'
'Обратитесь к специализированному сотруднику для пополнения '
'ресурсов. __Спасибо за понимание__',
'Сотрудники Лаборатории Aperture Science обеспокоены частым разрушением '
'важного и дорогого лабораторного оборудования, из-за чего на это '
'был установлен запрет\n'
'Обратитесь к специализированному сотруднику для снятия '
'запрета. __Спасибо за понимание__']
class TalkModule(commands.Cog, name="Общение"):
"""Работа с разговорным модулем кота"""
def __init__(self, bot):
self.bot = bot
self.unknown_phrases = []
if os.path.exists('speak_data.json'):
with open('speak_data.json', 'r') as f:
self.data = json.load(f)
else:
self.data = [[['привет', 'здаров', 'приветушки'], ['Привет', 'Дароу', 'Мяу', ':)']]]
@commands.Cog.listener()
async def on_message(self, message):
if db.guild_settings.find_one({'id': message.guild.id}) is None: return
if message.author.name != 'Котейка' and db.guild_settings.find_one({"id": message.guild.id})['aux']['talk']:
try:
pattern = re.compile(
r'(^|[^а-яА-ЯЁёa-zA-Z]|[,.])((ко(т((ейк)|(ик)|(ан)|([её]нок)|(я[рт]))?|(шак)))([иаыуэя]|(ов)|(ом))?)([^а-яА-ЯЁёa-zA-Z]|$)')
if pattern.search(message.content.lower()):
rand_meow = meow[randint(0, len(meow) - 1)]
if False: pass # rand_meow == '\*Роняет вазу\*':
# try:
# if self.data['vase'] <= 0:
# await message.channel.send(vase_error[randint(0, len(vase_error) - 1)])
# self.data['vase'] = 0
# else:
# await message.channel.send(rand_meow)
# self.data['vase'] -= 1
# except IndexError:
# self.data['vasa'] = 10
else:
sended = False
max_con = 0
right_answer = ''
i = pattern.search(message.content.lower()).group(0)
text = message.content.lower().replace(i, '')
if text.startswith(','):
text = text[1:]
if text.startswith(' '):
text = text[1:]
text = text.replace('<@>', '')
if len(text) >= 3:
for group in self.data:
# print(group)
for known_pharase in group[0]:
# print(known_pharase)
con = Levenshtein.ratio(known_pharase, text)
# print(con)
if con >= 0.65:
if max_con < con:
max_con = con
right_answer = choice(self.data[self.data.index(group)][1])
sended = True
if not sended:
await message.channel.send(choice(meow))
text = message.content.lower().replace(i, '')
if text.startswith(','):
text = text[1:]
if text.startswith(' '):
text = text[1:]
text = text.replace('<@>', '')
if len(text) >= 3:
self.unknown_phrases.append(text)
else:
await message.reply(right_answer)
except Exception as e:
print(repr(e))
@commands.command(brief="Выводит список неизвестных фраз",
help="Если кот найдет сообщение, в котором содержится слово \"кот\" (неважно какого "
"вида/числа/рода) он попытается на него ответить. Если в базе нет нужного ответа, то кот"
"положит сообщение в этот список")
@commands.check(is_secret)
async def up(self, ctx):
if len(self.unknown_phrases) <= 10:
e = discord.Embed(title="Неизвестные фразы:",
description='\n'.join([f"{self.unknown_phrases.index(el) + 1}. {el}"
for el in self.unknown_phrases]))
else:
e = discord.Embed(title="Неизвестные фразы:",
description='\n'.join(
[f"{len(self.unknown_phrases) - 10 + i}. {self.unknown_phrases[-10 + i]}"
for i in range(10)]))
await ctx.send(embed=e)
@commands.command(brief="Вносит фразу в список неизвестних для дальнейшего обучения")
@commands.check(is_secret)
async def down(self, ctx, phrase):
self.unknown_phrases.append(phrase)
@commands.command(brief="Обучение коты разговору с жалкими человеками",
help="На одну неизвестную фразу может приходиться от одного до нескольких ответов.\n"
"Кот будет по одному писать неизвестную фразу и ждать минуту\n"
"Для ввода нескольких ответов напиши `+`, а потом по одной пиши ответы. После ввода всех"
"ответов напиши `stop`\n"
"`cancel` для отмены обучения\n"
"`next` для пропуска и удаления вопроса из списка\n"
"`pass` для пропуска \"на потом\"\n")
@commands.check(is_secret)
async def teach(self, ctx):
t_author = ctx.message.author
t_channel = ctx.message.channel
pharases = tuple(self.unknown_phrases)
def check(m):
return (m.author == t_author) and (m.channel == t_channel)
for phrase in phrases:
await ctx.send(phrase)
try:
answer = await self.bot.wait_for('message', timeout=60.0, check=check)
except:
await ctx.send("Обучение прервано. Сработал таймаут на минуту")
if answer.content.lower() == 'cancel':
break
elif answer.content.lower() == 'next':
del self.unknown_phrases[self.unknown_phrases.index(phrase)]
continue
elif answer.content.lower() == 'pass':
continue
elif answer.content.lower() == '+':
await ctx.send('OK')
id = len(self.data)
self.data.append([[phrase], []])
while 1:
answerInCycle = await self.bot.wait_for('message', timeout=60.0, check=check)
if answerInCycle.content.lower() == 'cancel':
break
elif answerInCycle.content.lower() == 'stop':
del self.unknown_phrases[self.unknown_phrases.index(phrase)]
break
else:
self.data[id][1].append(answerInCycle.content.replace("\'", "\\'"))
with open('speak_data.json', 'w') as f:
json.dump(self.data, f)
await ctx.send('Сохранено')
continue
else:
self.data.append([[phrase], [answer.content]])
with open('speak_data.json', 'w') as f:
json.dump(self.data, f)
await ctx.send('Сохранено')
await ctx.send('Неизвестных фраз нет')
@commands.command(name='del', brief="Удаляет элемент разговорного-БД кота")
@commands.check(is_secret)
async def del_f(self, ctx, q, *, a: int = None):
if a is None:
del self.data[q]
else:
del self.data[q][a]
with open('speak_data.json', 'w') as f:
json.dump(self.data, f)
await ctx.send('Сохранено')
@commands.command(brief="Выводит сайт с базой данных кота")
@commands.check(is_secret)
async def knowledge(self, ctx):
await ctx.send('https://miyakobot.ru')
@app_commands.command()
async def meow(self, inter):
await inter.response.send_message("Meow")
@app_commands.command(name=_T("cats"))
async def cats(self, inter):
await inter.response.send_message(_T("are cutes"))
async def setup(bot):
await bot.add_cog(TalkModule(bot))

View File

@ -1,9 +1,9 @@
import discord import discord
from discord import app_commands from discord import app_commands
from discord.ext import commands from discord.ext import commands
import translators as ts # import translators as ts
#async def setup(bot): async def setup(bot): ...
@bot.tree.context_menu() # @bot.tree.context_menu()
async def translate(inter: discord.Interaction, message: discord.Message): # async def translate(inter: discord.Interaction, message: discord.Message):
await inter.response.send_message(ts.google(message.content, to_language=str(inter.locale)), ephemeral=True) # await inter.response.send_message(ts.google(message.content, to_language=str(inter.locale)), ephemeral=True)