Example #1
0
def init():
    global page
    TABOT_ACCESS_TOKEN = "EAANbYW2bhcwBAHprKcgSrs86S3MFVdVv37auFZBAo4EPzAMTjKNDQuLj9227ai1Agbryvs2QXcHQgf7vHs2Xv0YynvT7XDo4wPAjSHabFyvbJVQfkUkZCJP7PZBRZBcLctaT7MG0aDSJDFZCBbnxcfR8KB48i9YAWLiIAmSmRevoiIfLGWUIY"
    page = Page(TABOT_ACCESS_TOKEN)
    page.show_starting_button("GET_START")
    page.greeting(
        "Hi {{user_first_name}}! TaBot is Messenger Bot to help you know more about Celcom Prepaid Package. Let's Get Started!"
    )
    page.show_persistent_menu([
        Template.ButtonPostBack("Available command ⚛️", 'COMMAND'),
        Template.ButtonWeb("Celcom website 📱", "https://www.celcom.com.my"),
        Template.ButtonPostBack("tabot", 'START')
    ])
Example #2
0
from flask import Flask, request

from src.CONFIG import CONFIG
from src.helper import *

chatterbot = ChatBot("Training Example")
chatterbot.set_trainer(ChatterBotCorpusTrainer)

app = Flask(__name__)
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
VERIFY_TOKEN = os.environ['VERIFY_TOKEN']
page = Page(ACCESS_TOKEN)

raw_data, data, developers_data, team_udaan_data = prepare_data()
zipped = map_icon_list()
page.show_starting_button("START_PAYLOAD")

page.show_persistent_menu([
    Template.ButtonPostBack('Information', 'PMENU_' + 'Information'),
    Template.ButtonPostBack('Reach Us', 'PMENU_' + 'map')
])


@page.callback(['START_PAYLOAD'])
def start_callback(payload, event):
    page.send(
        event.sender_id,
        "Welcome to Udaan 2018! Write down info to get information about various events."
    )
    page.send(
        event.sender_id,
    elif payload == 'REFRESH':
        text = '你希望想擁有的信用卡特色?'
        page.send(sender_id, text, quick_replies=[{'title': '高額現金回饋', 'payload': 'cash'},
                                                  {'title': '旅遊交通', 'payload': 'traffic'},
                                                  {'title': '休閒娛樂', 'payload': 'entertain'},
                                                  {'title': '購物', 'payload': 'shopping'},
                                                  {'title': '電子支付功能(悠遊卡、一卡通)', 'payload': 'easycard'},
                                                  {'title': '宗教', 'payload': 'religion'}])
    ## 當使用者按下卡片中的'詳細資訊'時
    else:
        page.send(sender_id, card_detail(payload))

########################################################
## 設置起始按鈕與常駐選單
page.greeting('我們是一群致力於讓各位elite成為卡奴的學生,想變卡奴找我們準沒錯!')
page.show_starting_button('START')
page.show_persistent_menu([Template.ButtonPostBack('重新查詢', 'REFRESH'),
                           Template.ButtonWeb('前往此網頁以獲得更多資訊', 'https://money101.com.tw'),
                           Template.ButtonWeb('讓你看看我們的資料庫!', 'https://github.com/chrisyang-tw/PBC_Final/blob/master/data.csv')])

########################################################
## 訊息傳送與判斷
@page.handle_message
def message_handler(event):
    sender_id = event.sender_id
    message = event.message_text

    ## 讓機器人在使用者傳送訊息後立刻已讀訊息並開啟輸入指示器(點點點符號)
    page.mark_seen(sender_id)
    page.typing_on(sender_id)
    
Example #4
0
"""     C O N S T A N T S  """
PAGE_ACCESS_TOKEN = "EAAkxYspVIqgBANJbHTxnhLPX4SPWcHvJtolWFmyeZBhOI1vO6G4BAghOXJyH6ZCuUiCKs9vdmjD3xy3Gz5GfTqIxIdjxPW2TUUWNWnRNBQvl2cjSr1G1qv8k9QP8WmmvSELSUSKcWGfsyPIIQ4RDtFTpR5Jc6ZCII3Y7NUfdAZDZD"
VERIFY_TOKEN = "this is the veryfy token"
"""     End Of Constants    """
"""app instance setup"""
app = Flask(__name__)
app.config[
    "SQLALCHEMY_DATABASE_URI"] = "mysql://*****:*****@localhost/bot_db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.secret_key = "horhe borhes"
""" EOF """
""" Flask_Migrate instance """
migrate = Migrate(app, db)
""" page instance setup """
page = Page(PAGE_ACCESS_TOKEN)
page.show_starting_button("GET_STARTED")
page.show_persistent_menu([
    Template.ButtonPostBack('contact info', 'PERSISTENT_CONTACT_INFO'),
    Template.ButtonWeb("MOVEONCOMPANY", "www.google.com")
])
page.greeting("Hello!")
""" EOF """
"""for modularity"""
""" EOF """


@app.route('/', methods=['POST'])
def webhook():
    """the center of all """
    data = request.get_json()
    # pprint(data)  #FIXME: remove this line from production
Example #5
0
class FacebookClient(BotAPIClient):
    """
    Facebook Messenger Bot API client
    """

    def __init__(self, app, token):
        self._app = app
        self._token = token

        # Set in `initialize()`
        self._page = None  # type: Page

        self._error_handler = None  # type: Callable[Exception]
        self._plaintext_handlers = []  # type: List[Callable[Event]]
        self._voice_handlers = []  # type: List[Callable[Event]]
        self._media_handlers = []  # type: List[Callable[Event]]

    @property
    def client_name(self):
        return 'facebook'

    def unify_update(self, event: Event, payload: str = None) -> Update:
        """
        Create the internal `Update` type from facebook's `Event`
        """
        ud = Update()
        ud.original_update = event
        ud.client_name = self.client_name
        ud.message_id = event.message_mid
        ud.datetime = datetime.datetime.fromtimestamp(event.timestamp / 1000.0)

        ud.payload = payload

        ud.user, created = User.get_or_create(facebook_id=event.sender_id)
        if created:
            ud.user.save()

        if event.message_attachments:
            try:
                voice = next(x for x in event.message_attachments if x.get('type') == 'audio')
                ud.voice_id = voice['payload']['url']
            except StopIteration:
                pass

        if hasattr(event, 'message_text'):
            ud.message_text = event.message_text
        return ud

    def initialize(self):
        self._page = Page(self._token)
        self._page.show_starting_button("START_BOT")

        # Add webhook handlers
        self._app.add_url_rule('/', 'index', self._authentication, methods=['GET'])
        self._app.add_url_rule('/', 'request', self._webhook, methods=['POST'])

        self._page.set_webhook_handler('message', self._message_handler)
        self._page.set_webhook_handler('delivery', self._delivery_handler)

    @staticmethod
    def _delivery_handler(event):
        pass
        # delivery = event.delivery
        # message_ids = delivery.get("mids")
        # watermark = delivery.get("watermark")
        # log.debug(f"Message delivered: {message_ids} ({watermark})")

    def perform_actions(self, actions: List[ChatAction]):
        """
        Executes a sequence of `ChatActions` planned by the `DialogManager`.
        This includes sending messages, showing "typing" notifications, waiting when there are delays planned,
        and adding QuickReply buttons.
        """
        for action in actions:
            try:
                user_id = action.peer.facebook_id

                if action.show_typing:
                    self.show_typing(user_id)
                if action.delay:
                    delay = action.delay.value if isinstance(action.delay, ChatAction.Delay) else action.delay
                    # Facebook bots are very slow, shorten timeout
                    time.sleep(delay * 0.3)

                quick_replies = None
                if action.action_type == ChatAction.Type.ASKING_QUESTION:
                    if action.choices:
                        quick_replies = [
                            QuickReply(
                                title=remove_emoji(x),
                                payload=f"test_{x}"
                            ) for x in action.choices[:10]]
                elif action.action_type == ChatAction.Type.SENDING_MEDIA:
                    self.send_media(action.peer, action.media_id, caption=action.render())
                    continue

                self._page.send(
                    recipient_id=user_id,
                    message=action.render(remove_html=True),
                    quick_replies=quick_replies)
            finally:
                self.end_typing(user_id)

    @staticmethod
    def _authentication():
        """
        Authentication is done when the webhook is set up in the facebook developer console
        """
        all_args = request.args
        if 'hub.challenge' in all_args:
            return all_args['hub.challenge']
        log.info("Root request: " + str(all_args))
        return ''

    def _webhook(self):
        self._page.handle_webhook(request.get_data(as_text=True))
        return "ok"

    def start_listening(self):
        pass  # Flask handles this automatically

    @staticmethod
    def stop_listening():
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            raise RuntimeError('Not running with the Werkzeug Server')
        func()

    def set_start_handler(self, callback):
        @self._page.callback(['START_BOT'])
        def start_handler(payload, event):
            callback(self, self.unify_update(event, payload))

    def _message_handler(self, event):
        for callback in self._plaintext_handlers:
            if not event.message_text:
                break
            callback(self, self.unify_update(event))
        for callback in self._voice_handlers:
            if not event.is_attachment_message:
                break
            if not any(x for x in event.message_attachments if x.get('type') == 'audio'):
                break
            callback(self, self.unify_update(event))

    def add_plaintext_handler(self, callback):
        self._plaintext_handlers.append(callback)

    def add_voice_handler(self, callback):
        self._voice_handlers.append(callback)

    def add_media_handler(self, callback):
        self._media_handlers.append(callback)

    def download_voice(self, voice_id, path):
        filepath = os.path.join(path, 'voice.mp4')
        r = requests.get(voice_id, stream=True)
        with open(filepath, 'wb') as f:
            shutil.copyfileobj(r.raw, f)
        return filepath

    def send_media(self, peer, media_id, caption):
        filepath = get_file_by_media_id(media_id)
        ext = os.path.splitext(filepath)[1]

        return  # TODO: This is broken

        # if ext == '.mp4':
        #     video_url = settings.APP_URL + f'media/video/{media_id}{ext}'
        #     print(video_url)
        #     return self._page.send(peer.facebook_id, Attachment.Video(video_url))
        # elif ext in ('.jpg', '.jpeg', '.png'):
        #     image_url = settings.APP_URL + f'media/image/{media_id}{ext}'
        #     return self._page.send(peer.facebook_id, Attachment.Image(image_url))
        # elif ext == '.webp':
        #     pass  # sticker
        #     # msg = self.bot.send_sticker(peer.telegram_id, file)
        #     # if caption:
        #     #     self.send_message(peer, caption)
        #     # return msg

    def show_typing(self, user_id):
        try:
            self._page.typing_on(user_id)
        except:
            log.error("Turning typing indication on failed.")

    def end_typing(self, user_id):
        try:
            self._page.typing_off(user_id)
        except:
            log.error("Turning typing indication off failed.")

    def add_error_handler(self, callback):
        self._error_handler = callback
Example #6
0
                            page.send(
                                sender_id,
                                "Hello je suis Wispi ton compagnon de voyage\n je suis la pour te suggérer des activitées :)\n\nTape aide pour plus d'infos"
                            )
                            continue

                        if sender_id not in BANNED_USERNAME:
                            _thread.start_new_thread(
                                handleMessage.handle,
                                (sender_id, message_text, page))
                        else:
                            alog.warning("SENDER ID IN BANNED USERNAME")
    except:
        print("Exception in user code:")
        print("-" * 20)
        traceback.print_exc(file=sys.stdout)
        print("-" * 20)
        page.send(sender_id, "Il y a eu une erreur désolé")

    return "ok", 200


if __name__ == '__main__':
    page.show_starting_button(GET_STARTED)
    # page.hide_greeting()
    page.greeting(
        "Hello je suis wispi ton compagnon de voyage\n je suis la pour te suggérer des activitées :)"
    )
    page.hide_persistent_menu()
    app.run(port=8042, debug=True)