Skip to content

Instantly share code, notes, and snippets.

@QuadTriangle
Created October 2, 2018 13:24
Show Gist options
  • Select an option

  • Save QuadTriangle/d753f19a7cb30107ee6d5580bb37ca8b to your computer and use it in GitHub Desktop.

Select an option

Save QuadTriangle/d753f19a7cb30107ee6d5580bb37ca8b to your computer and use it in GitHub Desktop.
A wikipedia bot for facebook messenger
import requests
from flask import Flask, request
from mediawiki import MediaWiki, DisambiguationError
from pymessenger.bot import Bot
ACCESS_TOKEN = 'SORRY, PUT YOUR ACCESS TOKEN HERE!'
app = Flask(__name__)
bot = Bot(ACCESS_TOKEN)
wikipedia = MediaWiki()
requests.adapters.DEFAULT_RETRIES = 5
@app.route("/", methods=['GET', 'POST'])
def wiki_bot():
if request.method == 'POST':
output = request.get_json()
for event in output.get('entry', []):
for message in event.get('messaging', []):
if message.get('message'):
try:
handle_message(message)
except Exception as exc:
print(exc)
return request.args.get("hub.challenge") or 'Success'
def handle_message(message):
recipient_id = message['sender']['id']
message_body = message['message'].get('text')
quick_reply = message['message'].get('quick_reply')
attachments = message['message'].get('attachments')
if message_body and quick_reply:
show_page(recipient_id, quick_reply)
elif message_body and not attachments:
show_search_result(recipient_id, message_body)
else:
bot.send_image_url(recipient_id, 'https://i.imgur.com/Vv4SsCq.jpg')
def show_search_result(recipient_id, message_body):
results = wikipedia.search(message_body, results=4)
if not results:
bot.send_text_message(recipient_id, f"Sorry, Wikipedia doesn't have an entry for: {message_body}")
return
quick_reply_option = [(result, result) for result in results]
quick_reply_message = 'Please, select the most relevent option'
bot.send_quick_reply(recipient_id, quick_reply_message, quick_reply_option)
def show_page(recipient_id, quick_reply):
payload = quick_reply.get('payload')
if payload.startswith('more'):
title = payload.split(':=:')[1]
page = wikipedia.page(title)
quick_reply_message = 'Sections'
quick_reply_option = [(section, f'section:=:{title}:=:{section}') for section in page.sections]
bot.send_quick_reply(recipient_id, quick_reply_message, quick_reply_option[:11])
elif payload.startswith('section'):
_, title, section = payload.split(':=:')
page = wikipedia.page(title)
bot.send_quick_reply(recipient_id, page.section(section)[:2000], [['More', f'more:=:{page.title}']])
else:
try:
page = wikipedia.page(payload)
bot.send_quick_reply(recipient_id, page.summary[:2000], [['More', f'more:=:{page.title}']])
except DisambiguationError as exc:
bot.send_text_message(recipient_id, str(exc))
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment