aboutsummaryrefslogtreecommitdiff
path: root/kjvbot.py
diff options
context:
space:
mode:
authorCamil Staps2016-05-03 15:04:59 +0200
committerCamil Staps2016-05-03 15:04:59 +0200
commit51e91ba151612ced708092516bb50c50857cb1c6 (patch)
tree8c15cd790105d9dd918556e7bfef2430479eb2d3 /kjvbot.py
parentFix Song of Solomon / Revelation bug (diff)
pylint
Diffstat (limited to 'kjvbot.py')
-rw-r--r--kjvbot.py70
1 files changed, 42 insertions, 28 deletions
diff --git a/kjvbot.py b/kjvbot.py
index a0f1a4f..dfc1e99 100644
--- a/kjvbot.py
+++ b/kjvbot.py
@@ -1,77 +1,91 @@
+#!/usr/bin/env python3
+"""Telegram bot that can search in the KJV"""
import asyncio
-import json
-import urllib
from subprocess import check_output
import sys
-import time
import telepot
from telepot.async.delegate import per_inline_from_id, create_open
+
def get_verses(ref):
+ """Get text from a bible reference"""
verses = check_output(['bible', '-f', ref]).decode('utf-8').splitlines()
- return map(lambda s:s.split(' ', 1), verses)
+ return [s.split(' ', 1) for s in verses]
+
-def search(q):
- q = q.split()
+def search(query):
+ """Search for a query"""
+ query = query.split()
try:
- ctx = list(filter(lambda s: s[0] == ':', q))[0][1:]
+ ctx = [s for s in query if s[0] == ':'][0][1:]
except IndexError:
ctx = ''
- q = list(filter(lambda s: not s[0] == ':', q))
- print(ctx, q)
- refs = check_output(['bible', '-f'] + q).decode('utf-8').splitlines()[2:]
- return map(get_verses, list(filter(lambda r: r.find(ctx) == 0, refs)))
+ query = [s for s in query if s[0] != ':']
+ print(ctx, query)
+ refs = check_output(['bible', '-f']+query).decode('utf-8').splitlines()[2:]
+ return [get_verses(r) for r in refs if r.find(ctx) == 0]
+
-class InlineHandler(telepot.async.helper.UserHandler):
+class KJVInlineHandler(telepot.async.helper.UserHandler):
+ """Inline handler for the KJV bot"""
def __init__(self, seed_tuple, timeout):
- super(InlineHandler, self).__init__(seed_tuple, timeout,
- flavors=['inline_query', 'chosen_inline_result'])
+ super(KJVInlineHandler, self).__init__(
+ seed_tuple, timeout,
+ flavors=['inline_query', 'chosen_inline_result'])
@asyncio.coroutine
def on_inline_query(self, msg):
+ """Handle a query"""
query_id, _, query_string = telepot.glance(msg, flavor='inline_query')
-
+
query_string = query_string.strip()
articles = []
if not query_string == '':
if not query_string[0] == '?':
for [ref, txt] in get_verses(query_string):
- articles.append({'type': 'article',
+ articles.append({
+ 'type': 'article',
'id': ref,
'title': ref,
'message_text': '%s: %s' % (ref, txt),
- 'description': txt })
+ 'description': txt
+ })
else:
for [[ref, txt]] in search(query_string):
- articles.append({'type': 'article',
+ articles.append({
+ 'type': 'article',
'id': ref,
'title': ref,
'message_text': '%s: %s' % (ref, txt),
- 'description': txt })
+ 'description': txt
+ })
yield from self.bot.answerInlineQuery(query_id, articles[:20], 300)
def on_chosen_inline_result(self, msg):
+ """We don't care about chosen inline results"""
pass
- def on_close(*args, **kwargs):
+ def on_close(self, *args, **kwargs):
+ """Tear-down"""
pass
+
def main():
- TOKEN = sys.argv[1]
-
- bot = telepot.async.DelegatorBot(TOKEN, [
- (per_inline_from_id(), create_open(InlineHandler, timeout=10)),
+ """Start the KJV bot using a token from the command line"""
+ token = sys.argv[1]
+
+ bot = telepot.async.DelegatorBot(token, [
+ (per_inline_from_id(), create_open(KJVInlineHandler, timeout=10)),
])
loop = asyncio.get_event_loop()
-
- loop.create_task(bot.messageLoop())
+
+ loop.create_task(bot.message_loop())
print('Listening...')
-
+
loop.run_forever()
if __name__ == '__main__':
main()
-