-
Notifications
You must be signed in to change notification settings - Fork 0
Custom Command
커스텀 커맨드는 기존의 명령어를 자신이 원하는 명령어로 바꿀 수 있는 기능을 제공합니다. 이 문서에서는 사용자가 명령어를 바꾸기 위해서 어떻게 해야 하는지, 우리가 만든 코드가 어떻게 작동하는지에 대해 기술되어 있습니다. 여기를 보시면 기존 명령어에 대한 설명이 나와있습니다.
config
폴더에 custom_command.txt
에 명령어들이 적혀 있습니다. 이 중 자신이 변경하기 원하는 커맨드를 정하고 변경하기 위한 명령어를 그 옆에 입력합니다.
영어로 사용하기 불편한 유저들이나 자신이 원하는 커맨드를 사용하고 싶은 유저들을 위해 먼저 팀에서 예시로 커스텀 커맨드 목록을 작성해보았습니다.
custom_command.txt
- cmd_help=도움
- cmd_blacklist=블랙리스트
- cmd_save=저장
- cmd_play=플레이
- cmd_stream=스트림
- cmd_search=검색
- cmd_summon=소환
- cmd_pause=일시정지
- cmd_resume=재생
- cmd_shuffle=셔플
- cmd_remove=제거
- cmd_skip=스킵
- cmd_volume=볼륨
- cmd_option=옵션
- cmd_queue=재생목록
기존의 뮤직봇을 실행할때와 똑같이 run.bat
또는 run.sh
를 실행합니다. 그렇면 해당 스크립트 파일이 custom.py
를 실행시킨 후 run.py
를 실행하게 됩니다. 그러면 뮤직 봇이 실행됩니다. 커스텀된 명령어를 가지고요!
상세한 코드 설명이 궁금하신 분들은 아래 항목을 읽어 주세요.
모든 코드는 custom.py
파일에서 작성합니다. 작성된 커스텀 명령어 파일인 custom_command.txt
를 먼저 불러읽어야 한다. 이 때 error 체크를 위한 코드가 필요한 데 이것이 에러 핸들링입니다. 필요한 모듈은 os
, fileinput
, sys
등이며, 이는 뮤직봇 프로젝트의 기본 모듈이기도 합니다.
import os
import fileinput
import sys
#file read error handler
def filecheck(filename):
if filename == ‘custom_command.txt’:
filepath = ‘../config/‘
else:
filepath = ‘’
if not os.path.isfile(filepath + filename):
print('Cannot find file',filename)
exit(1)
에러가 없다면 정상적으로 작성된 커스텀 명령어 txt파일을 읽어들입니다.
#configparser cannot read international characters. code write required
def readcommand(config_file):
filecheck('custom_command.txt')
f_commands = open('../config/custom_command.txt',encoding='UTF8')
lines = f_commands.readlines()
commands = {}
for i in lines:
if '=' in i:
item = i.split('=')
#delete space, 'feff' exception, delete '\n'
commands[item[0].replace(' ','').replace('\ufeff','')] = 'cmd_' + item[1].replace(' ','').replace('\n','')
f_commands.close()
return commands
#erase contents and write string in r+ file
def clearwrite(file,string):
file.seek(0)
file.truncate(0)
file.write(string)
코드 변경 과정에서 일어날 수 있는 코드 손상에 대비하기 위해 백업 파일을 생성합니다. 먼저 마크되었는지 확인하고 `bot.py가 수정되었다면 백업으로부터 복원하고 아니라면 백업파일을 생성합니다.
#check if makred
filecheck('bot.py')
f_botpy = open('bot.py','r+',encoding='UTF8')
#if modified, restore back-up
if "#custom command" in f_botpy.readline():
filecheck('bot.back')
f_backup = open('bot.back', 'r', encoding='UTF8')
clearwrite(f_botpy,f_backup.read())
# if not modified, make back-up
else:
f_backup = open('bot.back', 'w', encoding='UTF8')
f_backup.write(f_botpy.read())
f_botpy.close()
f_backup.close()
bot.py
를 수정하고 마크하여 최종적으로 사용자가 정한 커스텀 명령어가 원래의 명령어처럼 수행되게 합니다.
#modify and mark bot.py
f_botpy = open('bot.py','r+',encoding='UTF8')
strings = f_botpy.read()
commands = readcommand('../config/custom_command.txt')
for key, value in commands.items():
strings = strings.replace(key,value)
clearwrite(f_botpy,'#custom command\n' + strings)
f_botpy.close()