def test_client_send_error_with_no_error_data(self, mock_post): mock_post.return_value.status_code = 190 mock_post.return_value.json.return_value = { 'error': { u'message': u'This Page access token belongs to a Page that has been deleted.', u'code': 190, u'type': u'OAuthException' } } messenger = MessengerClient(access_token='1234') recipient = messages.Recipient(recipient_id='123') message = messages.Message(text='Hello World') request = messages.MessageRequest(recipient, message) self.assertRaises(MessengerException, messenger.send, request) mock_post.assert_called_with( 'https://graph.facebook.com/v2.6/me/messages', json={ "message": { "text": "Hello World" }, "recipient": { "id": "123" } }, params={'access_token': '1234'})
def test_client_send_error_with_error_data(self, mock_post): mock_post.return_value.status_code = 190 mock_post.return_value.json.return_value = { "error": { "message": "Invalid parameter", "type": "FacebookApiException", "code": 100, "error_data": "No matching user found.", "fbtrace_id": "D2kxCybrKVw" } } messenger = MessengerClient(access_token='1234') recipient = messages.Recipient(recipient_id='123') message = messages.Message(text='Hello World') request = messages.MessageRequest(recipient, message) self.assertRaises(MessengerException, messenger.send, request) mock_post.assert_called_with( 'https://graph.facebook.com/v2.6/me/messages', json={ "message": { "text": "Hello World" }, "recipient": { "id": "123" } }, params={'access_token': '1234'})
def test_client_subscribe(self, mock_post): mock_post.return_value.status_code = 200 mock_post.return_value.json.return_value = {'success': True} messenger = MessengerClient(access_token='1234') messenger.subscribe_app() mock_post.assert_called_with( 'https://graph.facebook.com/v2.6/me/subscribed_apps', params={'access_token': '1234'})
def test_client_send(self, mock_post): mock_post.return_value.status_code = 200 mock_post.return_value.json.return_value = { 'success': True } messenger = MessengerClient(access_token='1234') recipient = messages.Recipient(recipient_id='123') message = messages.Message(text='Hello World') request = messages.MessageRequest(recipient, message) messenger.send(request) mock_post.assert_called_with( 'https://graph.facebook.com/v2.6/me/messages', json={ "message": {"text": "Hello World"}, "recipient": {"id": "123"} }, params={'access_token': '1234'} )
# Create your views here. from messengerbot import MessengerClient, messages, attachments, templates, elements import json,wikipedia,urllib,os from chatbot import Chat, register_call from .models import * from django.db.utils import OperationalError access_token = `< Access token >` VALIDATION_TOKEN= `< VALIDATION_TOKEN >` api_key = `< API key >` # Manully initialise client messenger = MessengerClient(access_token=access_token) def index(request): return render(request,"home.html") def about(query,qtype=None): service_url = 'https://kgsearch.googleapis.com/v1/entities:search' params = { 'query': query, 'limit': 10, 'indent': True, 'key': api_key, } url = service_url + '?' + urllib.urlencode(params) response = json.loads(urllib.urlopen(url).read())
def init_bot(self): self._bot = MessengerClient(self.token)
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from messengerbot import MessengerClient, messages, attachments, templates, elements import json, wikipedia, urllib, os from chatbot import Chat, register_call ACCESS_TOKEN = 'EAAJJC9XzVbABAE8X09HE4lv3HcGu43SkLlHPEGtEktIhivLsDfIeoOEGmCCjn0Uqd42jyLmiGIRRZAGUkfoQXD7X8I65ETb4rHf6BWdD9zOGgZCSKVlwt0Y9AgyZBAIQq0oXC73HOzL1p16D4NJF5gLBGYGzNdS9fs2aCfD4QZDZD' VALIDATION_TOKEN = "First Chatbot Demo" API_KEY = "643265136383408" messenger = MessengerClient(access_token=ACCESS_TOKEN) @register_call('whoIs') def who_is(query, session_id): try: return wikipedia.summary(query) except Exception: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except Exception: pass return "I don't know about " + query @csrf_exempt def webhook(request): if request.method != "POST": if request.GET['hub.verify_token'] == VALIDATION_TOKEN: return HttpResponse(request.GET['hub.challenge']) return HttpResponse("Failed validation. Make sure the validation tokens match.") return chathandler(request)
from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from messengerbot import MessengerClient, messages from chatbot import register_call from django.chatbot.chatbot import chat from django.conf import settings import json import wikipedia import urllib.parse import urllib.request # Manually initialise client messenger = MessengerClient(access_token=settings.ACCESS_TOKEN) def index(request): return render(request, "home.html") def about(query, qtype=None): service_url = 'https://kgsearch.googleapis.com/v1/entities:search' params = { 'query': query, 'limit': 10, 'indent': True, 'key': settings.API_KEY, } url = service_url + '?' + urllib.parse.urlencode(params) response = json.loads(urllib.request.urlopen(url).read()) if not len(response['itemListElement']):
app = Flask(__name__) # Configure app. _access_token = os.environ.get('CHRONOLOGIST_ACCESS_TOKEN') _verify_token = os.environ.get('CHRONOLOGIST_VERIFY_TOKEN') if _access_token is None and __name__ == '__main__': raise RuntimeError('`CHRONOLOGIST_ACCESS_TOKEN` env var is not set') app.config.update(DEBUG=eval(os.environ.get('CHRONOLOGIST_DEBUG', 'False')), VERIFY_TOKEN=_verify_token, ACCESS_TOKEN=_access_token, DIALOGFLOW_PROJECT_ID='chronologist-mvqppm', DIALOGFLOW_LANGUAGE_CODE='en') api = Api(app) history_api = History_API() messenger = MessengerClient(access_token=app.config['ACCESS_TOKEN']) # Logging. gunicorn_error_logger = logging.getLogger('gunicorn.error') app.logger.handlers.extend(gunicorn_error_logger.handlers) app.logger.setLevel(logging.DEBUG if app.config['DEBUG'] else logging.INFO) class FacebookOG(Resource): def get(self): return "OK!", 200 class Bot(Resource): def __init__(self): self.bot_ai = BotAI()
from kik.messages import TextMessage, PictureMessage, SuggestedResponseKeyboard,\ TextResponse, LinkMessage,StartChattingMessage, CustomAttribution from bot import kik,FB_PAGE_TOKEN from messengerbot import MessengerClient, attachments, templates, elements from messengerbot import messages as fbmessages fbmessenger = MessengerClient(access_token=FB_PAGE_TOKEN) def dispatchMessage(context,msg_type,*args,**kwargs): kwargs['msg_type'] = msg_type if context['platform'] == 'KIK': sendKikMessages(*args,**kwargs) if context['platform'] == 'FB': sendFBMessage(*args,**kwargs) def abstract_kik_message(to,chat_id,content,msg_type): if msg_type == 'text': return TextMessage(to=to,chat_id=chat_id,body=content) if msg_type == 'image': return PictureMessage(to=to,chat_id=chat_id,pic_url=content) if msg_type == 'link': return LinkMessage(to=to,chat_id=chat_id,url=content) def sendKikMessages(chat_id,from_user,msgs,suggested_responses=[],msg_type=None): send_these = [] for msg in msgs: send_these.append(abstract_kik_message( to=from_user, chat_id=chat_id, content=msg,
from pprint import pprint # Vendors # https://github.com/geeknam/messengerbot from messengerbot import MessengerClient, messages, attachments, templates, elements import api_tools as api import db_tools as db from Criteria import Criteria import wit_handler as wit # "Constants" (variables that should not change) RESULTS_LIMIT = 3 # Initializing client messenger = MessengerClient(access_token=os.getenv('FB_PAGE_TOKEN')) def send_facebook_message(fbid, data): """ TODO: write description """ if 'storyline' in data: store_storyline(fbid, data["storyline"]) if 'criteria' in data and data["criteria"]: store_criteria(fbid, data["criteria"]) if 'action' in data: if data["action"] == 'api_call': handle_api_call(fbid) elif data["action"] == 'reset': reset_search(fbid)
from messengerbot import MessengerClient, messages, attachments, templates, elements # Manully initialise client messenger = MessengerClient( access_token= 'EAADrcnA0YAIBAMfwcg2wUmk6BG2IHZAthghXZBqYwE4Arb5uYz8M7foLlm1cfPsNdlj8JIlNmE8n7isZCAhn2b7ZChWoJxyentZC5aqRtIMfR4ich' ) # With env var export MESSENGER_PLATFORM_ACCESS_TOKEN=your_token from messengerbot import messenger recipient = messages.Recipient(recipient_id='123') # Send text message message = messages.Message(text='Hello World') request = messages.MessageRequest(recipient, message) messenger.send(request) # Send button template web_button = elements.WebUrlButton(title='Show website', url='https://petersapparel.parseapp.com') postback_button = elements.PostbackButton(title='Start chatting', payload='USER_DEFINED_PAYLOAD') template = templates.ButtonTemplate(text='What do you want to do next?', buttons=[web_button, postback_button]) attachment = attachments.TemplateAttachment(template=template) message = messages.Message(attachment=attachment) request = messages.MessageRequest(recipient, message) messenger.send(request)