some refractor

This commit is contained in:
2022-08-29 00:38:13 +03:00
parent caa8d6b20e
commit 4a33b35283
9 changed files with 87 additions and 89 deletions

2
.gitignore vendored
View File

@@ -5,4 +5,4 @@
*.json *.json
*.pyc *.pyc
/.run/ /.run/
!/.env /.env

View File

@@ -1,3 +1,16 @@
__version__ = '1.0.0' __version__ = '1.0.1'
__title__ = "Pisya bot" __title__ = "Pisya_bot"
__author__ = "beaconborn" __author__ = "beaconborn"
from typing import NamedTuple, Literal
class VersionInfo(NamedTuple):
major: int
minor: int
micro: int
releaselevel: Literal["alpha", "beta", "candidate", "final"]
serial: int
version_info: VersionInfo = VersionInfo(major=1, minor=0, micro=1, releaselevel="alpha", serial=0)

22
__main__.py Normal file
View File

@@ -0,0 +1,22 @@
import platform
import sys
from __init__ import version_info
import pkg_resources
def show_version():
entries = []
entries.append(
"- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info)
)
entries.append("- Pisya_bot v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info))
if pkg := pkg_resources.get_distribution("disnake"):
entries.append(f" - disnake pkg_resources: v{pkg.version}")
uname = platform.uname()
entries.append("- system info: {0.system} {0.release} {0.version}".format(uname))
print("\n".join(entries))
show_version()

View File

@@ -1,13 +1,13 @@
#!/usr/bin/env python3
import asyncio import asyncio
import logging import logging
import os import os
import sys import sys
import pisya_bot
import disnake import disnake
from disnake import OptionChoice, OptionType, Option from disnake import OptionChoice, OptionType, Option
from disnake.ext import commands from disnake.ext import commands
from dotenv import load_dotenv from dotenv import load_dotenv
from __init__ import version_info
from lib.CogsPrepare import work_with_cogs from lib.CogsPrepare import work_with_cogs
from lib.Comands import determine_prefix, check_conf from lib.Comands import determine_prefix, check_conf
@@ -35,9 +35,13 @@ asyncio.run(work_with_cogs('load', bot))
@bot.event @bot.event
async def on_ready(): async def on_ready():
slash_commands = [r.name for r in bot.slash_commands]
commands = [r.name for r in bot.commands]
logging.info(f'Bot started') logging.info(f'Bot started')
logging.info('We have logged in as {0.user}'.format(bot)) logging.info('We have logged in as {0.user}'.format(bot))
logging.info(f'{pisya_bot.__version__}') logging.info('Version of bot is - v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
logging.info(f'list of all slash commmmands: \n{slash_commands}')
logging.info(f'list of all commmmands: \n{commands}')
@bot.slash_command( @bot.slash_command(

View File

@@ -130,7 +130,7 @@ class Admin(commands.Cog, name='Admin'):
await inter.response.send_message("You don`t have permissions", ephemeral=True) await inter.response.send_message("You don`t have permissions", ephemeral=True)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.command( @commands.slash_command(
name="set_time", name="set_time",
description="Read list of tracks for user", description="Read list of tracks for user",
options=[ options=[
@@ -142,16 +142,16 @@ class Admin(commands.Cog, name='Admin'):
await inter.response.send_message(f"Change max audio duration to {seconds} sec", ephemeral=True) await inter.response.send_message(f"Change max audio duration to {seconds} sec", ephemeral=True)
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.command( @commands.slash_command(
name="set_bot_channel", name="set_bot_channel",
description="Set channel whitch itterate with bot", description="Set channel whitch itterate with bot",
options=[ options=[
Option("channel", "specify channel", OptionType.channel, required=True), Option("channel", "specify channel", OptionType.channel, required=True),
] ]
) )
async def set_time(self, inter, _channel: commands.Range[5, 30]): async def set_bot_channel(self, inter, channel):
await write_json(inter.guild.id, "channel", _channel) await write_json(inter.guild.id, "channel", channel.id)
await inter.response.send_message(f"Channet setted up to{_channel} sec", ephemeral=True) await inter.response.send_message(f"Channel setted up to {channel.mention}", ephemeral=True)
def setup(bot): # an extension must have a setup function def setup(bot): # an extension must have a setup function

View File

@@ -1,12 +1,15 @@
import logging import logging
import random import random
from os import path, makedirs, rename, remove from os import path, makedirs, rename, remove
from typing import Optional
import disnake
from disnake import Option, OptionType
from disnake.ext import commands from disnake.ext import commands
from lib.Comands import determine_time from lib.Comands import determine_time
from lib.DB import read_db, check_exist_audio, add_audio from lib.DB import read_db, check_exist_audio, add_audio
from lib.Player import play_audio from lib.Player import play_audio, get_audio_list
# todo: write chose audio from list by slash command # todo: write chose audio from list by slash command
@@ -54,6 +57,18 @@ class Audio(commands.Cog):
else: else:
logging.info(f'Skip playing by any else') logging.info(f'Skip playing by any else')
@commands.slash_command(name="play_audio",
description="Set channel whitch itterate with bot",
options=[
Option("audio", "select audio", OptionType.string, required=True),
]
)
async def play_audio(self,
integration: disnake.ApplicationCommandInteraction,
audio: Optional[str]
) -> None:
await get_audio_list(integration, audio)
@commands.command(name="upload_audio") @commands.command(name="upload_audio")
async def upload_audio(self, ctx, user=None): async def upload_audio(self, ctx, user=None):
user = user or ctx.author user = user or ctx.author

View File

@@ -1,5 +1,9 @@
import asyncio
import json import json
import os import os
from typing import Union
import disnake
""" """
Some prepare for commands Some prepare for commands
@@ -104,3 +108,9 @@ def determine_time(msg):
except: except:
pass pass
return parameter return parameter
def maybe_defer(inter: disnake.Interaction, *, delay: Union[float, int] = 2.0, **options) -> asyncio.Task:
"""Defer an interaction if it has not been responded to after ``delay`` seconds."""
loop = inter.bot.loop
if delay <= 0:
return loop.create_task(inter.response.defer(**options))

View File

@@ -1,7 +1,10 @@
import logging import logging
from asyncio import sleep from asyncio import sleep
from typing import Union, Optional
import disnake
from disnake import FFmpegPCMAudio from disnake import FFmpegPCMAudio
from disnake.ext import commands
async def play_audio(audio, bot, vc): async def play_audio(audio, bot, vc):
@@ -16,3 +19,11 @@ async def play_audio(audio, bot, vc):
await sleep(0.5) await sleep(0.5)
await sleep(1) await sleep(1)
await vp.disconnect() await vp.disconnect()
async def get_audio_list(inter: Union[disnake.ApplicationCommandInteraction, commands.Context],
search: Optional[str],
return_embed: bool = False,
) -> None:
await list_files()

77
main.py
View File

@@ -1,77 +0,0 @@
import random
import sys
import threading
import logging
import disnake
from asyncio import sleep
from os import walk
from disnake import FFmpegPCMAudio
from disnake.ext import commands
threading.current_thread().name = "main"
logging.basicConfig(stream=sys.stdout, filemode='w', level='INFO',
format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
intents = disnake.Intents(members=True)
bot = commands.Bot(command_prefix='$', guild_subscriptions=True, intents=intents)
f = []
for filenames in walk('audio'):
f.extend(filenames)
break
f = f[2]
@bot.event
async def on_voice_state_update(member, before, after):
# channel = bot.get_channel(783729824896122930)
_role = 929729495370461205
_memb = 375664768087752714
_bot_id = 946819004314570852
role = disnake.utils.find(lambda r: r.name == 'тарковчане', member.roles)
if before.channel is None and role in member.roles:
track = random.randint(0, len(f) - 1)
audio_source = FFmpegPCMAudio(f'audio/{f[track]}')
logging.error(f'{track}\t\t{f[track]}')
if not bot.voice_clients:
await sleep(1)
_channel = after.channel
vc = await after.channel.connect()
if not vc.is_playing():
vc.play(audio_source, after=None)
while vc.is_playing():
await sleep(0.5)
await sleep(1)
await vc.disconnect()
if before.channel is None and member.id == _memb:
track = random.randint(0, len(f) - 1)
audio_source = FFmpegPCMAudio(f'audio/{_memb}/bear2_enemy_scav3.wav')
logging.error(f'{track}\t\t\t{f[track]}')
if not bot.voice_clients:
await sleep(1)
_channel = after.channel
vc = await after.channel.connect()
if not vc.is_playing():
vc.play(audio_source, after=None)
while vc.is_playing():
await sleep(0.5)
await sleep(1)
await vc.disconnect()
@bot.event
async def on_member_join(member):
if member.bot == 0:
role = disnake.utils.get(member.guild.roles, id=734358428939452486)
else:
role = disnake.utils.get(member.guild.roles, id=734358434945826858)
logging.info(f"Adding to {member} role {role}")
await member.add_roles(role)
@bot.event
async def on_ready():
logging.info(f'Bot started')
bot.run('OTQ2ODE5MDA0MzE0NTcwODUy.YhkP6Q.dhFqi2MJMrxzHt5FtjK5Cl-5BI8')