aboutsummaryrefslogtreecommitdiff
path: root/kjvbot.py
diff options
context:
space:
mode:
authorCamil Staps2016-03-20 21:47:03 +0100
committerCamil Staps2016-03-20 21:47:03 +0100
commitdd29c2ac5132fd926aeda6325d3fb21dfe09c49e (patch)
tree6367d356b8baa2e46524cb28969803c7a5534919 /kjvbot.py
First version
Diffstat (limited to 'kjvbot.py')
-rw-r--r--kjvbot.py73
1 files changed, 73 insertions, 0 deletions
diff --git a/kjvbot.py b/kjvbot.py
new file mode 100644
index 0000000..83e2af8
--- /dev/null
+++ b/kjvbot.py
@@ -0,0 +1,73 @@
+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):
+ verses = check_output(['bible', '-f', ref]).decode('utf-8').splitlines()
+ return map(lambda s:s.split(' ', 1), verses)
+
+def search(q):
+ q = q.split()
+ try:
+ ctx = list(filter(lambda s: s[0] == ':', q))[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:22]
+ return map(get_verses, list(filter(lambda r: r.find(ctx) == 0, refs)))
+
+class InlineHandler(telepot.async.helper.UserHandler):
+ def __init__(self, seed_tuple, timeout):
+ super(InlineHandler, self).__init__(seed_tuple, timeout,
+ flavors=['inline_query', 'chosen_inline_result'])
+
+ @asyncio.coroutine
+ def on_inline_query(self, msg):
+ 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',
+ 'id': ref,
+ 'title': ref,
+ 'message_text': '%s: %s' % (ref, txt),
+ 'description': txt })
+ else:
+ for [[ref, txt]] in search(query_string):
+ articles.append({'type': 'article',
+ 'id': ref,
+ 'title': ref,
+ 'message_text': '%s: %s' % (ref, txt),
+ 'description': txt })
+
+ yield from self.bot.answerInlineQuery(query_id, articles[:20], 300)
+
+ def on_chosen_inline_result(self, msg):
+ pass
+
+ def on_close(*args, **kwargs):
+ pass
+
+TOKEN = sys.argv[1]
+
+bot = telepot.async.DelegatorBot(TOKEN, [
+ (per_inline_from_id(), create_open(InlineHandler, timeout=10)),
+])
+loop = asyncio.get_event_loop()
+
+loop.create_task(bot.messageLoop())
+print('Listening...')
+
+loop.run_forever()
+