class YoMamaBotView(generic.View): page = fbmq.Page('XXX') def get(self, request, *args, **kwargs): if self.request.GET['hub.verify_token'] == 'XXX': print('verify is ok') return HttpResponse(self.request.GET['hub.challenge']) else: return HttpResponse('Error, invalid token') @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return generic.View.dispatch(self, request, *args, **kwargs) # Post function to handle Facebook messages def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary incoming_message = json.loads(self.request.body.decode('utf-8')) #print(str(incoming_message)+ ' +++++') # Facebook recommends going through every entry since they might send # multiple messages in a single call during high load #page = fbmq.Page('EAAXTQIyKBiwBAMnl26FWLW7T6ZBCsD3TFPRcRxIaYU4YkMjrKosWZBwXDyLZBRzWfIXZCvWLLZCGF8bqixLDKXm8mFA7SNSbJjTfnagkDmeZBLM6ZA9yTDD5RRjTbcoRQWexH0qcnNM8ZAsFrUs3oQxgbtAJYlHaFZCS88cr1d90pawZDZD') #page.send('1488848524485107', "hello world!") for entry in incoming_message['entry']: for message in entry['messaging']: # Check to make sure the received call is a message call # This might be delivery, optin, postback for other events if 'message' in message: # Print the message to the terminal #print(message['message']+ ' ++++ message text') try: #post_facebook_message(message['sender']['id'], message['message']['text']) sqlop.letsinsert(str(message['sender']['id']), str(message['message']['text']), str(message['message']['seq'])) pprint(message) pprint(message['recipient']['id']) except: pprint('Kayit olmadi') post_facebook_message(message['sender']['id'], 'Üzgünüm sizi anlayamadım') return HttpResponse()
def lambda_handler(event, context): if 'params' in event.keys(): params = event['params']['querystring'] if params and params['hub.mode'] == 'subscribe': if params['hub.verify_token'] == verify_token: return int(params['hub.challenge']) else: return "Verification error" else: messaging = json.loads(event['body']) messaging = messaging['entry'][0]['messaging'][0] if 'message' in messaging.keys( ) and 'text' in messaging['message'].keys(): sender, message = messaging['sender']['id'], messaging['message'][ 'text'] sender = int(sender) page = fbmq.Page(PAGE_ACCESS_TOKEN) if message == 'next': connectDb() pet = getRandomPet() page.send(sender, "This is {}!".format(pet.name)) #page.send(sender, "(DEBUG pet_id ={})".format(pet.pet_id)) description, img = parsePetFromId(pet.pet_id) attachment = Attachment.Image(img) page.send(sender, attachment) buttons = [ Template.ButtonWeb("Support {}".format(pet.name), "https://www.google.com") ] if description: page.send(sender, description) page.send( sender, Template.Buttons(naturalLanguage("emphatic"), buttons)) else: print(messaging) response = { 'statusCode': 200, 'body': json.dumps({'success': True}), 'headers': { 'Content-Type': 'application/json', } } return response
def post(self, request, *args, **kwargs): # Converts the text payload into a python dictionary page = fbmq.Page('EAAXTQIyKBiwBAMnl26FWLW7T6ZBCsD3TFPRcRxIaYU4YkMjrKosWZBwXDyLZBRzWfIXZCvWLLZCGF8bqixLDKXm8mFA7SNSbJjTfnagkDmeZBLM6ZA9yTDD5RRjTbcoRQWexH0qcnNM8ZAsFrUs3oQxgbtAJYlHaFZCS88cr1d90pawZDZD') incoming_message = json.loads(self.request.body.decode('utf-8')) #pprint(incoming_message) #print(str(incoming_message)+ ' +++++') try: img_url=incoming_message['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'] # Facebook recommends going through every entry since t #page = fbmq.Page('EAAXTQIyKBiwBAMnl26FWLW7T6ZBCsD3TFPRcRxIaYU4YkMjrKosWZBwXDyLZBRzWfIXZCvWLLZCGF8bqixLDKXm8mFA7SNSbJjTfnagkDmeZBLM6ZA9yTDD5RRjTbcoRQWexH0qcnNM8ZAsFrUs3oQxgbtAJYlHaFZCS88cr1d90pawZDZ #page.send('1488848524485107', "hello wor img_url=incoming_message['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'] pprint(img_url) img = urllib2.urlopen(img_url) localFile = open('/home/kafein/thy_hackathon/images/deeesktop.jpg', 'wb') localFile.write(img.read()) localFile.close() pprint('testttttt') time.sleep(5) list_of_files = glob.glob('/home/kafein/thy_hackathon/check-in/*') # * means all if need specific format then *.csv pprint('heyooooo') latest_file = max(list_of_files, key=os.path.getctime) image_url=latest_file recipient_id=incoming_message['entry'][0]['id'] pprint(recipient_id) pprint(image_url) im = Image.open(str(image_url)) dosya_adi=im.filename pprint(dosya_adi) pprint(str(dosya_adi).split('check-in/')[1].split('.jpg')[0]) dosya_adi=str(dosya_adi).split('check-in/')[1].split('.jpg')[0] cumle='Sayin '+str(str(dosya_adi).split('_')[1])+' kimlik numarali '+str(dosya_adi.split('.')[0])+' ' + str(dosya_adi.split('.')[1].split('_')[0]) + ' ' +str(dosya_adi.split('_')[2]) +' ucaginizda koltuk numaraniz '+ str(dosya_adi.split('_')[3])+ ' olarak ayarlanmistir. Iyi Yolculuklar Dileriz!' pprint(cumle) page.send('1488848524485107', str(cumle)) except: pass # Print the message to the terminal #print(message['message']+ ' ++++ message text') try: pprint('TETE') except: pprint('Kayit olmadi') post_facebook_message(message['sender']['id'],'Üzgünüm sizi anlayamadım') return HttpResponse()
kik_service.set_configuration( Configuration(webhook='https://%s%s' % (config.SERVER_NAME, config.KIK_BOT_WEBHOOK))) except Exception as e: logging.warning(e) else: kik_service = None if config.MICROSOFT_BOT_ENABLED: microsoft_service = BotFrameworkMicrosoft(config.MICROSOFT_BOT_ID, config.MICROSOFT_BOT_KEY) else: microsoft_service = None if config.FACEBOOK_BOT_ENABLED: facebook_service = fbmq.Page(config.FACEBOOK_BOT_KEY) try: facebook_service.show_starting_button("START_PAYLOAD") except Exception as e: logging.warning(e) else: facebook_service = None if config.TELEGRAM_BOT_ENABLED: telegram_service = TeleBot(config.TELEGRAM_BOT_KEY, threaded=False) try: telegram_service.set_webhook( url='https://%s%s' % (config.SERVER_NAME, config.TELEGRAM_BOT_WEBHOOK), max_connections=100)
import os, sys app = Flask(__name__) #FB Messenger Token # ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] # VERIFY_TOKEN = os.environ['VERIFY_TOKEN'] ACCESS_TOKEN = 'EAAQENu0nml0BAA5VZATAIav1GYZBqhQaUwP2gAbybmc4L1mz65fZBZBjzXfx6iHbOtfSTZAVrEDmFuKjLZCGqzdmEmMKPJxqZCMSc7tG2OFFlMVjQ8rBwyZAdFPnSw2ZCgxzCaIuFRs2HYHDhExR3oszDqn4vi80YSle9GTVTN7dW0wZDZD' VERIFY_TOKEN = 'columbia' bot = Bot(ACCESS_TOKEN) #looper = False #messenger introduction page = fbmq.Page(ACCESS_TOKEN,api_ver="v2.11") page.greeting("Welcome to MemeBot! Chat with us to get memes or compliments.") @app.route('/') def index(): return render_template('index.html', name='MemeBot') #receiving messages @app.route('/', methods=['GET']) def verify(): # Webhook verification if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"): if not request.args.get("hub.verify_token") == "hello": return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello world", 200
from flask import Flask, request from tokens import TOKEN, PAGE_ACCESS_TOKEN from flask_sqlalchemy import SQLAlchemy import json import fbmq from fbmq import QuickReply, Attachment from pprint import pprint import random import re import requests app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) page = fbmq.Page(PAGE_ACCESS_TOKEN) @app.route('/webhook', methods=['GET']) def verify(): if request.args.get("hub.mode") == "subscribe" and request.args.get( "hub.challenge"): if not request.args.get("hub.verify_token") == TOKEN: return "Verification token mismatch", 403 return request.args["hub.challenge"], 200 return "Hello World" @app.route('/webhook', methods=['POST']) def hook(): page.handle_webhook(request.get_data(as_text=True))
def letsinsert (userid,text,seq): db = MySQLdb.connect(host="127.0.0.1", # your host, usually localhost user="******", # your username passwd="mysql", # your password db="facebook") # name of the data base cur = db.cursor() db.autocommit(True) # Use all the SQL you like if str(userid) !='XXX': pprint("insert into talks (userid,text,seq) values ('"+str(userid).encode("utf-8")+"','"+str(text).encode("utf-8")+"','"+str(seq).encode("utf-8")+"')") cur.execute("insert into talks (userid,text,seq) values ('"+str(userid).encode("utf-8")+"','"+str(text).encode("utf-8")+"','"+str(seq).encode("utf-8")+"')") cur.execute("commit") cur.execute("select text from talks where ID =(select max(ID) from talks )") data = cur.fetchall() for row in data : last_talk=str(row[0]) pprint(last_talk) page = fbmq.Page('XXX') evet_hayir = [QuickReply(title="Evet", payload="PICK_ACTION"),QuickReply(title="Hayir", payload="PICK_COMEDY")] bagis = [QuickReply(title="XXX", payload="PICK_ACTION"),QuickReply(title="XXX", payload="PICK_COMEDY"),QuickReply(title="XXX", payload="PICK_COMEDY")] #pprint("insert into talks (userid,text,seq) values ('"+str(userid).encode("utf-8")+"','"+str(text).encode("utf-8")+"','"+str(seq).encode("utf-8")+"')") #cur.execute("insert into talks (userid,text,seq) values ('"+str(userid).encode("utf-8")+"','"+str(text).encode("utf-8")+"','"+str(seq).encode("utf-8")+"')") #cur.execute("commit") cur.close () if last_talk=='evet' or last_talk=='Evet': page.send('XX', "XXXX!", quick_replies=bagis, metadata="DEVELOPER_DEFINED_METADATA") elif last_talk=='XXX' or last_talk=='XXX' or last_talk=='XX': page.send('XX', str(last_talk) +"' XXX!") elif last_talk.isdigit() and len(str(last_talk))== 10: page.send('XX', "XXXX!") elif last_talk.isdigit() and len(str(last_talk))== 5: page.send('XX', "XXX") elif last_talk=='meraba' or last_talk=='selam' or last_talk=='Merhaba' or last_talk=='XX' or last_talk=='XX' or last_talk=='merhaba' or last_talk=='hey' or last_talk=='Hey' or last_talk=='Selam': page.send('XX', "XX XXX XX XX XXX ?", quick_replies=evet_hayir, metadata="DEVELOPER_DEFINED_METADATA") else : page.send('XX', "XX XX ,X XX XX XX ? ") # print all the first cell of all the rows #for row in cur.fetchall(): # print row[0] db.commit() db.close()
import scraper.slcm as scraper import parser.parser as parser import parser.responses as responses import utils.dbase as database import requests import fbmq from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from wit import Wit ### CONFIGS ### app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) page = fbmq.Page(os.environ["PAGE_ACCESS_TOKEN"]) wit_client = Wit(os.environ["WIT_TOKEN"]) dbase = database.handler(db) responder = responses.messages() ### Quick Replies on messenger ### quick_replies = [ fbmq.QuickReply(title="What can you do?", payload="WHAT"), fbmq.QuickReply(title="Attendance", payload="ATTENDANCE"), fbmq.QuickReply(title="Bunk", payload="BUNK"), fbmq.QuickReply(title="Timetable", payload="TIMETABLE"), fbmq.QuickReply(title="Teacher Guardian", payload="TEACHER"), ] ### DB Skeleton ###