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)
def incoming_fb_webhook(bot_key=None): """Handle a webhook from facebook.""" bot = Bot.query.filter_by(bot_key=bot_key).get_or_404() fb_key = bot.fb_key if not fb_key: return Response(status='404') page = Page(fb_key) page.handle_webhook(request.get_data(as_text=True)) return Response(status='200')
def send_bank_info(image, title, subtitle, url=None, recipient_id="1491985787521789"): page = Page(FACEBOOK_TOKEN_3) news = [] template = build_template(image=image, title=title, subtitle=subtitle, url=url) news.append(template) page.send(recipient_id, Template.Generic(news))
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') ])
def send_active_resources(recipient_id="1491985787521789"): page = Page(FACEBOOK_TOKEN_3) news = [] template = build_template( image="https://rapidpro.datos.gob.mx/media/FECHA_DE_PAGO.png", title="Proxima fecha de pago", subtitle="Te recordaremos cuando sea tu proxima fecha de pago", postback={ "text": "Fecha de pago", "content": "PAYDAY" }) news.append(template) template = build_template( image="https://rapidpro.datos.gob.mx/media/AHORRO.png", title="Ahorra", subtitle="Recibe informacion que te ayudara a ahorrar", postback={ "text": "Ahorra", "content": "SAVING" }) news.append(template) template = build_template( image="https://rapidpro.datos.gob.mx/media/BANSEFI.png", title="Bansefi mas cercano?", subtitle="Consulta tu banco mas cercano", postback={ "text": "Conoce", "content": "BANSEFI" }) news.append(template) page.send( recipient_id, Template.List(elements=news, buttons=[{ "title": "No, gracias", "type": "postback", "payload": "ss" }]))
# -*- coding: utf-8 -*- """Archivo principal para el echobot. Main File for the echobot""" from fbmq import Page from flask import Flask, request from random import choice PAGE_ACCESS_TOKEN = "EAAEyhjxiH3IBAHb3J9yzCH0ucLSC8J9EYp8yFNLnfrXGZAsI6IKbdZCZCeZBPqn6Rs8GmZA54PhNQC7wvpmeLx9em42FOZBXqcCfMfnqOmTnnOExnjijQpYr5qBL1VXJxUy10jZBsmCBAQ6fhSIiPPyLvUvLZCh3WTqMPJ4ENtQHKAZDZD" VERIFY_TOKEN = "EchoBotChido" app = Flask(__name__) page = Page(PAGE_ACCESS_TOKEN) @app.route('/') def hello_world(): """La página principal del servidor. The server main page.""" return 'Inicio del servidor' GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up", "good morning", "good afternoon", "hey") GREETING_RESPONSES = ["Welcome. ", "Hello. ", "Hi. ", "Greetings. ", "Good morning. ", "Good Afternoon. "] INFORMATION_REQUESTS_KEYWORDS = ['price', 'titan v', 'titan xp', '1080ti', '1080', '1070ti', '1070', '1060', 'delivery', 'discount'] INFORMATION_REQUESTS_RESPONSES = {'price': 'Our prices are in MXN: the Nvidia Titan V has a cost of $58,000\nTitan XP is $23,000\nGTX 1080Ti: $16,000\nGTX 1080 $13,499\nGTX 1070 Ti for only $11,499\nGTX 1070 is at $8,600\nGTX 1060 has a price of $6,200.\n', 'titan v': 'The Nvidia Titan V is our top of the line Graphics Card! Featuring a whopping 110 TeraFLOPS.\n', 'titan xp': 'Pascal architecture powers the Titan XP, along with 11.4Gbps/12GB G5X Memory and 3840 CUDA® Cores.', '1080ti': 'The GeForce® GTX 1080 Ti is NVIDIA\'s new flagship gaming GPU, based on the NVIDIA Pascal™ architecture.\n', '1080': 'The new GeForce GTX 1080 is meticulously crafted to offer superior heat dissipation using vapor chamber cooling technology and premium materials, so it runs as cool as it looks.\n', '1070ti': 'Play confortably @60+FPS, 1440p 21:9 aspect ratio on ultra settings for any game, on a very good price.\n', '1070': 'GeForce GTX 1070 graphics cards deliver the incredible speed and power of NVIDIA Pascal™, the most advanced gaming GPU architecture ever created.\n', '1060': 'The GeForce GTX 1060 6 GB Founders Edition graphics card is crafted by NVIDIA engineers with premium materials and components.\n', 'delivery': 'We have standard worldwide delivery for free!\n', 'discount': 'Our current online discounts range from 0% to 10%! Check out http://35.190.164.46:8083 for more.\n'} @app.route('/webhook', methods=['GET', 'POST']) def webhook(): """El método que se ejecuta cuando Facebook se conecta. This method executes as Facebook connect to us."""
import json import os from fbmq import Page, Template from flask import Blueprint, request, current_app, jsonify from barfinder.extensions import csrf_protect from . import facebook mod = Blueprint('chat', __name__, url_prefix='/api/chat') page = Page(os.environ.get('FB_ACCESS_TOKEN')) @page.handle_message def message_handler(event): restaurant = facebook.receive_message(event) if restaurant is None: page.send(event.sender_id, 'Sorry, I couldn\'t find a place with that ' 'description') else: page.send(event.sender_id, Template.Generic([ Template.GenericElement( restaurant.name, subtitle='\n'.join(restaurant.raw_yelp_data.get('display_address', [])), image_url=restaurant.raw_yelp_data.get('image_url'), buttons=[ Template.ButtonWeb("View in Yelp", restaurant.raw_yelp_data['url']),
from fbmq import Attachment, Page import sys import os path = os.listdir('/home')[0] sys.path.append('/home/' + path + '/github') from FBKey import host from FBChatBot import Chatbot2Sql, MessageFun, tem_function from FBChatBot.taiwan_train import TaiwanTrainRemainTicketSql_fun, search_remain_ticket from FBChatBot.taiwan_train import order_ticket, TaiwanTrainRemainTicketSql, CancelTaiwanTrainTicket from FBChatBot.taiwan_train.search_remain_ticket import station_set from FBChatBot.taiwan_train.MyTicket import MyTicket ssl_dir = '/etc/letsencrypt/live/linsam.servebeer.com/' page_access_token = MessageFun.page_access_token page = Page(page_access_token) #-------------------------------------------------------------- def chat(message_text, sender_id, recipient_id): '''if TaiwanTrainRemainTicketSql_fun.bool_sender_id_first(sender_id) != 1: print('no first') elif TaiwanTrainRemainTicketSql_fun.bool_sender_id_first(sender_id) == 1: text = '歡迎使用台鐵訂票機器人,\n以下是訂票範例' MessageFun.send_message(sender_id, text) Chatbot2Sql.update(text,sender_id,recipient_id,'server') url = "http://114.34.138.146/train_ticket_png/" image_url = url + 'train_example.png'
import traceback import json import base64 import requests import string from imp import reload from fbmq import Attachment, Template, QuickReply, Page reload(sys) import skypebot from flask import Flask, request import Tensorflow_chat_bot_response as bt import config as conf page = Page(conf.fb_access_token) app = Flask(__name__) ################################################## #skype bot client_id = conf.id_Micosoft #Microsoft ID client_secret = conf.password_Microsoft #Microsoft mot de passe bot = skypebot.SkypeBot(client_id, client_secret) @app.route('/', methods=['POST']) def webhook(): if request.method == 'POST':
# -*- coding: utf-8 -*- from flask import Flask, request from fbmq import Page, QuickReply, Attachment, Template import requests, records, re, json from flask_restful import Resource, Api token = '<auth token here>' metricsData = {} macid = 111111111111 pg = Page(token) import time db = records.Database('mysql://<user>:<password>@<url>:3306/db') app = Flask(__name__) api = Api(app) class deviceMetrics(Resource): def get(self): return { "energy": metricsData["energy"], "money_saved": metricsData["savings"], "days": metricsData["days"], "charging_status": "charging" } @app.route('/') def index(): # return str(macid) return '^_^'
import os import requests from fbmq import Page from dotenv import load_dotenv load_dotenv() page = Page(os.getenv("FB_TOKEN")) def send_message(uid, message): page.send(uid, message) def push_noti(users, message): for uid in users: send_message(uid, message)
import requests import sys import os import json import uuid from datetime import timedelta from werkzeug.exceptions import HTTPException from flask import Flask, request, render_template, redirect, url_for, Blueprint, jsonify from fbmq import Page, Template, Template, QuickReply, NotificationType from config import FACEBOOK_TOKEN, VERIFY_TOKEN, SECRET_KEY, CASA_LINK from flask_babel import Babel, refresh page = Page(FACEBOOK_TOKEN) app = Flask(__name__) errors = Blueprint('errors', __name__) data = None app.config['SECRET_KEY'] = SECRET_KEY app.permanent_session_lifetime = timedelta(minutes=10) babel = Babel(app) ctx = app.app_context() ctx.push() @babel.localeselector def get_locale(): if 'language' in request.cookies: return request.cookies.get('language') else:
from fbmq import Page from config import CONFIG page = Page(CONFIG['FACEBOOK_TOKEN'])
from bottle import route, run, request, abort, static_file import requests from fbmq import Page, Template from bs4 import BeautifulSoup from fsm import TocMachine import os ACCESS_TOKEN = "EAAcAuEo7Do8BAJPovcKLCLVUq6YRbR0m9ClabeXrGZB6RNhkJjMkXEPe2p2tP8oGXYN31mE10WniNb9mgeLjGNbZAnpuReNbn6mlqtOZAyGd1qMwp1iDiQhoFIyClIuA13gzWi3N6FGhDl9khnImAU9IKAIOmyMfIZBEujZAx3nRZAgyUi7avb" VERIFY_TOKEN = "123" my_params = {'q': 'hi'} PORT = os.environ['PORT'] d = {"ID": 1} page = Page(ACCESS_TOKEN) google_url = 'https://www.google.com.tw/search' machine = TocMachine( states=[ 'user', 'state1', 'state2', 'state3', 'state4', 'state5', 'state6', 'state7', 'state8', 'state9', 'state10', 'state11' ], transitions=[ { 'trigger': 'advance', 'source': 'user', 'dest': 'state1', 'conditions': 'is_going_to_state1' }, { 'trigger': 'advance',
"""EOF""" """ 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()
from flask import Flask, request from fbmq import Page, Attachment, QuickReply, Buttons, Template import apiai import json import quickreplies as qr import news import weather as w app = Flask(__name__) page = Page( page_access_token= 'EAAa7BshAslQBAAm0V8gZCA9dwlFjZC5bD5YYkhasmZBZC0nO2CMLV1K9aJY5r9VTFa6slwBQLGb1su8vhyoOLldsqKeYddHw7lP34fGJRHbWi0LXKotZCSKzP1djDp1FzR4X5oMmJk4iCYvIp60Ab5JVtMAIJGK1rScZAb4Caws78K2ueQdbEl' ) def handle_allActions(sender, action, ai_reply): if action == 'action.getNews': smart_object = qr.get_news_quick_reply() page.send(recipient_id=sender, message='Choose any one of these sources:', quick_replies=smart_object) elif action == 'smalltalk.greetings.hello': quickreply_mini = [ QuickReply(title='news', payload='news_hello'), QuickReply(title='weather', payload='weather') ] message_ai = ai_reply['result']['fulfillment']['speech'] page.send( recipient_id=sender, message=message_ai + '! Click on the button below, or you can simply text What is the news? For info on weather tap on weather',
import os import json from pprint import pprint from flask import Flask, request, abort from fbmq import Attachment, Template, QuickReply, Page from call_api import create_issue from push_notification import push_noti from dotenv import load_dotenv load_dotenv() page = Page(os.getenv("FB_TOKEN")) user_database = [] app = Flask(__name__) class User(): def __init__(self, uid): self.uid = uid self.profile_detail = self.user_info(uid) self.loc = None self.image = None self.text = None self.in_create_issue = False def user_info(self, uid) -> dict: user = page.get_user_profile(uid)
from fbmq import Page, Template import os from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt ACCESS_TOKEN = os.environ["FB_ACCESS_TOKEN"] SECRET_KEY = os.environ["FB_SECRET_KEY"] page = Page(ACCESS_TOKEN) page.show_starting_button("GETTING_STARTED") @page.callback(['GETTING_STARTED']) def start_callback(payload, event): first_name = page.get_user_profile(event.sender_id).get( "first_name", "Anonymous") page.send( event.sender_id, "Chào {}, vui lòng chọn các chức năng của bot trong MENU nhé !".format( first_name)) @csrf_exempt def fb_webhook(request): if request.method == "GET": if SECRET_KEY == request.GET.get('hub.verify_token'): return HttpResponse(request.GET.get("hub.challenge")) else: page.handle_webhook(request.body) return HttpResponse("")
# coding=utf-8 import os,sys,json,random,requests,unicodedata from fbmq import Page, Attachment, QuickReply, utils from fbmq import template as Template from datetime import datetime from flask import Flask, request token = "EAAXucKw0xEwBAGMKSa2ZBHy6kW2rCDJVz9ZBKioho7EiDOPNFJs3IvKcBrVWesDnYzZCfL4uytPnY2HYTTWdbPvPvIaT97RvTcuhRAJSZB2GJLV5RsZCfzLbeTkNSmWLgJhWyNNjgQkQxh0rciNhWo4Skv29CQjLZAZCeq5rysgyAZDZD" page = Page(token) QuestaoPaga=["quais sao as opcoes de pagamento?","como posso pagar?","pagar"] QuestaoPreco=["quanto custam os produtos?","preco","quanto custa?","quanto e?", "quanto é que os teus serviços custam?"] saudacoes = ["bom dia","boa tarde","boa noite","ola","boas"] vidal = ["qual o segredo da vida?","qual o proposito de viver","existe um suprasumo da sapiencia"] nome = ["como te chamas?","quem es tu?","qual o teu nome?"] perg_area = ["em que areas opera?", "o que fazem?", "qual a area da empresa?"] perg_servc=["posso saber mais sobre um serviço?", "que servicos tem em particular?","que servicos oferecem?"] smile=[":D",":P",":)",";)",":*"] #moderator = [2199242023423175] #ID Pedro e Cátia class buttons: btnmenu = [ Template.ButtonPostBack("Serviços", "MUSIC_PAYLOAD"), Template.ButtonPostBack('"Produtos recreativos"',"PROD_PAYLOAD"), Template.ButtonPostBack("Ajuda","AJUDA_PAYLOAD") ] class quickReply: quick_musica = [{'title': 'Rock', 'payload': 'PICK_ROCK'}, {'title': "Rn'B", 'payload': 'PICK_RnB'}, {'title': 'Pop', 'payload': 'PICK_POP'},
"""CraftyBot.""" import os import sys from jinja2 import StrictUndefined from flask import Flask, jsonify, render_template, redirect, request, flash, session, abort from fbmq import Page, Attachment, Template, QuickReply, NotificationType from lib.model import User, Project, Proj_Stat, Status, Pattern, Image, Fabric, connect_to_db, db from seed_status import create_status from datetime import datetime, timedelta from settings import crafter, server_host app = Flask(__name__) facebook = os.environ['FACEBOOK_TOKEN'] page = Page(facebook) # Required to use Flask sessions and the debug toolbar app.secret_key = "" app.jinja_env.undefined = StrictUndefined ############################################################################## @app.route('/webhook', methods=['POST', 'GET']) def webhook(): """Run once at the begining to connect to facebook api.""" if request.method == 'POST': print request.get_data(as_text=True) page.handle_webhook(request.get_data(as_text=True)) return "ok" else: challenge = request.args.get('hub.challenge') return challenge
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from fbmq import Page 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,
from flask import request from fbmq import Attachment, Template, QuickReply, Page import time from .models import * from .globals import * from .graph import * CART_ITEM = Item() page = Page(ACCESS_TOKEN) page.greeting("{{user_first_name}}, Welcome to Circuit House!") # Starting button action page.show_starting_button("START_PAYLOAD") # Starting Button Callback Handler @page.callback(['START_PAYLOAD']) def start_callback(payload, event): print("GET STARTED TRIGGERED!") sender_id = event.sender_id profile = get_user_info(sender_id) sender_name = profile['first_name'] page.typing_on(sender_id) time.sleep(.3) page.typing_off(sender_id) # Conversation Starter quick_replies = [ QuickReply(title="📦 Order Product", payload="PICK_ORDER"),
import os from fbmq import Page, Attachment from flask import Flask, request app = Flask(__name__) page = Page(os.getenv('PAGE_TOKEN', '')) @app.route("/") def hello(): return "Hello World!" @app.route('/webhook', methods=['GET']) def webhook_get(): print(request.get_data(as_text=True)) mode = request.args.get('hub.mode') token = request.args.get('hub.verify_token') challenge = request.args.get('hub.challenge') if mode == 'subscribe' and token == os.getenv('SECRET', ''): return challenge else: return "wrong token" @app.route('/webhook', methods=['POST']) def webhook(): page.handle_webhook(request.get_data(as_text=True)) return "ok"
""" Must create database for this work from app import db """ #connects the postgesql to python app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] db = SQLAlchemy(app) #this is the reddit developer acc reddit = praw.Reddit(client_id = '', client_secret = '', user_agent = 'my user agent') #This needs to be filled with the PAGE ACCESS TOKEN PAT= '' page = Page(PAT) #this is the welcome screen before you get started page.greeting("Hi! I'm Todd! If you want to laugh or just need someone to make you happy, I'm the right person to talk to!") #this will show the get started button page.show_starting_button("START_PAYLOAD") @page.callback(['START_PAYLOAD']) def start_callback(payload, event): print("Let's start!") #the different menus that are being shown page.show_persistent_menu([Template.ButtonPostBack('What do I do?', 'MENU_PAYLOAD/1'), Template.ButtonPostBack('Hotline', 'MENU_PAYLOAD/2'), Template.ButtonWeb('Other Hotlines', 'http://www.pleaselive.org/hotlines/')]
# -*- coding: utf-8 -*- """Archivo principal para el echobot. Main File for the echobot""" from fbmq import Page from flask import Flask, request # Token generado por la página web. Generated token in the facebook web page PAGE_ACCESS_TOKEN = "EAAXLozIQG8YBAOFvsfAZBHJhsGTM4hocXn8AUVyHQObcXy9ahVbhUWJu8P0GWgfzCs7sOpVdpZAjbsDEp4eSuoTPmsxNQNhCZC86BmCwlNcZCeUTf5Wxyqnco6URo7UZCSgKEGWNkIm40MnW9MZAcdNib8gz4EyZAzkrpBHnta40YwNba3XmfMo" # Token generado por nosotros. Token generated by us VERIFY_TOKEN = "EchoBotChido" # Si cambias este token, asegúrate de cambiarlo también en la página de configuración del webhook. If you change this token, verify that you changed it too in the webhook configuration. app = Flask(__name__) page = Page( PAGE_ACCESS_TOKEN ) # Generamos la instancia de la página de facebook. We make the facebook page instance @app.route('/') def hello_world(): """La página principal del servidor. The server main page.""" return 'Inicio del servidor' @app.route('/webhook', methods=['GET', 'POST']) def webhook(): """El método que se ejecuta cuando Facebook se conecta. This method executes as Facebook connect to us.""" if request.method == 'POST': # if the message is a POST, we handle it with message_handler. Si el mensaje es POST, se maneja con el message_handler # Facebook sends the user messages with a POST. Facebook manda los mensajes del usuario con un POST. page.handle_webhook(request.get_data(as_text=True)) return 'ok' elif request.method == 'GET': # if the message is a GET, we handle it here. Si el mensaje es un GET, lo manejamos aquí. # The first you configure the webhook, FB sends a GET to your webhook to verify that it really is you, and you're not working on someone's else page.
def load_page(page_id, token): """Load a facebook page object.""" PAGES[page_id] = Page(token, message=facebook_message_handler)
# coding=utf-8 import os, sys, json, random, fb, requests from fbmq import Page, Template, Attachment, QuickReply from datetime import datetime from flask import Flask, request page = Page( "EAACoZCnVve74BAAIZCs17iPNPK6pUatUdOKhY2EciLVhTEZAU2Bx1KD3EFYiUvYtFYxNXEOQXYj2VVcme8PmsLBuHQGQgDztJfcjcqVPZBfM8ZArrXgOxvSbgvrUZAIvz34ACTZBhUUfQ6qrlY7KHEN0lBZAng5Oylz58XGtGfmJAd2l9bE4sjS5" ) date = datetime.now().strftime("%d/%m") app = Flask(__name__) numbergen = [1, 2] @app.route('/', methods=['GET']) def verify(): # Vai ao endpoint e verifica os tokens, para o webhook if request.args.get("hub.mode") == "subscribe" and request.args.get( "hub.challenge"): if not request.args.get( "hub.verify_token") == os.environ["VERIFY_TOKEN"]: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello world", 200 @app.route('/', methods=['POST']) def webhook(): # Processa msg data = request.get_json() log(data)
import os from flask import Flask, request from fbmq import Attachment, Template, QuickReply, Page from search_card import recommend_card, card_detail import random ######################################################## ## 設置事件終點、通關密碼和認證密碼 app = Flask(__name__) ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] VERIFY_TOKEN = os.environ['VERIFY_TOKEN'] page = Page(ACCESS_TOKEN) ## 設置webhook @app.route("/", methods=['GET', 'POST']) def webhook(): if request.method == 'GET': if request.args.get('hub.verify_token') == VERIFY_TOKEN: return request.args.get('hub.challenge') else: return 'Invalid verification token' else: page.handle_webhook(request.get_data(as_text=True)) return 'ok' ######################################################## ## 判讀payload內容 @page.handle_postback def received_postback(event): sender_id = event.sender_id payload = event.postback_payload
from flask import Flask, request from fbmq import Attachment, Template, QuickReply, Page from ts import query_AllProduct from Userprofile import * from insertDB import * from templates import * import random import json import requests from FBToken import * ######################################################## ## 設置事件終點、通關密碼和認證密碼 app = Flask(__name__) page = Page(ACCESS_TOKEN) allProduct = query_AllProduct() profile = {} ## 設置webhook @app.route("/", methods=['GET', 'POST']) def webhook(): if request.method == 'GET': if request.args.get('hub.verify_token') == VERIFY_TOKEN: return request.args.get('hub.challenge') else: return 'Invalid verification token' else: page.handle_webhook(request.get_data(as_text=True)) return 'ok'
currentdir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import config from messages import handleMessage import datetime from pymongo import MongoClient client = MongoClient("localhost") db = client.wispi page = Page(config.PAGE_ACCESS_TOKEN) def process(tweet): if "pitch" in tweet: cursor = db.tastes.find({'taste': 'business'}) for document in cursor: tList = [] page.send( document["userId"], "Tu m'a dit aimer tout ce qui est en relation avec le commerce / business / entreprenariat n'est ce pas ? J'ai trouvé pour toi un évenement qui pourrait te plaire !" ) eventName, eventDate, eventLink, eventAdress, eventCity, eventId = "Pitch a l'EDHEC", datetime.datetime.now( ), "wispi.tk", "393 Prom. des Anglais, 06200 Nice", "Nice", "0x4984987"