2018~/Python Skill Up
파이썬 텔레그램 쓰기 - 2 예약 명령어 구조 만들기(파일 관리)
반원_SemiCircle
2019. 9. 22. 21:57
/명령어 구조 만들기
- msg['text']에 처음 /이면 예약명령어로 인식
- 그 다음 if문으로 분기를 만들면 된다.
기존 echo 기능 재정리
def handle(msg):
content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)
print(msg)
print('-'*36)
if content_type == 'text':
#예약 명령어인지 확인
if msg['text'][0] == "/":
#에코 기능
if msg['text'].split()[0] == '/echo':
bot.sendMessage(chat_id, '(Echo)'+msg['text'][len('/echo '):])
파일목록 확인 기능 추가
TOKEN = '토큰값'
import telepot, os
from telepot.loop import MessageLoop
#해당 폴더 파일리스트
def get_dir_list(path):
if os.path.exists(path):
return os.listdir(path)
else :
return None
def handle(msg):
content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)
print(msg)
print('-'*36)
if content_type == 'text':
#예약 명령어인지 확인
if msg['text'][0] == "/":
#에코 기능
if msg['text'].split()[0] == '/echo':
bot.sendMessage(chat_id, '(Echo)'+msg['text'][len('/echo '):])
#파일 관련 기능
elif msg['text'].split()[0] == '/목록':
path = msg['text'][len('/목록 '):]
print(repr(path))
fileList = get_dir_list(path)
if fileList :
res = '[{}경로 파일 목록]'.format(path)
res += '\n'.join(fileList)
else :
res = '경로가 잘못되었습니다.'
bot.sendMessage(chat_id,res)
bot = telepot.Bot(TOKEN)
# MessageLoop(bot, handle).run_as_thread()
bot.message_loop(handle,run_forever=True)
print ('Listening ...')
전송 가능 함수들
- Bot 가능 함수 : 참고
- bot.sendMessage의 경우는 텍스트 보낼 경우 사용하는 함수
- text 이외의 파일 형태인 경우는 두번째 인자로 open('파일명','rb)를 넣어준다.
- sendPhoto
- sendAudio
- sendDocument
- sendVoice
문서, 사진, 영상 다운로드 추가
def handle(msg):
content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)
print(msg)
print('-'*36)
if content_type == 'text':
#예약 명령어인지 확인
if msg['text'][0] == "/":
#에코 기능
if msg['text'].split()[0] == '/echo':
bot.sendMessage(chat_id, '(Echo)'+msg['text'][len('/echo '):])
#파일 관련 기능
elif msg['text'].split()[0] == '/목록':
path = msg['text'][len('/목록 '):]
print(repr(path))
fileList = get_dir_list(path)
if fileList :
res = '[{}경로 파일 목록]'.format(path)
res += '\n'.join(fileList)
else :
res = '경로가 잘못되었습니다.'
bot.sendMessage(chat_id,res)
elif msg['text'].split()[0] == '/문서':
try:
path = msg['text'][len('/문서 '):]
if os.path.exists(path):
bot.sendDocument(chat_id,open(path,'rb'))
except:
bot.sendMessage(chat_id,'해당 파일을 찾을 수 없거나, 경로가 잘못되었습니다.')
elif msg['text'].split()[0] == '/사진':
try:
path = msg['text'][len('/사진 '):]
if os.path.exists(path):
bot.sendPhoto(chat_id,open(path,'rb'))
except:
bot.sendMessage(chat_id,'해당 파일을 찾을 수 없거나, 경로가 잘못되었습니다.')
elif msg['text'].split()[0] == '/영상':
try:
path = msg['text'][len('/영상 '):]
if os.path.exists(path):
bot.sendVideo(chat_id,open(path,'rb'))
except:
bot.sendMessage(chat_id,'해당 파일을 찾을 수 없거나, 경로가 잘못되었습니다.')
문서-사진-영상 코드 재정리
def handle(msg):
content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)
print(msg)
print('-'*36)
if content_type == 'text':
#예약 명령어인지 확인
if msg['text'][0] == "/":
#에코 기능
if msg['text'].split()[0] == '/echo':
bot.sendMessage(chat_id, '(Echo)'+msg['text'][len('/echo '):])
#파일 관련 기능
elif msg['text'].split()[0] == '/목록':
path = msg['text'][len('/목록 '):]
print(repr(path))
fileList = get_dir_list(path)
if fileList :
res = '[{}경로 파일 목록]'.format(path)
res += '\n'.join(fileList)
else :
res = '경로가 잘못되었습니다.'
bot.sendMessage(chat_id,res)
elif msg['text'].split()[0] in ['/문서','/사진','/영상']:
try:
path = msg['text'][len(msg['text'].split()[0])+1:]
if os.path.exists(path):
if msg['text'].split()[0] == '/문서':
bot.sendDocument(chat_id,open(path,'rb'))
elif msg['text'].split()[0] == '/사진':
bot.sendPhoto(chat_id,open(path,'rb'))
elif msg['text'].split()[0] == '/영상':
bot.sendVideo(chat_id,open(path,'rb'))
else :
bot.sendMessage(chat_id,'찾을 수 없습니다.')
except:
bot.sendMessage(chat_id,'전송 과정에서 오류가 발생하였습니다.')