inflearn logo
강의

Course

Instructor

Dr. Nam's Python Basics, 100% Practical Use

Making a Telegram Bot - Weather, Exchange Rate Response, Computer File Transfer

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

546

olivee

5 asked

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)

python 웹-크롤링 텔레그램봇

Answer 1

0

communityai8509

안녕하세요, 인프런 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, "파일이 존재하지 않습니다.")

38강 = 연산자 더하고 빼기

0

60

2

주석처리

0

116

1

함수의 파라미터값 msg

0

155

1

강의자료 이미지 안나옴

0

239

3

강의자료 질문 두번째

0

165

3

강의자료 관련 질문

0

116

1

파이썬 예외 처리 try / except 파일 처리 코드가 실행이 안됩니다.

0

235

1

소수 너무 어려워요

0

245

1

imagefont 함수 사용

0

239

1

pylint

0

357

1

add 함수 문의 ㅠㅠ

0

283

1

형식 문의드립니다.

0

209

1

변수 명을 왜 src, tar로 하셨는지 궁금합니다.

0

602

1

숫자야구 코드를 짜 봤는데 뭔가 이상합니다.

0

253

1

zsh: command not found: pylint

0

269

1

질문드립니다.

1

374

2

list.reverse() 출력에 대해서 질문있습니다.

1

433

1

데코레이터 함수 및 동작시간 질문입니다.~

1

323

2

opencv 사용하면서 궁금한점 (해상도)

1

781

1

질문드립니다.

1

299

1

아래 오류가 뜨면서 vscode가 컴파일이 되지 않는데.. 혹시 왜이럴까요?

1

445

1

크롤링안되는 현상 문의 드립니다.

1

421

1

파이썬 크롤링 관련 문의

1

277

1

정규 표현식 질문있습니다.

1

243

1