텔레봇을 사용하여 점심 메뉴 추천 받기

2024. 11. 25. 08:45·이것저것

Telegram 봇을 생성한김에 점심 메뉴 추천도 받아보고 싶어 짐 (매번 고르는게 힘듬)

개발은 할줄 모르기에 AI 도움을 받아 재미삼아 해 봄...

  • 봇 토큰은 별도의 파일에서 읽어오도록 설정 (token.txt)
  • 메뉴도 별도의 파일에서 읽어서 진행 (menu.txt)
  • 텔레그램 봇은 명령어로 영문, 숫자 및 밑줄(_)만 사용할 수 있음
    • 점심 추천 명령을 "밥먹자"로 사용하고 싶어 MessageHandler를 사용하여 입력 된 텍스트를 감지하여 특정 문자열(밥먹자)과 일치할 때 명령이 실행하도록 설정
    • 봇 명령 수행 시 "/"를 사용해야 되나 MessageHandler 사용으로 "/" 없이 입력 된 "밥먹자"를 감지
  • 추천한 메뉴가 맘에 들지 않을 경우 다시 선택 할 수 있도록 "다시 추천" 버튼 추가
  • 선택이 완료 되면 "종료" 버튼을 클릭하여 종료

 

소스코드

import random
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes, MessageHandler, filters

# 봇 토큰을 외부 파일에서 읽어오는 함수
def load_token():
    with open('token.txt', 'r') as file:
        return file.read().strip()

# 메뉴 파일에서 메뉴 목록을 읽어오는 함수
def load_menu():
    with open('menu.txt', 'r', encoding='utf-8') as file:
        return [line.strip() for line in file if line.strip()]

# 점심 명령어 처리 함수
async def lunch(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [[InlineKeyboardButton("점심 메뉴 추천", callback_data='recommend')]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text('안녕하세요! 점심 메뉴를 추천해드릴까요?', reply_markup=reply_markup)

# 버튼 클릭 처리 함수
async def button_click(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    query = update.callback_query
    await query.answer()

    if query.data == 'recommend':
        menu_list = load_menu()
        recommended_menu = random.choice(menu_list)
        await query.edit_message_text(text=f"오늘의 추천 점심 메뉴는 '{recommended_menu}'입니다!")

        # 추가 버튼을 제공하여 사용자가 다시 추천받거나 종료할 수 있도록 함
        keyboard = [
            [InlineKeyboardButton("다시 추천", callback_data='recommend')],
            [InlineKeyboardButton("종료", callback_data='exit')]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        await query.message.reply_text('다시 추천받으시겠습니까?', reply_markup=reply_markup)

    elif query.data == 'exit':
        await query.edit_message_text(text="봇을 종료합니다. 다음에 또 만나요!")

# 메시지를 처리하는 핸들러
async def text_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.message.text == "밥먹자":
        await lunch(update, context)

def main() -> None:
    TELEGRAM_TOKEN = load_token()  # 외부 파일에서 토큰 로드
    application = Application.builder().token(TELEGRAM_TOKEN).build()

    # /lunch 명령어에 대한 핸들러 추가
    application.add_handler(CommandHandler("lunch", lunch))
    
    # 텍스트 메시지 핸들러 추가 (한글 "밥먹자" 처리)
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, text_handler))

    application.add_handler(CallbackQueryHandler(button_click))

    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == '__main__':
    main()

 

 

 

실행

python lunch.py

 

 

 

Telegram 에서 확인

"밥먹자" 입력

 

"점심 메뉴 추천" 선택

 

"다시 추천" 선택

 

"종료" 선택

 

 

 

 

저작자표시 비영리 변경금지 (새창열림)
'이것저것' 카테고리의 다른 글
  • IGP, BGP(iBGP, eBGP) 비교
  • TCP Active open, Passive open 비교
  • PC 부팅 시 Telegram으로 메시지 보내기
  • PPS를 bps로, bps를 PPS로 변환
기억보다는 기록을...
기억보다는 기록을...
내가 보려고 정리하는 글..
  • 기억보다는 기록을...
    메모장
    기억보다는 기록을...
    • 분류 전체보기
      • 클라우드(Azure, AWS, Alibaba)
      • 모니터링(Zabbix,Grafana)
      • 가상화(VMWare, Hyper-V)
      • Docker
      • Ansible
      • Linux
      • Windows
      • 이것저것
      • SQL
      • -------------------------
      • 재테크
  • 전체
    오늘
    어제
  • hELLO· Designed By정상우.v4.10.2
기억보다는 기록을...
텔레봇을 사용하여 점심 메뉴 추천 받기
상단으로

티스토리툴바