1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
#!/usr/bin/env python3
"""Telegram bot that can search in the KJV"""
import asyncio
from subprocess import check_output
import sys
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 [s.split(' ', 1) for s in verses]
def search(query):
"""Search for a query"""
query = query.split()
try:
ctx = [s for s in query if s[0] == ':'][0][1:]
except IndexError:
ctx = ''
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 KJVInlineHandler(telepot.async.helper.UserHandler):
"""Inline handler for the KJV bot"""
def __init__(self, seed_tuple, timeout):
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',
'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):
"""We don't care about chosen inline results"""
pass
def on_close(self, *args, **kwargs):
"""Tear-down"""
pass
def main():
"""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.message_loop())
print('Listening...')
loop.run_forever()
if __name__ == '__main__':
main()
|