ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python] Make Korail reservation Macro with telegram bot
    Programing/python 2019. 11. 12. 21:37

     

     

    기차를 자주타서 예매를 하다 보면

    I often take train, so I always reserve ticket on my phone.

    원하는 여정이 매진일 때가 종종 있다.

    But the journey I want is usually sold out.

    그럴때면 새로고침을 하면서 계속 예매 시도를 한다.

    When that happen, I'll refresh and keep trying to book.

    이렇게 해서 실패한적은 없지만 시간과 노동이 소모되어 불편하다.

    This has never failed, but time and labor are inconvenient.

     

    텔레그램 봇을 이용해서 기차표 예약을 하는 매크로를 만들 수 있다는 글을 보게 되었다.

    I found out that I can create macro that uses Telegram bot to book train tickets.

    소스코드는 공개되지 않아, 직접만들기로 결심했다.

    I couldn't the source code, I decided to build it myself.

     

    개발 언어는 python을 사용하는게 유용해 보였다.

    The development language seemed to use Python.

    python으로 프로젝트를 한 경험이 없지만, (몇년째 주로 javascript를 사용한다.)

    I have no experience with python,) (I have mostly used javascript for several years.

    언어가 다 거기서 거기니 크게 게의치 않고 개발을 시작했다.

    But, the languages are all similer, so I started developing without much care.

     


    [주요 모듈 선택]

    [Main modules selection]

    1.

    텔레그램 봇 모듈은 telepot을 사용했다.

    I've used telepot module.

    선택 이유는 단순하다.

    The reason for the selection is simple.

    이 모듈로 충분히 개발 가능하다고 판단 되었고,

    I judged that this module could be developed enough,

    개발을 오랜시간 하고 싶지 않았다. (다른 모듈보다 먼저 알게 되었다.^^)

    and I didn't want to develop for a long time

     

     Etc moudule: python-telegram-bot 

     

    2.

    코레일 모듈은 korail2을 사용했다.

    I've used korail2 moude also.

     


     

     

    먼저 korail 관련 코드를 작성한다. 

    First, write code that related korail.

    # -*- coding: utf-8 -*-
    import sys
    from korail2 import *
    from datetime import datetime
    import json
    
    with open('account.json') as account:
        account_data = json.load(account)
    
    class Letskorail:
            def __init__(self, ...):
    
            def login(self, ...):
              
            def getInputString(self, ...):
    
            def insert(self, ...):
    
            def getTrainsLength(self, ...):
    
            def search(self, ...):
    
            def reserve(self, ...):
    

     

    코레일 계정 정보는 account.json 파일에 저장하여 불러온다.

    My korail account infomation loaded in the account.json file.

     

    Functions:

      __init__() : 디폴트 값을 설정한다. (예약 정보)

                      Set default values.(Reservation information)

      login() : 계정 정보를 가지고 코레일에 로그인 한다.

                   Login to korail with the account information.

      getInputString() : 설정된 변수값들을 String으로 반환한다.

                                  Return variable values converted to string.

      insert() : 예매 정보를 입력한다. (출발역, 도착역, 날짜, 시간)

                     Input your journey information. (departure station, arrival station, date, time)

      getTrainsLength() : 검색된 여정의 개수를 반환한다.

                                      Return count of searched journey list.

      search() : 여정 검색

                      Search for your journey.

      reserve() : 여정 예약

                      Reserve your choosen journey

     

     


     

    텔레그램 봇을 개발하기 위해선 인증 토큰을 생성해야한다.

    You must create Auth-token for Telegram bot develop.

     

    먼저 'BotFather'를 찾아서 대화를 건다.

    First, you can search 'BotFather' and start talk to him.

    BotFather

    /start 메시지를 보내면 명령어 세트를 확인 할 수 있다.

    You can check the command set by sending a '/start' message.

    /newbot 으로 새로운 나의 봇을 만들자.

    And you can create new bot by sending a '/newbot' message.

    create bot command

    봇 네임을 입력하면 아래와같이 봇링크와 토큰을 확인 할 수 있다.

    And then, if send bot name what you want, you can check new bot link and token.

     


     

    이제 마지막으로 봇 코드를 작성해본다.

    Finally, Write code that related bot.

     

    예약작업은 while 문을 사용하여

    Reservation job is used while loop.

    원하는 여정이 매진 시 성공할때까지 무한으로 작업을 시도한다.

    If it is sold out, repeat indefinitely work until success.

     

    예약 작업을 정지하고 싶으면, 정지 요청을 하면 되는데

    Basically, If you want to stop, you can send stop message.

    기본으로 하나의 쓰레드로 작업을 하면 정지를 시킬 수 없기 때문에

    But, you'll not be able to stop. because one thread.

    쓰레드를 추가하여 이 문제를 해결했다. (비동기로 해결을 해보려 했지만 잘 되지 않았다.)

    So, I create additional thread to macro job. (I tried to solve it asyncronously but it didn't work.)

    # -*- coding: utf-8 -*-
    import sys
    import time
    import telepot
    from telepot.loop import MessageLoop
    from korail2 import *
    from datetime import datetime
    from Letskorail import Letskorail
    import threading
    
    ...
    
    def reserve(chat_id, info):
        while is_reserved:
            작업
    
    def handle(msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        ...
        if content_type == 'text':
            if info == "시작":
                ...
            elif info == "예약":
                try:
                    t = threading.Thread(target=reserve, args=(chat_id, info))
                    t.start()
                except Exception as e :
                    print("expection: {}".format(e))
            elif info == "정지":
                        ...
    TOKEN = sys.argv[1]
    
    bot = telepot.Bot(TOKEN)
    MessageLoop(bot, handle).run_as_thread()
    print ('Listening ...')
    
    while 1:
        timeObject.sleep(10)

     

    Functions:

      handle() : 텔레그램 봇의 메세지 이벤트 헨들러

                      Message handler of Telegram bot.

      reserve() : 예약작업(매크로)을 수행

                        Run the reservation macro job.

     

     


     

    Run:

      $ python FILENAME.py TOKEN

     

     

     

    제대로 예약이 된 것을 확인 할 수 있다.

    You can check that you've a reservation.

     

     

     


     

     

     

     

     

     

     

     

     

     

     

    댓글

Designed by Tistory.