• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

텔레그램 봇 만들기 코드 실행이 안됩니다 박사님..ㅠ

23.03.27 13:37 작성 23.03.27 13:38 수정 조회수 320

0

안녕하세요, 좋은 강의 보고 따라하면서 학습중입니다.

좋은강의 정말 감ㅅㅏ드립니다..

지금 텔레그램 봇 만들기 - 날씨 / 환율 응답, 컴퓨터 파일전송 기능 강의를 수강중입니다.

 

/dir [대상폴더] 는 잘 구현이 되었는데

/getfile /Users/사용자/test.txt

로 파일 전송 기능이 구현이 안됩니다..

디버깅으로 로그를 봐도 모르겠어서 질문 남깁니다!!

 

미리 감사드립니다.

스크린샷도 같이 첨부드립니다!

참고로 맥북으로 진행중입니다.

 

 

[1] 디버깅

[2] 기능구현 x

/dir /Users/Desktop 입력하면 데스크탑 파일목록 나옴.

[3] 코드

import telepot
import logging
import os

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

telegram_token = "6129613380:AAGbL2T-ogOaIK4v2YTPe4zTD9pzBikKLEA"

# 파일 경로 찾기
def get_dir_list(dir):
    str_list = ""
    if os.path.exists(dir):
        file_list = os.listdir(dir)
        file_list.sort()

        for f in file_list :
            full_path = os.path.join(dir,f)
            if os.path.isdir(full_path):
                f = "[" + f + "]"
            str_list += f
            str_list += "\n"
    str_list.strip()
    return str_list


def handler(msg):
    content_type, chat_Type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True) 

    print(msg)
    
    # if content_type == "text" :
    #     bot.sendMessage(chat_id, "[반사] {}".format(msg["text"]))

    # /dir c:\\workspace
    if content_type == "text":
        str_message = msg["text"]
        if str_message[0:1] == "/":
            args = str_message.split(" ")
            command = args[0]
            del args[0]

            if command == "/dir":
                filepath = " ".join(args)
                if filepath.strip() == " ":
                    bot.sendMessage(chat_id, "/dir [대상폴더]로 입력해주세요.")
       
                else:
                    filelist = get_dir_list(filepath)
                    bot.sendMessage(chat_id,filelist)

        elif command[0:4] == "/get":
            filepath = " ".join(args)
            if os.path.exists(filepath):
                try:
                    if command == "/getfile":
                        bot.sendDocument(chat_id, open(filepath, "rb"))
                    elif command == "/getimage":
                        bot.sendPhoto(chat_id, open(filepath, "rb"))
                    elif command == "/getaudio":
                        bot.sendAudio(chat_id, open(filepath, "rb"))
                    elif command == "getvideo" : #/getvideo c:\test\movie.mp4
                        bot.sendVideo(chat_id, open(filepath, "rb"))
                except Exception as e:
                    bot.sendMessage(chat_id, "파일 전송 실패 {}".format(e))
            else : 
                bot.sendMessage(chat_id, "파일이 존재하지 않습니다.")

bot = telepot.Bot(telegram_token)
bot.message_loop(handler,run_forever=True)

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.05.24

안녕하세요, 인프런 AI 인턴입니다.

해당 코드에서 /getfile 명령어 처리 부분이 실행되지 않는 이유는, elif 조건문이 if문 안에 위치하여 해당 코드가 실행되지 않고 지나가기 때문입니다. 따라서, handler 함수 내부의 코드에서 아래와 같이 elif문이 if문 바깥에 위치하도록 수정해주세요.

    # /dir c:\\workspace
    if content_type == "text":
        str_message = msg["text"]
        if str_message[0:1] == "/":
            args = str_message.split(" ")
            command = args[0]
            del args[0]

            if command == "/dir":
                filepath = " ".join(args)
                if filepath.strip() == " ":
                    bot.sendMessage(chat_id, "/dir [대상폴더]로 입력해주세요.")

                else:
                    filelist = get_dir_list(filepath)
                    bot.sendMessage(chat_id,filelist)

            elif command[0:4] == "/get":
                filepath = " ".join(args)
                if os.path.exists(filepath):
                    try:
                        if command == "/getfile":
                            bot.sendDocument(chat_id, open(filepath, "rb"))
                        elif command == "/getimage":
                            bot.sendPhoto(chat_id, open(filepath, "rb"))
                        elif command == "/getaudio":
                            bot.sendAudio(chat_id, open(filepath, "rb"))
                        elif command == "getvideo" : #/getvideo c:\test\movie.mp4
                            bot.sendVideo(chat_id, open(filepath, "rb"))
                    except Exception as e:
                        bot.sendMessage(chat_id, "파일 전송 실패 {}".format(e))
                else : 
                    bot.sendMessage(chat_id, "파일이 존재하지 않습니다.")