Skip to content

Commit

Permalink
Merge pull request Just-Some-Bots#1834 from Just-Some-Bots/review
Browse files Browse the repository at this point in the history
1.9.8_4
  • Loading branch information
Jayden Bailey authored Jan 29, 2019
2 parents b068250 + b4fca16 commit bf1d880
Show file tree
Hide file tree
Showing 13 changed files with 214 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ logs/
data/
config/options.ini
config/permissions.ini
config/aliases.json
config/autoplaylist.txt
config/autoplaylist_removed.txt
config/whitelist.txt
Expand Down
5 changes: 5 additions & 0 deletions config/example_aliases.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"play": ["p"],
"skip": ["s"],
"queue": ["q"]
}
3 changes: 3 additions & 0 deletions config/example_options.ini
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ LegacySkip = no
# Leave servers if the owner is not found in them.
LeaveServersWithoutOwner = no

# Use command alias defined in aliases.json.
UseAlias = yes

[Files]
# Path to your i18n file. Do not set this if you do not know what it does.
i18nFile =
3 changes: 2 additions & 1 deletion config/example_permissions.ini
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
; Specify the name of youtube-dl extractors that people will be able to play using the bot. Seperated by spaces.
; This is to allow restriction of playing porn videos through the bot, as these are supported by yt-dl. Leave blank to allow all.
; For a list of possible extractors, see https://github.com/rg3/youtube-dl/tree/master/youtube_dl/extractor
; The generic extractor is used by the bot to query the song when the query text is given via the play command.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Expand Down Expand Up @@ -162,4 +163,4 @@ InstaSkip = no
Remove = no
SkipWhenAbsent = yes
BypassKaraokeMode = no
Extractors = youtube youtube:playlist
Extractors = generic youtube youtube:playlist
107 changes: 107 additions & 0 deletions config/i18n/ru.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
{
"cmd-resetplaylist-response": "Автоплейлист сервера был сброшен.",
"cmd-help-invalid": "Такой команды не существует",
"cmd-help-no-perms": "У вас нет разрешение на использование каких-либо команд. Используйте `{}help all` для того чтобы все-равно получить список всех команд",
"cmd-help-response": "Для получения информации об определенной команде, используйте `{}help [команда]`",
"cmd-help-all": "\nТолько эти команды вы можете использовать, для получения списка всех команд используйте `{}help all`",
"cmd-blacklist-invalid": "Укащан неверный аргумент '{0}', используйте +, -, add или remove",
"cmd-blacklist-added": "{0} пользователей было добавлено в черный список",
"cmd-blacklist-none": "Никто из этих пользователей не находится в черном списке.",
"cmd-blacklist-removed": "{0} пользователей были удалены из черного списка",
"cmd-id-self": "Твой ID - `{0}`",
"cmd-id-other": "ID **{0}** - `{1}`",
"cmd-save-exists": "Эта песня уже есть в автоплейлисте.",
"cmd-save-invalid": "Этот трек недействителен.",
"cmd-save-success": "Добавлено <{0}> в автоплейлист.",
"cmd-joinserver-response": "Нажмите здесь чтобы пригласить меня на свой сервер: \n{}",
"cmd-play-spotify-album-process": "Воспроизводится альбом - `{0}` (`{1}`)",
"cmd-play-spotify-album-queued": "Поставлено в очередь `{0}` с **{1}** песнями.",
"cmd-play-spotify-playlist-process": "Воспроизведение плейлиста `{0}` (`{1}`)",
"cmd-play-spotify-playlist-queued": "Поставлено в очередь `{0}` с **{1}** песнями.",
"cmd-play-spotify-unsupported": "Это не URL от Spotify.",
"cmd-play-spotify-invalid": "Вы указали неверный URL, или же произошла ошибка.",
"cmd-play-spotify-unavailable": "Бот не настроен для воспроизведения музыки со Spotify. Проверьте свои настройки.",
"cmd-play-limit": "Вы достигли лимита на песни, поставленные в очередь ({0})",
"cmd-play-noinfo": "Это видео не может быть воспроизведено. Попробуйте использовать команду {0}stream",
"cmd-play-nodata": "Произошла ошибка при получении информации по данному запросу, youtubedl не дал ответа. Вам нужно будет перезапустить бота, если это повторится снова.",
"cmd-play-playlist-error": "Ошибка при добавлении плейлиста в очередь воспроизведения:\n`{0}`",
"cmd-play-playlist-gathering-1": "Получение информации о плейлисте с {0} песнями{1}",
"cmd-play-playlist-gathering-2": ", ETA: {0} секунд",
"cmd-play-playlist-maxduration": "Треки не были добавлены в очередь, поскольку все треки идут дольше допустимого лимита (%ss)",
"cmd-play-playlist-reply": "**%s** треков добавлено в очередь воспроизведения. Позиция трека в очереди: %s",
"cmd-play-playlist-invalid": "Этот плейлист не может быть воспроизведен.",
"cmd-play-playlist-process": "Воспроизведение {0} песен...",
"cmd-play-playlist-queueerror": "Ошибка при обработке и добавлении в очередь плейлиста {0}",
"cmd-play-playlist-skipped": "\nТакже, текущий трек был пропущен из-за превышения лимита на продолжительность.",
"cmd-play-playlist-reply-secs": "В очередь было добавлено {0} песен для воспроизведения через {1} секунд.",
"cmd-play-song-limit": "Длительность трека превышает лимит ({0} > {1})",
"cmd-play-song-reply": "`%s` было добавлено в очередь воспроизведения. Позиция в очереди: %s",
"cmd-play-next": "Следующая!",
"cmd-play-eta": " - примерное время до воспроизведения: %s",
"cmd-play-badextractor": "У вас нет разрешений для воспроизведения медиа с этого сервиса.",
"cmd-stream-limit": "Вы достигли лимита на песни, поставленные в очередь ({0})",
"cmd-stream-success": "Трансляция.",
"cmd-search-limit": "Вы достигли лимита треков в вашем плейлисте ({0})",
"cmd-search-noquery": "Пожалуйста, укажите ваш поисковой запрос.\n%s",
"cmd-search-noquote": "Пожалуйста, правильно укажите ваш поисковый запрос.",
"cmd-search-searchlimit": "Нельзя искать более %s видео.",
"cmd-search-searching": "Поиск видео...",
"cmd-search-none": "Видео не были найдены.",
"cmd-search-result": "Результат {0}/{1}: {2}",
"cmd-search-accept": "Ладно, сейчас!",
"cmd-search-decline": "Оу :(",
"cmd-np-action-streaming": "Трансляция",
"cmd-np-action-playing": "Воспроизведение",
"cmd-np-reply-author": "Сейчас {action}: **{title}** добавленное **{author}**\nПрогресс: {progress_bar} {progress}\n:point_right: <{url}>",
"cmd-np-reply-noauthor": "Сейчас {action}: **{title}**\nПрогресс: {progress_bar} {progress}\n:point_right: <{url}>",
"cmd-np-none": "В очереди нет песен! Добавьте что-нибудь с помощью {0}play",
"cmd-summon-novc": "Вы не в голосовом канале!",
"cmd-summon-noperms-connect": "Невозможно присоеденится к каналу `{0}`, отсутствует разрешение на подключение.",
"cmd-summon-noperms-speak": "Невозможно присоеденится к каналу `{0}`, нет разрешения на воспроизведение.",
"cmd-summon-reply": "Подключен к `{0.name}`",
"cmd-pause-reply": "Музыка в `{0.name}` была поставлена на паузу",
"cmd-pause-none": "Ничего не воспроизводится.",
"cmd-resume-reply": "Музыка в `{0.name}` продолжила свое воспроизведение",
"cmd-resume-none": "Плеер не на паузе.",
"cmd-shuffle-reply": "Очередь пользователя `{0}` была перемешана.",
"cmd-clear-reply": "Очередь пользователя `{0}` была очищена",
"cmd-remove-none": "Нечего удалять!",
"cmd-remove-reply": "Удален трек `{0}`, добавленный пользователем `{1}`",
"cmd-remove-missing": "В очереди `%s` ничего не найдено",
"cmd-remove-noperms": "У вас нет разрешений для того чтобы убрать этот трек из очереди, убедитесь что вы - тот, кто добавил этот трек в очереди или же вы можете убирать треки других",
"cmd-remove-invalid": "Неверный номер трека. Используйте {}queue для того чтобы получить номера треков в очереди.",
"cmd-remove-reply-author": "Убран трек `{0}`, добавленный `{1}`",
"cmd-remove-reply-noauthor": "Убран трек `{0}`",
"cmd-skip-none": "Невозможно пропустить! Плеер в данный момент не играет!",
"cmd-skip-dl": "Следующий трек (`%s`) загружается, пожалуйста подождите.",
"cmd-skip-force": "Пропущен `{}`.",
"cmd-skip-force-noperms": "У вас нет разрешения на быстрый пропуск.",
"cmd-skip-reply-skipped-1": "Ваша заявка на пропуск трека `{0}` была подтверждена.\nГолосование прошло успешно.{1}",
"cmd-skip-reply-skipped-2": " Следующая песня начинается!",
"cmd-skip-reply-voted-1": "Ваша заявка на пропуск трека `{0}` была подтверждена.\n**{1}** больше {2} нужно для пропуска трека.",
"cmd-skip-reply-voted-2": "пользователь",
"cmd-skip-reply-voted-3": "пользователи",
"cmd-volume-current": "Текущая громкость: `%s%%`",
"cmd-volume-invalid": "`{0}` неверный номер",
"cmd-volume-reply": "Изменена громкость - с **%d** до **%d**",
"cmd-volume-unreasonable-relative": "Невозможно изменить громкость: {}{:+} -> {}%. Укажите значение между {} и {:+}.",
"cmd-volume-unreasonable-absolute": "Невозможно изменить громкость: {}%. Укажите значение между 1 и 100.",
"cmd-option-autoplaylist-enabled": "Автоплейлист уже включен!",
"cmd-option-autoplaylist-disabled": "Автоплейлист уже выключен!",
"cmd-option-autoplaylist-none": "В файле autoplaylist отсутствуют треки.",
"cmd-option-invalid-value": "Предоставленное значение неверно.",
"cmd-option-invalid-param": "Предоставленные параметры неверны.",
"cmd-queue-more": "\n... и еще %s",
"cmd-queue-none": "В очереди нет песен! Добавьте что-нибудь с помощью {0}play",
"cmd-queue-playing-author": "Сейчас играет: `{0}` добавленное `{1}` {2}\n",
"cmd-queue-playing-noauthor": "Сейчас играет: `{0}` {1}\n",
"cmd-queue-entry-author": "{0} -- `{1}` от `{2}`",
"cmd-queue-entry-noauthor": "{0} -- `{1}`",
"cmd-clean-invalid": "Неверный параметр. Пожалуйста, укажите количество сообщений для поиска.",
"cmd-clean-reply": "Очищено {0} сообщений.",
"playlists-noperms": "Вы не можете запрашивать воспроизведение плейлистов",
"playlists-big": "В плейлисте слишком много треков ({0} > {1})",
"playlists-limit": "Треки из плейлиста + треки из вашей очереди достигли максимально доступного лимита ({0} + {1} > {2})",
"karaoke-enabled": "Режим караоке включен, попробуйте сделать это еще раз, когда он будет выключен!",
"left-no-owner-guilds": "Осталось `{}` из-за того что владелец бота не был найден."
}
2 changes: 1 addition & 1 deletion dockerentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
update = True

if update:
subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'])
subprocess.run([sys.executable, '-m', 'pip', 'install', '-U', '-r', 'requirements.txt'])

subprocess.run([sys.executable, 'run.py'])
61 changes: 61 additions & 0 deletions musicbot/aliases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import logging
import shutil
import json
from pathlib import Path

from .exceptions import HelpfulError

log = logging.getLogger(__name__)


class Aliases:
def __init__(self, aliases_file):
self.aliases_file = Path(aliases_file)
self.aliases_seed = AliasesDefault.aliases_seed
self.aliases = AliasesDefault.aliases

# find aliases file
if not self.aliases_file.is_file():
example_aliases = Path('config/example_aliases.json')
if example_aliases.is_file():
shutil.copy(str(example_aliases), str(self.aliases_file))
log.warning('Aliases file not found, copying example_aliases.json')
else:
raise HelpfulError(
"Your aliases files are missing. Neither aliases.json nor example_aliases.json were found.",
"Grab the files back from the archive or remake them yourself and copy paste the content "
"from the repo. Stop removing important files!"
)

# parse json
with self.aliases_file.open() as f:
try:
self.aliases_seed = json.load(f)
except:
raise HelpfulError(
"Failed to parse aliases file.",
"Ensure your {} is a valid json file and restart the bot.".format(str(self.aliases_file))
)

# construct
for cmd, aliases in self.aliases_seed.items():
if not isinstance(cmd, str) or not isinstance(aliases, list):
raise HelpfulError(
"Failed to parse aliases file.",
"See documents and config {} properly!".format(str(self.aliases_file))
)
self.aliases.update({alias.lower(): cmd.lower() for alias in aliases})

def get(self, arg):
"""
Return cmd name (string) that given arg points.
If arg is not registered as alias, empty string will be returned.
supposed to be called from bot.on_message
"""
ret = self.aliases.get(arg)
return ret if ret else ''

class AliasesDefault:
aliases_file = 'config/aliases.json'
aliases_seed = {}
aliases = {}
30 changes: 24 additions & 6 deletions musicbot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from .opus_loader import load_opus_lib
from .config import Config, ConfigDefaults
from .permissions import Permissions, PermissionsDefaults
from .aliases import Aliases, AliasesDefault
from .constructs import SkipState, Response
from .utils import load_file, write_file, fixg, ftimedelta, _func_, _get_variable
from .spotify import Spotify
Expand All @@ -48,7 +49,7 @@


class MusicBot(discord.Client):
def __init__(self, config_file=None, perms_file=None):
def __init__(self, config_file=None, perms_file=None, aliases_file=None):
try:
sys.stdout.write("\x1b]2;MusicBot {}\x07".format(BOTVERSION))
except:
Expand All @@ -62,6 +63,9 @@ def __init__(self, config_file=None, perms_file=None):
if perms_file is None:
perms_file = PermissionsDefaults.perms_file

if aliases_file is None:
aliases_file = AliasesDefault.aliases_file

self.players = {}
self.exit_signal = None
self.init_ok = False
Expand All @@ -75,6 +79,9 @@ def __init__(self, config_file=None, perms_file=None):
self.permissions = Permissions(perms_file, grant_all=[self.config.owner_id])
self.str = Json(self.config.i18n_file)

if self.config.usealias:
self.aliases = Aliases(aliases_file)

self.blacklist = set(load_file(self.config.blacklist_file))
self.autoplaylist = load_file(self.config.auto_playlist_file)

Expand Down Expand Up @@ -739,7 +746,7 @@ async def _scheck_ensure_env(self):
pathlib.Path('data/%s/' % guild.id).mkdir(exist_ok=True)

with open('data/server_names.txt', 'w', encoding='utf8') as f:
for guilds in sorted(self.guilds, key=lambda s:int(s.id)):
for guild in sorted(self.guilds, key=lambda s:int(s.id)):
f.write('{:<22} {}\n'.format(guild.id, guild.name))

if not self.config.save_videos and os.path.isdir(AUDIO_CACHE_PATH):
Expand Down Expand Up @@ -2167,7 +2174,7 @@ async def cmd_option(self, player, option, value):
else:
is_generic = [o for o in generic if o == option] # check if it is a generic bool option
if is_generic and (value in bool_y or value in bool_n):
name = is_generic[0]
name = is_generic [0]
log.debug('Setting attribute {0}'.format(name))
setattr(self.config, name, True if value in bool_y else False) # this is scary but should work
attr = getattr(self.config, name)
Expand Down Expand Up @@ -2607,11 +2614,22 @@ async def on_message(self, message):
command, *args = message_content.split(' ') # Uh, doesn't this break prefixes with spaces in them (it doesn't, config parser already breaks them)
command = command[len(self.config.command_prefix):].lower().strip()

args = ' '.join(args).lstrip(' ').split(' ')
# [] produce [''] which is not what we want (it break things)
if args:
args = ' '.join(args).lstrip(' ').split(' ')
else:
args = []

handler = getattr(self, 'cmd_' + command, None)
if not handler:
return
# alias handler
if self.config.usealias:
command = self.aliases.get(command)
handler = getattr(self, 'cmd_' + command, None)
if not handler:
return
else:
return

if isinstance(message.channel, discord.abc.PrivateChannel):
if not (message.author.id == self.config.owner_id and command == 'joinserver'):
Expand Down Expand Up @@ -2838,7 +2856,7 @@ async def on_voice_state_update(self, member, before, after):
self.server_specific_data[player.voice_client.guild]['auto_paused'] = False
player.resume()
elif player.voice_client.channel == before.channel and player.voice_client.channel != after.channel:
if len(player.voice_client.channel.members) == 0:
if len(player.voice_client.channel.members) == 1:
if not auto_paused and player.is_playing:
log.info(autopause_msg.format(
state = "Pausing",
Expand Down
Loading

0 comments on commit bf1d880

Please sign in to comment.