Skip to content

Instantly share code, notes, and snippets.

@bvanrijn bvanrijn/bot.py Secret
Created Aug 16, 2016

Embed
What would you like to do?
# -*- coding: utf-8 -*-
"""
Copyright: (C) 2016, Barend van Rijn
License: MIT (see https://mitlicense.org)
"""
# Import dependencies
from telegram.ext import Updater
import logging
import Algorithmia
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
# Set up basic logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
# This is the token for the Telegram Bot API.
# See https://core.telegram.org/bots#3-how-do-i-create-a-bot
# and https://core.telegram.org/bots#6-botfather
updater = Updater(token='<token>')
dispatcher = updater.dispatcher
# You can find your Algorithmia token by going to My Profile > Credentials
client = Algorithmia.client('<token>')
# The algorithm we'll be using
algo = client.algo('nlp/Summarizer/0.1.3')
def start(bot, update):
# Your bot will send this message when users first talk to it, or when they use the /start command
bot.sendMessage(chat_id=update.message.chat_id, text="Hi. Send me any English text and I'll summarize it for you.")
def summarize(bot, update):
try:
# Get the text the user sent
text = update.message.text
# Run it through the summarizer
summary = algo.pipe(text)
# Send back the result
bot.sendMessage(chat_id=update.message.chat_id, text=summary.result)
except UnicodeEncodeError:
bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, but I can't summarise your text.")
# This enables the '/start' command
start_handler = CommandHandler('start', start)
# Summarize all the messages sent to the bot, but only if they contain text
summarize_handler = MessageHandler([Filters.text], summarize)
dispatcher.add_handler(summarize_handler)
dispatcher.add_handler(start_handler)
updater.start_polling()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.