예제 #1
0
def GetPostback(event):
    Reply_token = event.reply_token
    Text_fromUser = event.postback.params['datetime']
    print(Text_fromUser)

    month = int(Text_fromUser[5:7])
    print(month)

    import datetime

    monthinteger = month

    month = str(datetime.date(1900, monthinteger, 1).strftime('%B'))
    if month == 'October':
        month = 'ตุลาคม'
    elif month == 'December':
        month = 'ธันวาคม'

    print (month)

    message = '' ### message ที่เราจะส่งกลับไปให้ยูสเสอ
    from dialogflow_uncle import detect_intent_texts
    project_id = os.getenv('DIALOGFLOW_PROJECT_ID')
    session_id = event.source.user_id  ## get user id
    message = detect_intent_texts(project_id,session_id,month,'en')
    
    text = []
    user_data = None

    for i in message['fulfillment_messages']:### เพิ่มจากในคลิบ
        txt = TextSendMessage(text=i)### เพิ่มจากในคลิบ
        text.append(txt)### เพิ่มจากในคลิบ
    
    if message['action'] == 'selectmonth':
        from MessageTemplate.Imgmap import summary_msg
        data = message['parameters']
        from google.protobuf.json_format import MessageToDict
        data = MessageToDict(data)
        when = data['month']
        where = data['Type']
        course = data['courses']
        msg = Base.get_or_new_from_json_dict(summary_msg(when,where,course),FlexSendMessage)
        text.append(msg)### เพิ่มจากในคลิบ
    


    res = line_bot_api.reply_message(Reply_token,messages=text)
예제 #2
0
def message_text(event):

    ### function reply_token
    Reply_token = event.reply_token  #### reply token
    text_fromUser = event.message.text  ### ข้อความจาก ยูสเซอ line
    print(text_fromUser)

    #### ตรวจสอบ ว่า ภายในข้อความของยูส มีคำว่า เช็คราคา อยู่หรือไม่ ถ้าใช้ บอทจะตอบกลับเป็น flex message
    if 'เช็คราคา' in text_fromUser:
        from Resource.bxAPI import GetBxPrice
        from random import randint
        num = randint(1, 10)
        data = GetBxPrice(Number_to_get=num)  ## เก็บจำนวนข้อมูล

        from Resource.FlexMessage import setbubble, setCarousel

        flex = setCarousel(data)

        from Resource.reply import SetMenuMessage_Object, send_flex

        flex = SetMenuMessage_Object(flex)
        send_flex(Reply_token,
                  file_data=flex,
                  bot_access_key=channel_access_token)

    ##### check newsapi
    elif 'เช็คข่าวสาร' in text_fromUser:
        text = TextSendMessage(
            text='ท่านได้ทำการเลือกเมนู เช็คข่าวสาร')  #setup text message

        from Resource.FlexMessage import news_setbubble
        from Resource.reply import SetMenuMessage_Object, send_flex
        from Resource.GetNews import get_cnn_news

        data = get_cnn_news()
        flex = news_setbubble(data['title'], data['description'], data['url'],
                              data['image_url'])

        text = TextSendMessage(
            text='รายงานข่าวสารสำหรับ CNN ล่าสุด').as_json_dict()

        msg = SetMenuMessage_Object([text, flex])

        send_flex(Reply_token,
                  file_data=msg,
                  bot_access_key=channel_access_token)

    else:
        message = ''  ### message ที่เราจะส่งกลับไปให้ยูสเสอ
        from dialogflow_uncle import detect_intent_texts
        project_id = os.getenv('DIALOGFLOW_PROJECT_ID')
        session_id = event.source.user_id  ## get user id
        message = detect_intent_texts(project_id, session_id, text_fromUser,
                                      'th')

        text = []
        user_data = None

        for i in message['fulfillment_messages']:  ### เพิ่มจากในคลิบ
            txt = TextSendMessage(text=i)  ### เพิ่มจากในคลิบ
            text.append(txt)  ### เพิ่มจากในคลิบ

        if message[
                'action'] == 'Uncleregister.Uncleregister-custom.Uncleregister-courses-custom.Uncleregister-courses-where-custom.Uncleregister-courses-where-when-yes':
            user_data = TextSendMessage(text=str(
                message['parameters']))  ### เพิ่มจากในคลิบ
            text.append(user_data)  ### เพิ่มจากในคลิบ

        line_bot_api.reply_message(Reply_token, messages=text)
예제 #3
0
def handle_message(event):
    text_from_user = event.message.text
    reply_token = event.reply_token
    userid = event.source.user_id

    disname = line_bot_api.get_profile(user_id=userid).display_name
    request_text = ('mybot' + '\n' + '>> {} : {}').format(
        disname, text_from_user)

    print(request_text)
    linechat(request_text)

    result_from_dialogflow = detect_intent_texts(
        project_id="worldstock-iardyn",
        session_id=userid,
        text=text_from_user,
        language_code="th")

    action = result_from_dialogflow["action"]
    response = result_from_dialogflow["fulfillment_messages"]  #as list

    print("action : " + action)
    print("response : " + str(response))

    try:
        if 'สวัสดี' in text_from_user:
            text_list = [
                'สวัสดีจ้า คุณ {} สนใจหุ้นตัวไหน'.format(disname),
                'สวัสดีจ้า คุณ {} วันนี้จะเล่นตัวไหนดี'.format(disname),
            ]

            from random import choice
            word_to_reply = choice(text_list)
            text_to_reply = TextSendMessage(text=word_to_reply)
            line_bot_api.reply_message(event.reply_token,
                                       messages=[text_to_reply])
            return 'OK'
        else:
            from bs4 import BeautifulSoup as soup
            from urllib.request import urlopen as req
            from pandas_datareader import data
            from datetime import datetime, date
            from scipy.stats import linregress
            import math
            import numpy as np
            import pandas as pd

            code = text_from_user
            ticket = [text_from_user]
            symbols = list(map(lambda e: e + '.bk', ticket))

            def checkmarket(code):
                url = 'https://www.settrade.com/C04_01_stock_quote_p1.jsp?txtSymbol={}&ssoPageId=9&selectPage=1'.format(
                    code)
                webopen = req(url)
                page_html = webopen.read()
                webopen.close()
                data = soup(page_html, 'html.parser')
                price = data.findAll('div', {'class': 'col-xs-6'})
                title = price[0].text
                stockprice = price[2].text
                stockprice = stockprice.replace('\n', '')
                change = price[3].text
                change = change.replace('\n', '')
                change = change.replace('\r', '')
                change = change[87:]
                comvlue = data.findAll('div', {'class': 'col-xs-4'})
                comvlue = comvlue[6].text
                comvlue = comvlue.replace(',', '')
                comvlue = format(float(comvlue), '')
                comvluee = format(float(comvlue), ',')
                return [title, stockprice, change, comvlue, comvluee]

            set50 = [
                'ADVANC', 'AOT', 'AWC', 'BAM', 'BBL', 'BDMS', 'BEM', 'BGRIM',
                'BH', 'BJC', 'BTS', 'CBG', 'COM7', 'CPALL', 'CPF', 'CPN',
                'CRC', 'DELTA', 'DTAC', 'EA', 'EGCO', 'GLOBAL', 'GPSC', 'GULF',
                'HMPRO', 'INTUCH', 'IVL', 'KBANK', 'KTB', 'KTC', 'LH', 'MINT',
                'MTC', 'OR', 'OSP', 'PTT', 'PTTEP', 'PTTGC', 'RATCH', 'SAWAD',
                'SCB', 'SCC', 'SCGP', 'TISCO', 'TMB', 'TOA', 'TOP', 'TRUE',
                'TU', 'VGI'
            ]

            set100 = [
                'ACE', 'AEONTS', 'AMATA', 'AP', 'BANPU', 'BCH', 'BCP', 'BCPG',
                'BEC', 'BPP', 'CENTEL', 'CHG', 'CK', 'CKP', 'DOHOME', 'EPG',
                'ESSO', 'GFPT', 'GUNKUL', 'HANA', 'JAS', 'IRPC', 'JMART',
                'JMT', 'KCE', 'KKP', 'MAJOR', 'MBK', 'MEGA', 'ORI', 'PLANB',
                'PRM', 'PTG', 'QH', 'RBF', 'RS', 'SPALI', 'STA', 'STEC',
                'SUPER', 'TCAP', 'THANI', 'TASCO', 'TISCO', 'TMB', 'TOA',
                'TPIPP', 'TQM', 'TTW', 'TVO', 'WHA', 'WHAUP'
            ]

            class stock:
                def __init__(self, stock):
                    self.stock = stock

                def ticket(self):
                    end = datetime.now()
                    start = datetime(end.year, end.month, end.day)
                    list = self.stock

                    dfall = data.DataReader(f'{list}',
                                            data_source="yahoo",
                                            start=start_year,
                                            end=end)
                    try:
                        dfM = data.DataReader(f'{list}',
                                              data_source="yahoo",
                                              start=monthly,
                                              end=end)
                    except ValueError:
                        dfM = data.DataReader(f'{list}',
                                              data_source="yahoo",
                                              start=start_year,
                                              end=end)
                    try:
                        preM = data.DataReader(f'{list}',
                                               data_source="yahoo",
                                               start=prevm,
                                               end=endvm)
                    except ValueError:
                        preM = data.DataReader(f'{list}',
                                               data_source="yahoo",
                                               start=start_year,
                                               end=end)

                    list = list.replace('.bk', '')
                    st = checkmarket(code)
                    stock = f'{list}'
                    list = list.upper()

                    try:
                        Close = float(st[1])
                    except ValueError:
                        Close = dfall['Close'].iloc[-1]
                    Close = '%.2f' % Close

                    OpenD = dfall['Open'].iloc[-1]
                    OpenD = '%.2f' % OpenD

                    try:
                        today_chg = float(st[2])
                    except ValueError:
                        today_chg = float(dfall['Close'].iloc[-1]) - float(
                            dfall['Close'].iloc[-2])
                    today_chg = '%.2f' % today_chg

                    #copy dataframeY
                    dfall = dfall.copy()
                    dfall['date_id'] = (
                        (dfall.index.date -
                         dfall.index.date.min())).astype('timedelta64[D]')
                    dfall['date_id'] = dfall['date_id'].dt.days + 1

                    # high trend lineY
                    dfall_mod = dfall.copy()
                    while len(dfall_mod) > 3:
                        reg = linregress(
                            x=dfall_mod['date_id'],
                            y=dfall_mod['Close'],
                        )
                        dfall_mod = dfall_mod.loc[dfall_mod['Close'] > reg[0] *
                                                  dfall_mod['date_id'] +
                                                  reg[1]]
                    reg = linregress(
                        x=dfall_mod['date_id'],
                        y=dfall_mod['Close'],
                    )
                    dfall['high_trend'] = reg[0] * dfall['date_id'] + reg[1]

                    # low trend lineY
                    dfall_mod = dfall.copy()
                    while len(dfall_mod) > 3:
                        reg = linregress(
                            x=dfall_mod['date_id'],
                            y=dfall_mod['Close'],
                        )
                        dfall_mod = dfall_mod.loc[dfall_mod['Close'] < reg[0] *
                                                  dfall_mod['date_id'] +
                                                  reg[1]]
                    reg = linregress(
                        x=dfall_mod['date_id'],
                        y=dfall_mod['Close'],
                    )
                    dfall['low_trend'] = reg[0] * dfall['date_id'] + reg[1]

                    HpreM = preM.nlargest(1, columns='High')
                    HpreM = HpreM['High'].iloc[-1]
                    if HpreM >= 100:
                        HpreM = (round(HpreM / 0.5) * 0.5)
                    elif HpreM >= 25:
                        HpreM = (round(HpreM / 0.25) * 0.25)
                    elif HpreM >= 10:
                        HpreM = (round(HpreM / 0.1) * 0.1)
                    elif HpreM >= 5:
                        HpreM = (round(HpreM / 0.05) * 0.05)
                    else:
                        HpreM = (round(HpreM / 0.02) * 0.02)
                    HpreM = '%.2f' % HpreM

                    LpreM = dfM.nlargest(1, columns='High')
                    LpreM = LpreM['Low'].iloc[-1]
                    if LpreM >= 100:
                        LpreM = (round(LpreM / 0.5) * 0.5)
                    elif LpreM >= 25:
                        LpreM = (round(LpreM / 0.25) * 0.25)
                    elif LpreM >= 10:
                        LpreM = (round(LpreM / 0.1) * 0.1)
                    elif LpreM >= 5:
                        LpreM = (round(LpreM / 0.05) * 0.05)
                    else:
                        LpreM = (round(LpreM / 0.02) * 0.02)
                    LpreM = '%.2f' % LpreM

                    HpreMp = (
                        (float(Close) - float(HpreM)) / float(HpreM)) * 100
                    HpreMp = '%.2f' % HpreMp

                    max_Y = dfall.nlargest(1, columns='High')
                    max_Y = max_Y['High'].iloc[-1]
                    max_Y = '%.2f' % max_Y

                    dif_max = (
                        (float(max_Y) - float(Close)) / float(Close)) * 100
                    dif_max = '%.2f' % dif_max

                    if (stock in set50):
                        inline = f'SET50'
                    elif (stock in set100):
                        inline = f'SET100'
                    else:
                        inline = ' '

                    text_return = f'{list} \nH {HpreM} ({HpreMp}%) > {Close} ({today_chg}) \ntake profit <= {LpreM}'
                    linechat(text_return)
                    word_to_reply = str(f'{text_return}')
                    print(word_to_reply)

                    text = st[0]
                    price_now = str(Close)
                    change = str(today_chg)
                    chgp = str(inline)

                    notice = f'{max_Y} ({dif_max}%)'
                    start = f'{HpreM} ({HpreMp}%)'
                    stop = f'{LpreM}'
                    target = f'{OpenD}'
                    avg = ' '

                    bubbles = []
                    bubble = flex_stock(text, price_now, change, chgp, notice,
                                        start, stop, target, avg)

                    flex_to_reply = SetMessage_Object(bubble)
                    reply_msg(reply_token,
                              data=flex_to_reply,
                              bot_access_key=channel_access_token)
                    return 'OK'

            for symbol in symbols:
                stock(symbol).ticket()

    except:
        text_list = [
            'หุ้น {} ไม่แสดงข้อมูล'.format(text_from_user),
            '{} สะกด {} ไม่ถูกต้อง'.format(disname, text_from_user),
        ]

        from random import choice
        word_to_reply = choice(text_list)
        text_to_reply = TextSendMessage(text=word_to_reply)
        line_bot_api.reply_message(event.reply_token, messages=[text_to_reply])
예제 #4
0
def message_text(event):
    print(event)
    Text_fromUser = event.message.text
    reply_Token = event.reply_token

    if 'เช็คราคา' in Text_fromUser:
        from Resource.bxAPI import GetBxPrice
        msg = GetBxPrice(Number_to_get=10)
        from Resource.FlexMessage import setCarousel
        flex = setCarousel(msg)  ### setup carousel
        flex = SetMenuMessage_Object(flex) ### setup flex
        send_flex(reply_Token , flex , channel_access_token)
    
    elif 'เช็คข่าวสาร' in Text_fromUser:
        from Resource.GetNews import get_cnn_news
        data = get_cnn_news()
        from Resource.FlexMessage import news_setbubble
        msg = news_setbubble(data['title'],data['description'],data['url'],data['image_url'])
        flex = SetMenuMessage_Object(msg)
        send_flex(reply_Token , flex , channel_access_token)
    
    else :
        message = '' ### message ที่เราจะส่งกลับไปให้ยูสเสอ
        text = []
        user_data = None

        from dialogflow_uncle import detect_intent_texts
        project_id = os.getenv('DIALOGFLOW_PROJECT_ID')
        session_id = event.source.user_id  ## get user id
        message = detect_intent_texts(project_id,session_id,Text_fromUser,'th')
        

        for i in message['fulfillment_messages']: ### เพิ่มจากในคลิบ
            txt = TextSendMessage(text=i)### เพิ่มจากในคลิบ
            text.append(txt)### เพิ่มจากในคลิบ

        ## adding imagemap message เรียนอะไร
        if message['action'] == 'register':
            from MessageTemplate.Imgmap import selectCourse
            imagemap = Base.get_or_new_from_json_dict(selectCourse(),ImagemapSendMessage)
            text.append(imagemap)
            ### prepare imagemap message to send

        #### เรียนที่ไหน
        elif message['action'] == 'selectcourses':
            from MessageTemplate.Imgmap import selectWhere
            imagemap = Base.get_or_new_from_json_dict(selectWhere(),ImagemapSendMessage)
            text.append(imagemap)
            ### prepare Imagemap message to send

        ### ให้ยูสเซอลงเวลา
        elif message['action'] == 'selecttype':
            from MessageTemplate.Imgmap import selectTime
            msg = Base.get_or_new_from_json_dict(selectTime(),TemplateSendMessage)
            text.append(msg)
        
        #### confirm message
        elif message['action'] == 'selectmonth':
            from MessageTemplate.Imgmap import confirmRegis
            msg = Base.get_or_new_from_json_dict(confirmRegis(),TemplateSendMessage)
            text.append(msg)
        
        ### sumarize message
        elif message['action'] == 'confirm':
            from google.protobuf.json_format import MessageToDict
            data = message['parameters']
            data = MessageToDict(data)

            from MessageTemplate.Imgmap import GetStudentCard


            ####เนื้องจากการส่งข้อความแบบ flex2019 SDK python ยังไม่รองรับทำให้เราต้องกลับมาส่งแบบ manual
            msg = []
            for i in text:
                Dict = i.as_json_dict()
                msg.append(Dict)
            msg.append(GetStudentCard(data['courses']))
            flex = SetMenuMessage_Object(msg)
            send_flex(reply_Token,file_data = flex,bot_access_key = channel_access_token)
        #### กรณีเข้าโหมดถามตอบ
        elif message['action'] == 'q&a':
            line_bot_api.link_rich_menu_to_user(session_id,richmenu['menu2'])
        #### กรณีกำลังถามตอบ
        elif message['action'] == 'qa.qa-fallback':
            from MessageTemplate.Imgmap import AnwserMsg

            from Resource.wolf import search_wiki

            result = search_wiki(Text_fromUser)

            ### set msg + answer
            Flex_Ans = AnwserMsg(Text_fromUser,result)

            ### set quick reply
            qbtn = QuickReplyButton(image_url='https://cdn0.iconfinder.com/data/icons/online-education-butterscotch-vol-2/512/Questions_And_Answers-512.png'
            ,action=MessageAction('หยุดถาม','หยุดถาม'))
            q = QuickReply(items=[qbtn])

            ### set text as json
            new_text1 = TextSendMessage(text='ลุงขอหาแปรป...').as_json_dict()
            new_text2 = TextSendMessage(text='อยากถามต่อไหม ถ้าไม่... กดปุ่ม หยุดถามได้เลยจร้า',quick_reply=q).as_json_dict()

            ### send msg with quick reply
            flex = SetMenuMessage_Object(Message_data=[new_text1,Flex_Ans,new_text2])

            r = send_flex(Reply_token,file_data = flex,bot_access_key = channel_access_token)
        #### กรณีหยุดถาม
        elif message['action'] == 'qa.qa-custom':
            line_bot_api.link_rich_menu_to_user(session_id,richmenu['menu1'])
            text = TextSendMessage(text='แล้วกลับมาถามใหม่น่าาาา...')
            line_bot_api.reply_message(reply_Token,text)
        print(message['action'])
        line_bot_api.reply_message(reply_Token,text)
            
    
    return 'OK'
예제 #5
0
def message_text(event):
    reply_token =  event.reply_token
    text_fromuser = event.message.text
    session_id = event.source.user_id
    text = TextSendMessage(text=text_fromuser)
   
   
    # text2 = TextSendMessage(text="test")
    # image_message_1 = ImageSendMessage(
    #     original_content_url='https://image.freepik.com/free-photo/green-blue-transparent-leaves_23-2148239758.jpg',
    #     preview_image_url='https://image.freepik.com/free-photo/green-blue-transparent-leaves_23-2148239758.jpg'
    # )
    # line_bot_api.reply_message(
    #     reply_token,
    #     messages=[text,text2,image_message_1]
    # )
    # line_bot_api.push_message(
    #     to=str(event.source),
    #     messages=text
    # )
    # # line_bot_api.multicast(["U65c8c03c10487a69855fd591bd830ac1","U4dd62d9af204ed4fa2f0a3f58c47db19"],text)
    # line_bot_api.push_message("U65c8c03c10487a69855fd591bd830ac1",TextSendMessage(text='Hello World!'))
    if 'เช็คราคา' in text_fromuser:
        from Resource.bxAPI import GetBxPrice
        from random import randint
        from flexMsg import setCarousel,setbubble
        num = randint(1,10)
        data = GetBxPrice(num)

        flex_data = setCarousel(data) 
        print(flex_data)
        from Resource.reply import SetMenuMessage_Object,send_flex
        flex= SetMenuMessage_Object(flex_data)
        send_flex(reply_token,flex,channel_access_token)
    elif 'เช็คข่าวสาร' in text_fromuser:
      
        # image = ImageSendMessage(original_content_url='https://yt3.ggpht.com/a/AGF-l7-ROxk4wco8xCKXtbSltQpYTsAvqNkrkQv1nA=s900-c-k-c0xffffffff-no-rj-mo',preview_image_url='https://yt3.ggpht.com/a/AGF-l7-ROxk4wco8xCKXtbSltQpYTsAvqNkrkQv1nA=s900-c-k-c0xffffffff-no-rj-mo')
        # line_bot_api.reply_message(reply_token,messages=[text,image])
        from flexMsg import news_setbubble 
        from Resource.reply import SetMenuMessage_Object , send_flex
        from Resource.newsAPI import get_cnn_news

        data = get_cnn_news()
        flex = news_setbubble(data['title'],data['description'],data['url'],data['image_url'])
        
        text = TextSendMessage(text='รายงานข่าวสารสำหรับ CNN ล่าสุด').as_json_dict()

        msg = SetMenuMessage_Object([text,flex])

        send_flex(reply_token,file_data = msg,bot_access_key = channel_access_token)

    elif 'เช็คเงื่อนไขพัสดุ' in text_fromuser:
      
        # image = ImageSendMessage(original_content_url='https://yt3.ggpht.com/a/AGF-l7-ROxk4wco8xCKXtbSltQpYTsAvqNkrkQv1nA=s900-c-k-c0xffffffff-no-rj-mo',preview_image_url='https://yt3.ggpht.com/a/AGF-l7-ROxk4wco8xCKXtbSltQpYTsAvqNkrkQv1nA=s900-c-k-c0xffffffff-no-rj-mo')
        # line_bot_api.reply_message(reply_token,messages=[text,image])
        from flexMsg import news_setbubble,test_setbubble 
        from Resource.reply import SetMenuMessage_Object , send_flex
        from Resource.newsAPI import get_cnn_news

        data = get_cnn_news()
        flex = test_setbubble()
        
        # text = TextSendMessage(text='รายงานข่าวสารสำหรับ CNN ล่าสุด').as_json_dict()

        msg = SetMenuMessage_Object([flex])

        send_flex(reply_token,file_data = msg,bot_access_key = channel_access_token)
    else:
        message = '' #ข้อความที่จะส่งกลับไปหา user
        from dialogflow_uncle import detect_intent_texts
        project_id = os.getenv('DIALOGFLOW_PROJECT_ID')
        message = detect_intent_texts(project_id=project_id,session_id=session_id,text=text_fromuser,language_code='th')
        
        text = []
        user_data = None

        for i in message['fulfillment_messages']:### เพิ่มจากในคลิบ
            txt = TextSendMessage(text=i)### เพิ่มจากในคลิบ
            text.append(txt)### เพิ่มจากในคลิบ

        if message['action'] == 'Uncleregister.Uncleregister-custom.Uncleregister-courses-custom.Uncleregister-courses-where-custom.Uncleregister-courses-where-when-yes':
            user_data = TextSendMessage(text=str(message['parameters']))### เพิ่มจากในคลิบ
            text.append(user_data)### เพิ่มจากในคลิบ
       
        # text = TextSendMessage(text="test")
       
        line_bot_api.reply_message(reply_token=reply_token,messages=text)
예제 #6
0
def handle_message(event):
    text_from_user = event.message.text
    reply_token = event.reply_token
    userid = event.source.user_id
    
    disname = line_bot_api.get_profile(user_id=userid).display_name
    request_text= ('ticket'+'\n' + '>> {} : {}').format(disname,text_from_user)
    print(request_text)
    linechat(request_text)

    result_from_dialogflow = detect_intent_texts(project_id="worldstock-iardyn",
                                        session_id=userid ,
                                        text=text_from_user , 
                                        language_code="th")
    
    action = result_from_dialogflow["action"]
    response = result_from_dialogflow["fulfillment_messages"] #as list

    print("action : " + action)
    print("response : " + str(response))

    try:
        if 'Hello Bot' in text_from_user:    
            text_list = [
                'สวัสดีจ้า คุณ {} '.format(disname),
                'สวัสดีจ้า คุณ {} วันนี้จะเล่นตัวไหนดี'.format(disname),
            ]

            from random import choice
            word_to_reply = choice(text_list)
            text_to_reply = TextSendMessage(text = word_to_reply)
            line_bot_api.reply_message(
                    event.reply_token,
                    messages=[text_to_reply]
                )
            return 'OK'

        else:
            from bs4 import BeautifulSoup as soup
            from urllib.request import urlopen as req
            from pandas_datareader import data
            from datetime import datetime, date
                    
            code = text_from_user
            ticket = [text_from_user]
            symbols = list(map(lambda e: e + '.bk', ticket))
                        
            def checkmarket(code):
                url = 'https://www.settrade.com/C04_01_stock_quote_p1.jsp?txtSymbol={}&ssoPageId=9&selectPage=1'.format(code)
                webopen = req(url)
                page_html = webopen.read()
                webopen.close()

                data = soup(page_html, 'html.parser')
                price = data.findAll('div',{'class':'col-xs-6'})
                title = price[0].text
                stockprice = price[2].text
                stockprice = stockprice.replace('\n','')
                change = price[3].text
                change = change.replace('\n','')
                change = change.replace('\r','')
                change = change[87:]
                change = change.replace('\n','')
                change = change.replace('(','')
                comvlue = data.findAll('div',{'class':'col-xs-4'})
                comvlue = comvlue[6].text
                comvlue = comvlue.replace(',','')
                comvlue = format(float(comvlue),'')
                comvluee = format(float(comvlue),',')
                return [title,stockprice,change,comvlue,comvluee]
            def free(code):
                url = 'https://www.settrade.com/C04_05_stock_majorshareholder_p1.jsp?txtSymbol={}&ssoPageId=14&selectPage=5'.format(code)
                webopen = req(url)
                page_html = webopen.read()
                webopen.close()
                data = soup(page_html, 'html.parser')
                freefloat = data.findAll('div',{'class':'row separate-content'})
                freefloat = freefloat[0].text
                freefloat = freefloat.replace('\n','')
                freefloat = freefloat.replace('\r','')
                freefloat = freefloat[-6:]
                freefloat = freefloat.replace('%','')
                return [freefloat]

            class ticket:
                def __init__(self,stock):
                    self.stock = stock
                    list = self.stock
                def bull(self):
                    list = self.stock

                    dfall = data.DataReader(f'{list}', data_source="yahoo",start=start_year, end=end)

                    try:
                        dfY = data.DataReader(f'{list}', data_source="yahoo", start=yearly, end=end)
                    except ValueError:
                        dfY = data.DataReader(f'{list}', data_source="yahoo", start=start_year, end=end)

                    try:
                        dfM = data.DataReader(f'{list}', data_source="yahoo", start=monthly, end=end)
                    except ValueError:
                        dfM = data.DataReader(f'{list}', data_source="yahoo", start=start_year, end=end)

                    list = list.replace('.bk','')
                    stock = f'{list}'
                    dfall.dropna(inplace=True)

                    st = checkmarket(stock)
                    fr = free(stock)
                    freefloat = fr[0]

                    try:
                        Close = float(st[1])
                    except ValueError:
                        Close = dfall['Close'].iloc[-1]

                    Close  = '%.2f'%Close
                    Close = str(Close) 

                    Open_all = dfall['Open'].iloc[0]
                    Open_all  = '%.2f'%Open_all
                    Open_all = str(Open_all)

                    Chg_all = ((float(Close) - float(Open_all))/ float(Open_all))*100
                    Chg_all = '%.2f'%Chg_all
                    Chg_all = str(Chg_all)

                    OpenY = dfY['Open'].iloc[0]
                    OpenY  = '%.2f'%OpenY
                    OpenY = str(OpenY)

                    CloseY = dfY['Close'].iloc[0]
                    CloseY  = '%.2f'%CloseY
                    CloseY = str(CloseY)

                    ChgY = ((float(Close) - float(OpenY)) / float(OpenY) )*100
                    ChgY = '%.2f'%ChgY
                    ChgY = str(ChgY)

                    Chg_closeY = ((float(Close) - float(CloseY)) / float(CloseY) )*100
                    Chg_closeY = '%.2f'%Chg_closeY
                    Chg_closeY = str(Chg_closeY)

                    OpenM = dfM['Open'].iloc[0]
                    OpenM  = '%.2f'%OpenM
                    OpenM = str(OpenM)

                    CloseM = dfM['Close'].iloc[0]
                    CloseM  = '%.2f'%CloseM
                    CloseM = str(CloseM)

                    ChgM = ((float(Close) - float(CloseM)) / float(CloseM) )*100
                    ChgM = '%.2f'%ChgM
                    ChgM = str(ChgM)

                    try:
                        today_chg = float(st[2])
                    except ValueError:
                        today_chg = float(dfall['Close'].iloc[-1]) - float(dfall['Close'].iloc[-2])

                    today_chg  = '%.2f'%today_chg
                    today_chg = str(today_chg)

                    def computeRSI (data, time_window):
                        diff = data.diff(1).dropna()
                        up_chg = 0 * diff
                        down_chg = 0 * diff

                        up_chg[diff > 0] = diff[ diff>0 ]    
                        down_chg[diff < 0] = diff[ diff < 0 ]

                        up_chg_avg   = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
                        down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean()

                        rs = abs(up_chg_avg/down_chg_avg)
                        rsi = 100 - 100/(1+rs)
                        return rsi

                    dfall['RSI'] = computeRSI(dfall['Close'], 14)
                    m_RSI = dfall['RSI'].iloc[-1]
                    m_RSI = '%.2f'%m_RSI
                    m_RSI = str(m_RSI)
                            
                    #copy dataframeY
                    dfall = dfall.copy()
                    dfall['date_id'] = ((dfall.index.date - dfall.index.date.min())).astype('timedelta64[D]')
                    dfall['date_id'] = dfall['date_id'].dt.days + 1

                    # high trend lineY
                    dfall_mod = dfall.copy()

                    while len(dfall_mod)>3:

                        reg = linregress(x=dfall_mod['date_id'],y=dfall_mod['Close'],)
                        dfall_mod = dfall_mod.loc[dfall_mod['Close'] > reg[0] * dfall_mod['date_id'] + reg[1]]

                    reg = linregress(x=dfall_mod['date_id'],y=dfall_mod['Close'],)
                    dfall['high_trend'] = reg[0] * dfall['date_id'] + reg[1]

                    # low trend lineY
                    dfall_mod = dfall.copy()

                    while len(dfall_mod)>3:

                        reg = linregress(x=dfall_mod['date_id'],y=dfall_mod['Close'],)
                        dfall_mod = dfall_mod.loc[dfall_mod['Close'] < reg[0] * dfall_mod['date_id'] + reg[1]]

                    reg = linregress(x=dfall_mod['date_id'],y=dfall_mod['Close'],)
                    dfall['low_trend'] = reg[0] * dfall['date_id'] + reg[1]
                    
                    min_Y = dfall.nsmallest(1, columns='Low')
                    min_Y = min_Y['Low'].iloc[-1]
                    min_Y = '%.2f'%min_Y
                    min_Y = str(min_Y)

                    max_Y = dfall.nlargest(1, columns='High')
                    max_Y = max_Y['High'].iloc[-1]
                    max_Y = '%.2f'%max_Y
                    max_Y = str(max_Y)

                    dfall['min_Y'] = float(min_Y)
                    dfall['max_Y'] = float(max_Y)
                    
                    #copy dataframe prevQ
                    dfY = dfY.copy()
                    dfY['date_id'] = ((dfY.index.date - dfY.index.date.min())).astype('timedelta64[D]')
                    dfY['date_id'] = dfY['date_id'].dt.days + 1

                    # high trend line prevQ
                    dfY_mod = dfY.copy()

                    while len(dfY_mod)>3:

                        reg = linregress(x=dfY_mod['date_id'],y=dfY_mod['Close'],)
                        dfY_mod = dfY_mod.loc[dfY_mod['Close'] > reg[0] * dfY_mod['date_id'] + reg[1]]

                    reg = linregress(x=dfY_mod['date_id'],y=dfY_mod['Close'],)
                    dfY['high_trendQ'] = reg[0] * dfY['date_id'] + reg[1]

                    # low trend line prevQ
                    dfY_mod = dfY.copy()

                    while len(dfY_mod)>3:

                        reg = linregress(x=dfY_mod['date_id'],y=dfY_mod['Close'],)
                        dfY_mod = dfY_mod.loc[dfY_mod['Close'] < reg[0] * dfY_mod['date_id'] + reg[1]]

                    reg = linregress(x=dfY_mod['date_id'],y=dfY_mod['Close'],)
                    dfY['low_trendQ'] = reg[0] * dfY['date_id'] + reg[1]
                    dfY['low_trendQ'] = dfY['low_trendQ'].replace(np.nan, dfY['Close'].iloc[0])

                    candle_start = dfY['low_trendQ'].iloc[0]
                    candle_start = '%.2f'%candle_start
                    candle_start = str(candle_start)

                    candle_end = dfY['low_trendQ'].iloc[-1]
                    candle_end = '%.2f'%candle_end
                    candle_end = str(candle_end)

                    if float(candle_start) > float(candle_end):
                        pattern = 'Lower low'
                    else:
                        pattern = 'Lower high'

                    Volume = dfY['Volume'].iloc[-1]
                    Volume = str(Volume)

                    vol_buy = (float(budget) / float(OpenY))
                    vol_buy = round(vol_buy,-2)

                    vol_key = float(vol_buy) / 2
                    vol_key = round(vol_key,-2)
                    vol_key = str(int(vol_key))

                    trade_val = float(Close) * float(Volume)
                    trade_val = int(float(trade_val))
                    trade_value = '{:,}'.format(trade_val)

                    dfall['Open_all'] = dfall['Open'].iloc[0]
                    dfall['high_trendQ'] = dfY['high_trendQ']
                    dfall['low_trendQ'] = dfY['low_trendQ']

                    dfY['OpenY'] = dfY['Open'].iloc[0]
                    dfY['CloseY'] = dfY['Close'].iloc[0]
                    dfM['CloseM'] = dfM['Close'].iloc[0]

                    dfall['ema'] = dfall['Close'].rolling(35).mean()
                    dfall['ema'] = dfall['ema'].replace(np.nan, dfY['Close'].iloc[0])
                    dfall['emas'] = dfall['Close'].rolling(10).mean()
                    dfall['emas'] = dfall['emas'].replace(np.nan, dfY['Close'].iloc[0])

                    ema = dfall['ema'].iloc[-1]
                    ema = float(ema)

                    if ema >= 100:
                        ema = (round(ema/0.5) * 0.5)
                    elif ema >= 25:
                        ema = (round(ema/0.25) * 0.25)
                    elif ema >= 10:
                        ema = (round(ema/0.1) * 0.1)
                    elif ema >= 5:
                        ema = (round(ema/0.05) * 0.05)
                    else:
                        ema = (round(ema/0.02) * 0.02)

                    ema = '%.2f'%ema
                    ema = str(ema)

                    emas = dfall['emas'].iloc[-1]
                    emas = float(emas)

                    if emas >= 100:
                        emas = (round(emas/0.5) * 0.5)
                    elif emas >= 25:
                        emas = (round(emas/0.25) * 0.25)
                    elif emas >= 10:
                        emas = (round(emas/0.1) * 0.1)
                    elif emas >= 5:
                        emas = (round(emas/0.05) * 0.05)
                    else:
                        emas = (round(emas/0.02) * 0.02)

                    emas = '%.2f'%emas
                    emas = str(emas)

                    pema = dfall['ema'].iloc[-1]
                    pema = ((float(Close) - float(pema)) / float(pema))*100
                    pema = '%.2f'%pema
                    pema = str(pema)

                    high_trend = dfall['high_trend'].iloc[-1]
                    high_trend = '%.2f'%high_trend
                    high_trend = str(high_trend)

                    high_trendQ = dfall['high_trendQ'].iloc[-1]
                    high_trendQ = '%.2f'%high_trendQ
                    high_trendQ = str(high_trendQ)

                    comvlue = float(st[3])
                    comvluee = str(st[4])

                    if float(ChgM) >= 0.0 :
                        trendM = ' '
                    else:
                        trendM = 'X'

                    if float(ChgY) >= 0 :
                        trendAll = '▲'
                        if float(Close) >= float(CloseM) :
                            if float(Close) >= float(ema):
                                trendY = '©'
                            else:
                                trendY = ' '
                        else:
                            trendY = ' '
                    else:
                        trendAll = '▼'
                        if float(Close) >= float(CloseM) :
                            if float(Close) >= float(ema):
                                trendY = '℗'
                            else:
                                trendY = ' '
                        else:
                            trendY = ' '
			        
                    if float(today_chg) >= 0:
                        if float(Close) > float(CloseY):
                            if float(Close) >= float(CloseM) :
                                if float(Close) >= float(ema):
                                    notice = f'หุ้นขาใหญ่เก็บ {CloseM}'
                                else:
                                    notice = f'หุ้นขาใหญ่ขาย {ema}'
                            else:
                                notice = f'หุ้นขาใหญ่ปล่อยไหล {CloseM}'
                        elif float(Close) >= float(CloseM) :
                            if float(Close) >= float(ema):
                                notice = f'หุ้นกลับตัวมีแรงซื้อ {CloseM}'
                            else:
                                notice = f'หุ้นไหลเมื่อหลุด {ema}'
                        elif float(Close) >= float(ema):
                            notice = f'หุ้นกลับตัวระยะสั้น เมื่อผ่าน {ema}'
                        else:
                            notice = f'หุ้นไม่มีใครเก็บ {ema}'
                    else:
                        notice = f'กำลังย่อ/ปรับฐาน ไม่หลุด {CloseM} ห่อกลับ'
                    
                    text = f'ตอนนี้ {list} \nราคา {Close} ({today_chg}) \n{notice} \nแนวต้าน {max_Y}  \nแนวรับ {min_Y}  \nFree Float {freefloat}%'

                    word_to_reply = str('{}'.format(text))
                    linechat(word_to_reply)
                    text_to_reply = TextSendMessage(text = word_to_reply)
                    line_bot_api.reply_message(event.reply_token,messages=[text_to_reply])
                    return 'OK'
            
            for code in codes:
                ticket(code).bull()

    except:
        text_list = ['คุณ {} รอสักครู่นะคะ กำลังค้นหา {} ในฐานข้อมูล'.format(disname, text_from_user),
            '{} สะกด {} ไม่ถูกต้อง ลองใหม่อีกครั้ง'.format(disname, text_from_user),]

        from random import choice
        word_to_reply = choice(text_list)
        text_to_reply = TextSendMessage(text = word_to_reply)
        line_bot_api.reply_message(event.reply_token,messages=[text_to_reply])
예제 #7
0
def handle_message(event):
    text_from_user = event.message.text
    reply_token = event.reply_token
    userid = event.source.user_id

    disname = line_bot_api.get_profile(user_id=userid).display_name
    request_text = ('ticket' + '\n' + '>> {} : {}').format(
        disname, text_from_user)
    print(request_text)
    linechat(request_text)

    result_from_dialogflow = detect_intent_texts(
        project_id="worldstock-iardyn",
        session_id=userid,
        text=text_from_user,
        language_code="th")

    action = result_from_dialogflow["action"]
    response = result_from_dialogflow["fulfillment_messages"]  #as list

    print("action : " + action)
    print("response : " + str(response))

    try:
        if 'Hello Bot' in text_from_user:
            text_list = [
                'สวัสดีจ้า คุณ {} '.format(disname),
                'สวัสดีจ้า คุณ {} วันนี้จะเล่นตัวไหนดี'.format(disname),
            ]

            from random import choice
            word_to_reply = choice(text_list)
            text_to_reply = TextSendMessage(text=word_to_reply)
            line_bot_api.reply_message(event.reply_token,
                                       messages=[text_to_reply])
            return 'OK'

        elif 'IQUSTB' in text_from_user:
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup

            def thbscrapt():

                req = Request('https://th.investing.com/currencies/usd-thb',
                              headers={'User-Agent': 'Chrome/78.0'})
                webopen = urlopen(req).read()
                data = soup(webopen, 'html.parser')

                thb_now = data.findAll('div',
                                       {'class': 'top bold inlineblock'})
                thb_now = thb_now[0].text
                thb_now = thb_now.replace('\n', ' ')
                thb_now = thb_now.replace(',', '')
                thb_now = thb_now.replace(' ', '')
                thb_now = thb_now.replace('\xa0', '')
                thb_now = thb_now[0:6]

                thb_chg = data.findAll('div',
                                       {'class': 'top bold inlineblock'})
                thb_chg = thb_chg[0].text
                thb_chg = thb_chg.replace('\n', ' ')
                thb_chg = thb_chg.replace(',', '')
                thb_chg = thb_chg.replace(' ', '')
                thb_chg = thb_chg.replace('\xa0', '')
                thb_chg = thb_chg[6:12]

                thb_pchg = data.findAll('div',
                                        {'class': 'top bold inlineblock'})
                thb_pchg = thb_pchg[0].text
                thb_pchg = thb_pchg.replace('\n', ' ')
                thb_pchg = thb_pchg.replace(',', '')
                thb_pchg = thb_pchg.replace(' ', '')
                thb_pchg = thb_pchg.replace('\xa0', '')
                thb_pchg = thb_pchg[13:18]

                return [thb_now, thb_chg, thb_pchg]

            def usdcheck():
                thb = thbscrapt()

                exit_long1 = float(thb[0]) * 1.015
                exit_long1 = '%.2f' % exit_long1

                exit_long2 = float(thb[0]) * 1.03
                exit_long2 = '%.2f' % exit_long2

                exit_long3 = float(thb[0]) * 1.045
                exit_long3 = '%.2f' % exit_long3

                exit_short1 = float(thb[0]) * 0.985
                exit_short1 = '%.2f' % exit_short1

                exit_short2 = float(thb[0]) * 0.97
                exit_short2 = '%.2f' % exit_short2

                exit_short3 = float(thb[0]) * 0.955
                exit_short3 = '%.2f' % exit_short3

                LongY = float(IQUSTB) * 1.005
                LongY = '%.2f' % LongY

                stop_longY = float(IQUSTB) * 0.995
                stop_longY = '%.2f' % stop_longY

                shortY = float(IQUSTB) * 0.995
                shortY = '%.2f' % shortY

                stop_shortY = float(IQUSTB) * 1.005
                stop_shortY = '%.2f' % stop_shortY

                price_now = float(thb[0])
                price_now = '%.2f' % price_now
                price_now = str(price_now)

                barM = float(price_now) - float(IQUSTB)
                chgp = str(thb[2])

                text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                alert1 = 'Long'
                alert2 = 'Short'

                text = text_from_user
                change = str(thb[1])

                if barM >= 0:
                    notice = alert1
                    start = IQUSTB
                    buy = LongY
                    stop = stop_longY
                    target = text1
                    number = '1'
                else:
                    notice = alert2
                    start = IQUSTB
                    buy = shortY
                    stop = stop_shortY
                    target = text2
                    number = '2'

                word_to_reply = '{}'.format(
                    text) + '\n' + 'now {} {} ({}%)'.format(
                        price_now, change, chgp)
                result = 'Position: {}'.format(
                    notice) + '\n' + 'Range: {} - {} '.format(
                        start, buy) + '\n' + 'Stop: {}'.format(
                            stop) + '\n' + 'Target: {}'.format(target)
                linechat(word_to_reply)
                print(number)

                bubble = flex_usdcheck(text, price_now, change, chgp, notice,
                                       start, buy, stop, target)
                flex_to_reply = SetMessage_Object(bubble)
                reply_msg(reply_token,
                          data=flex_to_reply,
                          bot_access_key=channel_access_token)
                return 'OK'

            usdcheck()

        elif 'IQXGL' in text_from_user:
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup

            def goldscrapt():
                req = Request('https://investing.com/currencies/xau-usd',
                              headers={'User-Agent': 'Chrome/78.0'})
                webopen = urlopen(req).read()
                data = soup(webopen, 'html.parser')

                gold_now = data.findAll('div',
                                        {'class': 'top bold inlineblock'})
                gold_now = gold_now[0].text
                gold_now = gold_now.replace('\n', ' ')
                gold_now = gold_now.replace(',', '')
                gold_now = gold_now[1:]
                gold_now = gold_now[0:8]

                goldchange = data.findAll('div',
                                          {'class': 'top bold inlineblock'})
                goldchange = goldchange[0].text
                goldchange = goldchange.replace('\n', ' ')
                goldchange = goldchange.replace(',', '')
                goldchange = goldchange[9:]
                goldchange = goldchange[0:5]

                chgp = data.findAll('div', {'class': 'top bold inlineblock'})
                chgp = chgp[0].text
                chgp = chgp.replace('\n', ' ')
                chgp = chgp.replace(',', '')
                chgp = chgp[18:]

                return [gold_now, goldchange, chgp]

            def goldcheck():
                gg = goldscrapt()

                exit_long1 = float(gg[0]) * 1.015
                exit_long1 = '%.2f' % exit_long1

                exit_long2 = float(gg[0]) * 1.03
                exit_long2 = '%.2f' % exit_long2

                exit_long3 = float(gg[0]) * 1.045
                exit_long3 = '%.2f' % exit_long3

                exit_short1 = float(gg[0]) * 0.985
                exit_short1 = '%.2f' % exit_short1

                exit_short2 = float(gg[0]) * 0.97
                exit_short2 = '%.2f' % exit_short2

                exit_short3 = float(gg[0]) * 0.955
                exit_short3 = '%.2f' % exit_short3

                LongY = float(IQXGL) * 1.005
                LongY = '%.2f' % LongY

                stop_longY = float(IQXGL) * 0.995
                stop_longY = '%.2f' % stop_longY

                shortY = float(IQXGL) * 0.995
                shortY = '%.2f' % shortY

                stop_shortY = float(IQXGL) * 1.005
                stop_shortY = '%.2f' % stop_shortY

                price_now = float(gg[0])
                price_now = '%.2f' % price_now
                price_now = str(price_now)

                barM = float(price_now) - float(IQXGL)
                chgp = str(gg[2])

                text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                alert1 = 'Long'
                alert2 = 'Short'

                text = text_from_user
                change = str(gg[1])

                if barM >= 0:
                    notice = alert1
                    start = IQXGL
                    buy = LongY
                    stop = stop_longY
                    target = text1
                    number = '1'
                else:
                    notice = alert2
                    start = IQXGL
                    buy = shortY
                    stop = stop_shortY
                    target = text2
                    number = '2'

                word_to_reply = '{}'.format(
                    text) + '\n' + 'now {} {} ({}%)'.format(
                        price_now, change, chgp)
                result = 'Position: {}'.format(
                    notice) + '\n' + 'Range: {} - {} '.format(
                        start, buy) + '\n' + 'Stop: {}'.format(
                            stop) + '\n' + 'Target: {}'.format(target)
                linechat(word_to_reply)
                bubble = flex_goldcheck(text, price_now, change, chgp, notice,
                                        start, buy, stop, target)

                flex_to_reply = SetMessage_Object(bubble)
                reply_msg(reply_token,
                          data=flex_to_reply,
                          bot_access_key=channel_access_token)
                return 'OK'

            goldcheck()

        elif 'IQXBRT' in text_from_user:
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup

            def wtiscrapt():
                req = Request(
                    'https://www.investing.com/commodities/brent-oil',
                    headers={'User-Agent': 'Chrome/78.0'})
                webopen = urlopen(req).read()
                data = soup(webopen, 'html.parser')

                wti_now = data.findAll('div',
                                       {'class': 'top bold inlineblock'})
                wti_now = wti_now[0].text
                wti_now = wti_now.replace('\n', ' ')
                wti_now = wti_now.replace(',', '')
                wti_now = wti_now[1:]
                wti_now = wti_now[0:6]

                wtichange = data.findAll('div',
                                         {'class': 'top bold inlineblock'})
                wtichange = wtichange[0].text
                wtichange = wtichange.replace('\n', ' ')
                wtichange = wtichange.replace(',', '')
                wtichange = wtichange[1:]
                wtichange = wtichange[6:11]

                chgp = data.findAll('div', {'class': 'top bold inlineblock'})
                chgp = chgp[0].text
                chgp = chgp.replace('\n', ' ')
                chgp = chgp.replace(',', '')
                chgp = chgp[16:]
                return [wti_now, wtichange, chgp]

            def wticheck():
                wti = wtiscrapt()

                exit_long1 = float(wti[0]) * 1.04
                exit_long1 = '%.2f' % exit_long1

                exit_long2 = float(wti[0]) * 1.08
                exit_long2 = '%.2f' % exit_long2

                exit_long3 = float(wti[0]) * 1.12
                exit_long3 = '%.2f' % exit_long3

                exit_short1 = float(wti[0]) * 0.96
                exit_short1 = '%.2f' % exit_short1

                exit_short2 = float(wti[0]) * 0.92
                exit_short2 = '%.2f' % exit_short2

                exit_short3 = float(wti[0]) * 0.88
                exit_short3 = '%.2f' % exit_short3

                LongY = float(IQXBRT) * 1.01
                LongY = '%.2f' % LongY

                stop_longY = float(IQXBRT) * 0.985
                stop_longY = '%.2f' % stop_longY

                shortY = float(IQXBRT) * 0.985
                shortY = '%.2f' % shortY

                stop_shortY = float(IQXBRT) * 1.01
                stop_shortY = '%.2f' % stop_shortY

                price_now = float(wti[0])
                price_now = '%.2f' % price_now
                price_now = str(price_now)

                barQ = float(price_now) - float(IQXBRT)
                chgp = str(wti[2])

                text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                alert1 = 'Long'
                alert2 = 'Short'

                text = text_from_user
                change = str(wti[1])

                if barQ >= 0:
                    notice = alert1
                    start = IQXBRT
                    buy = LongY
                    stop = stop_longY
                    target = text1
                    number = '1'
                else:
                    notice = alert2
                    start = IQXBRT
                    buy = shortY
                    stop = stop_shortY
                    target = text2
                    number = '2'

                word_to_reply = '{}'.format(
                    text) + '\n' + 'now {} {} ({}%)'.format(
                        price_now, change, chgp)
                result = 'Position: {}'.format(
                    notice) + '\n' + 'Range: {} - {} '.format(
                        start, buy) + '\n' + 'Stop: {}'.format(
                            stop) + '\n' + 'Target: {}'.format(target)
                linechat(word_to_reply)
                bubble = flex_wticheck(text, price_now, change, chgp, notice,
                                       start, buy, stop, target)

                flex_to_reply = SetMessage_Object(bubble)
                reply_msg(reply_token,
                          data=flex_to_reply,
                          bot_access_key=channel_access_token)
                return 'OK'

            wticheck()

        elif 'TFEX' in text_from_user:
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup

            def tfexupdate():

                req = Request(
                    'https://www.tfex.co.th/tfex/dailySeriesQuotation.html?locale=th_TH&symbol={}'
                    .format(tfex_code),
                    headers={'User-Agent': 'Chrome/78.0'})
                webopen = urlopen(req).read()
                data = soup(webopen, 'html.parser')
                main = data.findAll('span', {'class': 'h2'})

                tx = main[0].text
                tx = tx.replace('\n', '')
                tx = tx.replace('\r', '')
                tx = tx.replace(' ', '')
                tx = tx.replace(',', '')

                sub = data.findAll('span', {'class': 'h3'})
                ux = sub[0].text
                ux = ux.replace('\n', '')
                ux = ux.replace('\r', '')
                ux = ux.replace(' ', '')

                cx = sub[1].text
                cx = cx.replace('\n', '')
                cx = cx.replace('\r', '')
                cx = cx.replace(' ', '')
                cx = cx.replace(')', '')
                cx = cx.replace('(', '')
                return [tx, ux, cx]

            def tfexcheck():
                tff = tfexupdate()

                exit_long1 = float(tff[0]) * 1.04
                exit_long1 = '%.2f' % exit_long1

                exit_long2 = float(tff[0]) * 1.08
                exit_long2 = '%.2f' % exit_long2

                exit_long3 = float(tff[0]) * 1.12
                exit_long3 = '%.2f' % exit_long3

                exit_short1 = float(tff[0]) * 0.96
                exit_short1 = '%.2f' % exit_short1

                exit_short2 = float(tff[0]) * 0.92
                exit_short2 = '%.2f' % exit_short2

                exit_short3 = float(tff[0]) * 0.88
                exit_short3 = '%.2f' % exit_short3

                LongY = float(tfex_value) * 1.005
                LongY = '%.2f' % LongY

                stop_longY = float(tfex_value) * 0.995
                stop_longY = '%.2f' % stop_longY

                shortY = float(tfex_value) * 0.995
                shortY = '%.2f' % shortY

                stop_shortY = float(tfex_value) * 1.005
                stop_shortY = '%.2f' % stop_shortY

                price_now = float(tff[0])
                price_now = '%.2f' % price_now
                price_now = str(price_now)

                barM = float(price_now) - float(tfex_value)
                chgp = str(tff[2])

                text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                alert1 = 'Long'
                alert2 = 'Short'

                text = '{}'.format(tfex_code)
                change = str(tff[1])

                if barM >= 0:
                    notice = alert1
                    start = tfex_value
                    buy = LongY
                    stop = stop_longY
                    target = text1
                    number = '11'
                else:
                    notice = alert2
                    start = tfex_value
                    buy = shortY
                    stop = stop_shortY
                    target = text2
                    number = '22'

                word_to_reply = '{}'.format(
                    text) + '\n' + 'now {} {} ({}%)'.format(
                        price_now, change, chgp)
                result = 'Position: {}'.format(
                    notice) + '\n' + 'Range: {} - {} '.format(
                        start, buy) + '\n' + 'Stop: {}'.format(
                            stop) + '\n' + 'Target: {}'.format(target)
                linechat(word_to_reply)

                bubble = flex_tfexcheck(text, price_now, change, chgp, notice,
                                        start, buy, stop, target)

                flex_to_reply = SetMessage_Object(bubble)
                reply_msg(reply_token,
                          data=flex_to_reply,
                          bot_access_key=channel_access_token)
                return 'OK'

            tfexcheck()

        elif 'SET' in text_from_user:
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup

            def setscrapt():
                req = Request('https://www.investing.com/indices/thailand-set',
                              headers={'User-Agent': 'Chrome/78.0'})
                webopen = urlopen(req).read()
                data = soup(webopen, 'html.parser')

                set_now = data.findAll('div',
                                       {'class': 'top bold inlineblock'})
                set_now = set_now[0].text
                set_now = set_now.replace('\n', ' ')
                set_now = set_now.replace(',', '')
                set_now = set_now.replace(' ', '')
                set_now = set_now.replace('\xa0', '')
                set_now = set_now[0:7]

                set_chg = data.findAll('div',
                                       {'class': 'top bold inlineblock'})
                set_chg = set_chg[0].text
                set_chg = set_chg.replace('\n', ' ')
                set_chg = set_chg.replace(',', '')
                set_chg = set_chg.replace(' ', '')
                set_chg = set_chg.replace('\xa0', '')
                set_chg = set_chg[7:13]

                set_pchg = data.findAll('div',
                                        {'class': 'top bold inlineblock'})
                set_pchg = set_pchg[0].text
                set_pchg = set_pchg.replace('\n', ' ')
                set_pchg = set_pchg.replace(',', '')
                set_pchg = set_pchg.replace(' ', '')
                set_pchg = set_pchg.replace('\xa0', '')
                set_pchg = set_pchg[14:20]

                return [set_now, set_chg, set_pchg]

            def setcheck():
                st = setscrapt()

                price_now = float(st[0])
                price_now = '%.2f' % price_now
                price_now = str(price_now)

                change = str(st[1])
                chgp = str(st[2])

                exit_long1 = float(price_now) * 1.05
                exit_long1 = '%.2f' % exit_long1

                exit_long2 = float(price_now) * 1.10
                exit_long2 = '%.2f' % exit_long2

                exit_long3 = float(price_now) * 1.20
                exit_long3 = '%.2f' % exit_long3

                exit_short1 = float(price_now) * 0.95
                exit_short1 = '%.2f' % exit_short1

                exit_short2 = float(price_now) * 0.90
                exit_short2 = '%.2f' % exit_short2

                exit_short3 = float(price_now) * 0.80
                exit_short3 = '%.2f' % exit_short3

                LongY = float(set_value) * 1.005
                LongY = '%.2f' % LongY

                stop_longY = float(set_value) * 0.995
                stop_longY = '%.2f' % stop_longY

                shortY = float(set_value) * 0.995
                shortY = '%.2f' % shortY

                stop_shortY = float(set_value) * 1.005
                stop_shortY = '%.2f' % stop_shortY

                barQ = float(price_now) - float(set_value)
                barQ = float(barQ)

                text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                alert1 = 'Long'
                alert2 = 'Short'

                text = text_from_user

                if barQ >= 0:
                    notice = alert1
                    start = set_value
                    buy = LongY
                    stop = stop_longY
                    target = text1
                    number = '1'
                else:
                    notice = alert2
                    start = set_value
                    buy = shortY
                    stop = stop_shortY
                    target = text2
                    number = '2'

                word_to_reply = '{}'.format(
                    text) + '\n' + 'now {} {} ({}%)'.format(
                        price_now, change, chgp)
                result = 'Position: {}'.format(
                    notice) + '\n' + 'Range: {} - {} '.format(
                        start, buy) + '\n' + 'Stop: {}'.format(
                            stop) + '\n' + 'Target: {}'.format(target)
                linechat(word_to_reply)
                bubble = flex_setcheck(text, price_now, change, chgp, notice,
                                       start, buy, stop, target)

                flex_to_reply = SetMessage_Object(bubble)
                reply_msg(reply_token,
                          data=flex_to_reply,
                          bot_access_key=channel_access_token)
                return 'OK'

            setcheck()

        elif action == "crypto_response":
            from urllib.request import Request, urlopen
            from bs4 import BeautifulSoup as soup
            from pandas_datareader import data
            from datetime import datetime

            text_from_user = text_from_user.upper()
            code = [text_from_user]
            codes = list(map(lambda e: e + '-USD', code))

            class crypto:
                def __init__(self, code):
                    self.code = code

                def ticket(self):
                    end = datetime.now()
                    start = datetime(end.year, end.month, end.day)
                    list = self.code

                    dfY = data.DataReader(f'{list}',
                                          data_source="yahoo",
                                          start=yearly,
                                          end=end)
                    dfM = data.DataReader(f'{list}',
                                          data_source="yahoo",
                                          start=monthly,
                                          end=end)
                    #2020-01-01 = Y M D

                    OpenY = dfY['Open'].iloc[1]
                    OpenY = '%.2f' % OpenY
                    OpenY = str(OpenY)

                    OpenM = dfM['Open'].iloc[1]
                    OpenM = '%.2f' % OpenM
                    OpenM = str(OpenM)

                    OpenD = dfY['Open'].iloc[-1]
                    OpenD = '%.2f' % OpenD
                    OpenD = str(OpenD)

                    Close = dfY['Close'].iloc[-1]
                    Close = '%.2f' % Close
                    Close = str(Close)

                    Prev = dfY['Close'].iloc[-2]
                    Prev = '%.2f' % Prev
                    Prev = str(Prev)

                    barY = ((float(Close) - float(OpenY)) / float(OpenY)) * 100
                    barY = '%.2f' % barY
                    barY = float(barY)

                    barM = ((float(Close) - float(OpenM)) / float(OpenM)) * 100
                    barM = '%.2f' % barM
                    barM = float(barM)

                    LongY = float(OpenM) * 1.01
                    LongY = '%.2f' % LongY
                    LongY = str(LongY)

                    stop_longY = float(OpenM) * 0.985
                    stop_longY = '%.2f' % stop_longY
                    stop_longY = str(stop_longY)

                    exit_long1 = float(OpenD) * 1.05
                    exit_long1 = '%.2f' % exit_long1
                    exit_long1 = str(exit_long1)

                    exit_long2 = float(OpenD) * 1.10
                    exit_long2 = '%.2f' % exit_long2
                    exit_long2 = str(exit_long2)

                    exit_long3 = float(OpenD) * 1.20
                    exit_long3 = '%.2f' % exit_long3
                    exit_long3 = str(exit_long3)

                    shortY = float(OpenM) * 0.985
                    shortY = '%.2f' % shortY
                    shortY = str(shortY)

                    stop_shortY = float(OpenM) * 1.01
                    stop_shortY = '%.2f' % stop_shortY
                    stop_shortY = str(stop_shortY)

                    exit_short1 = float(OpenD) * 0.95
                    exit_short1 = '%.2f' % exit_short1
                    exit_short1 = str(exit_short1)

                    exit_short2 = float(OpenD) * 0.90
                    exit_short2 = '%.2f' % exit_short2
                    exit_short2 = str(exit_short2)

                    exit_short3 = float(OpenD) * 0.80
                    exit_short3 = '%.2f' % exit_short3
                    exit_short3 = str(exit_short3)

                    change = float(Close) - float(Prev)
                    change = '%.2f' % change
                    change = str(change)

                    chgp = (float(change) / float(Prev)) * 100
                    chgp = '%.2f' % chgp
                    chgp = str(chgp)

                    text1 = exit_long1 + ' | ' + exit_long2 + ' | ' + exit_long3
                    text2 = exit_short1 + ' | ' + exit_short2 + ' | ' + exit_short3

                    alert1 = 'Long'
                    alert2 = 'Short'

                    text = code
                    price_now = float(Close)
                    change = str(change)

                    if barM >= 0:
                        notice = alert1
                        start = OpenM
                        buy = LongY
                        stop = stop_longY
                        target = text1
                        number = '1'
                    else:
                        notice = alert2
                        start = OpenM
                        buy = shortY
                        stop = stop_shortY
                        target = text2
                        number = '2'

                    word_to_reply = '{}'.format(
                        text) + '\n' + 'now {} {} ({}%)'.format(
                            price_now, change, chgp)
                    result = 'Position: {}'.format(
                        notice) + '\n' + 'Range: {} - {} '.format(
                            start, buy) + '\n' + 'Stop: {}'.format(
                                stop) + '\n' + 'Target: {}'.format(target)
                    linechat(word_to_reply)

                    bubble = flex_crypto(text, price_now, change, chgp, notice,
                                         start, buy, stop, target)

                    flex_to_reply = SetMessage_Object(bubble)
                    reply_msg(reply_token,
                              data=flex_to_reply,
                              bot_access_key=channel_access_token)
                    return 'OK'

            for code in codes:
                crypto(code).ticket()

        else:
            from bs4 import BeautifulSoup as soup
            from urllib.request import urlopen as req
            from pandas_datareader import data
            from datetime import datetime, date

            code = text_from_user
            ticket = [text_from_user]
            symbols = list(map(lambda e: e + '.bk', ticket))

            def request(code):
                url = 'https://www.settrade.com/C04_02_stock_historical_p1.jsp?txtSymbol={}&ssoPageId=10&selectPage=2'.format(
                    code)
                webopen = req(url)
                page_html = webopen.read()
                webopen.close()

                data = soup(page_html, 'html.parser')
                price = data.findAll('div', {'class': 'col-xs-6'})
                title = price[0].text
                stockprice = price[2].text

                change = price[3].text
                change = change.replace('\n', '')
                change = change.replace('\r', '')
                change = change.replace('\t', '')
                change = change.replace(' ', '')
                change = change[11:]

                pchange = price[4].text
                pchange = pchange.replace('\n', '')
                pchange = pchange.replace('\r', '')
                pchange = pchange.replace(' ', '')
                pchange = pchange[12:]

                update = data.findAll('span', {'class': 'stt-remark'})
                stockupdate = update[0].text
                stockupdate = stockupdate[13:]
                return [title, stockprice, change, pchange, stockupdate]

            r = request(code)

            class stock:
                def __init__(self, stock):
                    self.stock = stock

                def ticket(self):
                    end = datetime.now()
                    start = datetime(end.year, end.month, end.day)
                    list = self.stock

                    dfY = data.DataReader(f'{list}',
                                          data_source="yahoo",
                                          start=yearly,
                                          end=end)
                    dfQ = data.DataReader(f'{list}',
                                          data_source="yahoo",
                                          start=quarter,
                                          end=end)
                    dfM = data.DataReader(f'{list}',
                                          data_source="yahoo",
                                          start=monthly,
                                          end=end)
                    list = list.replace('.bk', '')

                    OpenY = dfY['Open'].iloc[0]
                    OpenY = '%.2f' % OpenY
                    OpenY = str(OpenY)

                    OpenQ = dfQ['Open'].iloc[0]
                    OpenQ = '%.2f' % OpenQ
                    OpenQ = str(OpenQ)

                    p_openQ = (
                        (float(OpenQ) - float(OpenY)) / float(OpenY)) * 100
                    p_openQ = '%.2f' % p_openQ
                    p_openQ = str(p_openQ)

                    OpenM = dfM['Open'].iloc[0]
                    OpenM = '%.2f' % OpenM
                    OpenM = str(OpenM)

                    Close = float(f'{r[1]}')
                    Close = '%.2f' % Close
                    Close = str(Close)

                    barY = ((float(Close) - float(OpenY)) / float(OpenY)) * 100
                    barY = '%.2f' % barY
                    barY = float(barY)

                    barQ = ((float(Close) - float(OpenQ)) / float(OpenQ)) * 100
                    barQ = '%.2f' % barQ
                    barQ = float(barQ)

                    barM = ((float(Close) - float(OpenM)) / float(OpenM)) * 100
                    barM = '%.2f' % barM
                    barM = float(barM)

                    Volume1 = dfY['Volume'].iloc[-1]
                    Volume2 = dfY['Volume'].iloc[-2]

                    Volume = (float(Volume1) + float(Volume2)) / 2
                    Volume = '%.0f' % Volume
                    Volume = str(Volume)

                    value = float(Volume) * float(Close)
                    value = '%.2f' % value
                    value = str(value)

                    request_val = float(value)
                    request_val = '{:,.0f}'.format(request_val)
                    request_val = str(request_val)

                    exit1 = float(OpenQ) * 1.20
                    exit1 = '%.2f' % exit1
                    exit1 = str(exit1)

                    exit2 = float(OpenQ) * 1.40
                    exit2 = '%.2f' % exit2
                    exit2 = str(exit2)

                    exit3 = float(OpenQ) * 1.60
                    exit3 = '%.2f' % exit3
                    exit3 = str(exit3)

                    buyQ = float(OpenQ) * 1.02
                    buyQ = '%.2f' % buyQ
                    buyQ = str(buyQ)

                    stopQ = float(OpenQ) * 0.98
                    stopQ = '%.2f' % stopQ
                    stopQ = str(stopQ)

                    buyY = float(OpenY) * 1.02
                    buyY = '%.2f' % buyY
                    buyY = str(buyY)

                    stopY = float(OpenY) * 0.98
                    stopY = '%.2f' % stopY
                    stopY = str(stopY)

                    max_value = dfY.nlargest(1, columns='High')
                    max_value = max_value['High'].iloc[0]
                    max_value = '%.2f' % max_value
                    max_value = str(max_value)

                    max_valueQ = dfQ.nlargest(1, columns='High')
                    max_valueQ = max_valueQ['High'].iloc[0]
                    max_valueQ = '%.2f' % max_valueQ
                    max_valueQ = str(max_valueQ)

                    pmax_valueQ = ((float(max_valueQ) - float(OpenQ)) /
                                   float(OpenQ)) * 100
                    pmax_valueQ = '%.2f' % pmax_valueQ
                    pmax_valueQ = str(pmax_valueQ)

                    min_value = dfY.nsmallest(1, columns='Low')
                    min_value = min_value['Low'].iloc[0]
                    min_value = '%.2f' % min_value
                    min_value = str(min_value)

                    pmin_value = (
                        (float(min_value) - float(OpenY)) / float(OpenY)) * 100
                    pmin_value = '%.2f' % pmin_value
                    pmin_value = str(pmin_value)

                    support1 = float(OpenY) * 0.80
                    support1 = '%.2f' % support1
                    support1 = str(support1)

                    support2 = float(OpenY) * 0.70
                    support2 = '%.2f' % support2
                    support2 = str(support2)

                    support3 = float(OpenY) * 0.60
                    support3 = '%.2f' % support3
                    support3 = str(support3)

                    textY = exit1 + ' | ' + exit2 + ' | ' + exit3
                    textQ = exit1 + ' | ' + exit2 + ' | ' + exit3
                    text2 = support3 + ' | ' + support2 + ' | ' + support1

                    alert1 = 'ชนแนวต้าน'
                    alert2 = 'ไปต่อ'
                    alert3 = 'ซื้อ'
                    alert4 = 'อย่าเพิ่งเข้า'
                    alert5 = 'กำลังย่อ'
                    alert6 = 'ห้ามพลาด'
                    alert7 = 'เด้ง'
                    alert8 = 'ลงต่อ'
                    alert9 = 'Vol น้อย'

                    text = r[0]
                    price_now = r[1]
                    change = r[2]
                    chgp = str(r[3])
                    re_avg = '{}%'.format(barQ) + '\n' + 'H {} L {}'.format(
                        max_valueQ, min_value)

                    if float(value) > 7500000:
                        if barY >= 0.00:
                            if 0.00 < barY < 10.00:
                                notice = alert6
                                start = OpenY
                                buy = buyY
                                stop = stopY
                                target = textY
                                avg = re_avg
                            elif barQ > 12.00:
                                notice = alert1
                                start = OpenQ
                                buy = buyQ
                                stop = stopQ
                                target = textQ
                                avg = re_avg
                            elif barQ >= 0.00:
                                if barM >= 0.00:
                                    notice = alert3
                                    start = OpenQ
                                    buy = buyQ
                                    stop = stopQ
                                    target = textQ
                                    avg = re_avg
                                else:
                                    notice = alert5
                                    start = OpenQ
                                    buy = buyQ
                                    stop = stopQ
                                    target = textQ
                                    avg = re_avg
                            else:
                                notice = alert4
                                start = OpenQ
                                buy = buyQ
                                stop = stopQ
                                target = textQ
                                avg = re_avg
                        else:
                            if barQ >= 0.00:
                                if barM >= 0.00:
                                    notice = alert3
                                    start = OpenQ
                                    buy = buyQ
                                    stop = text2
                                    target = textQ
                                    avg = re_avg
                                else:
                                    notice = alert5
                                    start = OpenQ
                                    buy = buyQ
                                    stop = text2
                                    target = textQ
                                    avg = re_avg
                            else:
                                notice = alert8
                                start = OpenQ
                                buy = buyQ
                                stop = text2
                                target = textQ
                                avg = re_avg
                    else:
                        notice = alert9
                        start = OpenQ
                        buy = buyQ
                        stop = text2
                        target = textQ
                        avg = re_avg

                    word_to_reply = str('{} {}'.format(text, notice))
                    linechat(word_to_reply)

                    bubbles = []
                    bubble = flex_stock(text, price_now, change, chgp, notice,
                                        start, buy, stop, target, avg)

                    flex_to_reply = SetMessage_Object(bubble)
                    reply_msg(reply_token,
                              data=flex_to_reply,
                              bot_access_key=channel_access_token)
                    return 'OK'

            for symbol in symbols:
                stock(symbol).ticket()

    except:
        text_list = [
            'คุณ {} รอสักครู่นะคะ กำลังค้นหา {} ในฐานข้อมูล'.format(
                disname, text_from_user),
            '{} สะกด {} ไม่ถูกต้อง ลองใหม่อีกครั้ง'.format(
                disname, text_from_user),
        ]

        from random import choice
        word_to_reply = choice(text_list)
        text_to_reply = TextSendMessage(text=word_to_reply)
        line_bot_api.reply_message(event.reply_token, messages=[text_to_reply])