import sys
import traceback
import upbit

import time
import logging
import test_rsi as tr
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes, MessageHandler, filters, ConversationHandler

TOKEN = '33'

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context.

async def reStart(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [
        [
            InlineKeyboardButton("buy", callback_data="1"),
            InlineKeyboardButton("sell", callback_data="2"),
        ],
        [InlineKeyboardButton("감시", callback_data="3")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.callback_query.edit_message_text(" restart Bot. I will hold a conversation with you. ", reply_markup=reply_markup)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [
        [
            InlineKeyboardButton("buy", callback_data="1"),
            InlineKeyboardButton("sell", callback_data="2"),
        ],
        [InlineKeyboardButton("감시", callback_data="3")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text(" Hi! My name is start Bot. I will hold a conversation with you. ", reply_markup=reply_markup)

async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Parses the CallbackQuery and updates the message text."""
    query = update.callback_query
    await query.answer()
   
    # logging.info(text=f"Selected option: {query.data}")
    # await query.edit_message_text(text=f"Selected option: {query.data}")
    if query.data == '1':
        # upbit.buycoin_mp("KRW-BTC", '10000')
        await query.edit_message_text("BTC-KRW  10000 W 매수합니다")
    elif query.data == '2':
        # upbit.sellcoin_mp("KRW-BTC")
        await query.edit_message_text("KRW-BTC 시장가 매도 합니다")
       
    elif query.data == '3':      
        await query.edit_message_text("BTC-KRW---start")
        await coin(update, context)
       
    # return CallbackQueryHandler.END
     
async def coin(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:

    logging.info('--coin--')

    while True:
        rtnVal_rsi = tr.rsi_upbit(5) # 15 / 60 / 240 가능
        str_rsi = str( rtnVal_rsi)[:2]
        logging.info('--rsi='+ str_rsi)

        if rtnVal_rsi >= 70 :  
            textVal = "과매수 파세요~~~>>" + str_rsi
            await update.callback_query.message.edit_text(textVal)
            # await update.message.reply_text(textVal)
            # await reStart(update, context)
            break
        if rtnVal_rsi <= 30 :  
            textVal = "과매도~ 사세요~>>" + str_rsi
            await update.callback_query.message.edit_text(textVal)
            # await update.message.reply_text(textVal)
            # await reStart(update, context)
            break
        time.sleep(10)

async def bye(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("bye bye~")
    return CommandHandler.END

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Echo the user message."""
    await update.message.reply_text(update.message.text)

def main() -> None:
    """Start the bot."""
    application = Application.builder().token(TOKEN).build()

    # on different commands - answer in Telegram
    application.add_handler(CommandHandler("start", start))
    # application.add_handler(CommandHandler("coin", coin))
    # application.add_handler(CommandHandler("buy", buy))
    # application.add_handler(CommandHandler("sell", sell))
    application.add_handler(CallbackQueryHandler(button))
    application.add_handler(CommandHandler("bye", bye))

    # on non command i.e message - echo the message on Telegram
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    # Run the bot until the user presses Ctrl-C
    application.run_polling(allowed_updates=Update.ALL_TYPES)

# -----------------------------------------------------------------------------
# - Name : main
# - Desc : 메인
# -----------------------------------------------------------------------------
if __name__ == "__main__":
    main()

 

오늘은 텔레그램에 키보드를 만들고 

눌러서 결과값을 리턴받아  다음 태스크 실행 하는것을 연습해 보았다.

오류도 찾아가며 근본없이 코딩중 ㅎㅎ

 

참고자료

https://github.com/python-telegram-bot/python-telegram-bot/tree/master

+ Recent posts