-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
215 lines (163 loc) · 8.05 KB
/
bot.py
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# encoding: utf-8
import logging
import json
import subprocess
from datetime import datetime
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton
from article import Article, ArticleIndex
ARTICLES_ON_PAGE_NUM = 10
query_by_hash = {}
logging.basicConfig()
log = logging.getLogger('bot')
log.setLevel(logging.DEBUG)
def show_database_info(bot, update):
bot.send_message(chat_id=update.message.chat_id,
text=u'В базе {} статей'.format(Article.parsed_num()))
def show_help(bot, update):
message = u"""
Привет!
Я бот-поисковик по http://nplus1.ru
Сейчас в моей базе {} статей, последнее обновление базы было {}
Полнотекстовый поиск:
динозавр -- поиск по тексту статей
кошка *OR* кот *OR* панголин -- в выдаче будут статьи, в которых встречается одно из указанных слов
кошка *-*предок -- убирает из выдачи статьи, в которых встречается слово "предок"
рибо\* -- поиск по префиксу, найдет и рибосомы, и рибозимы, и Жана Рибо
Команды:
*/author <автор>* -- поиск по имени автора
*/update* -- обновление базы
*/help* -- эта справка
Исходники доступны тут: https://github.com/flagist0/nplus1search
""".format(Article.parsed_num(),
open('last_update.txt').readline().strip())
bot.send_message(chat_id=update.message.chat_id,
text=message,
parse_mode=ParseMode.MARKDOWN)
def rescrape(bot, update):
bot.send_message(chat_id=update.message.chat_id,
text=u'Начинаю обновление базы')
process = subprocess.Popen(['scrapy', 'crawl', 'nplus1'], stdout=subprocess.PIPE)
process.communicate()
bot.send_message(chat_id=update.message.chat_id,
text=u'Обновление базы закончено!')
with open('last_update.txt', 'w') as fh:
fh.write('{}'.format(datetime.now().strftime('%Y-%m-%d %H:%M')))
def search_by_author(bot, update, args):
author = ' '.join(args)
response_opts = get_search_by_author_response(author, cur_page=0)
bot.send_message(chat_id=update.message.chat_id, **response_opts)
def search_by_text(bot, update):
query = update.message.text
response_opts = get_search_by_text_response(query, cur_page=0)
bot.send_message(chat_id=update.message.chat_id, **response_opts)
def get_search_by_author_response(author, cur_page):
reply_markup = None
where = Article.author == author
count = Article.select().where(where).count()
if count:
cursor = Article.select().where(where).order_by(Article.date.desc())
offset, limit, total = get_pagination(cursor, cur_page)
output = get_count_header(offset, limit, total)
output += get_search_by_author_response_text(cursor, offset, limit)
author_hash = hash(author)
query_by_hash[author_hash] = author
reply_markup = get_reply_markup(cur_page, offset, limit, total,
# callback data len is limited to 64b
{'meth': 's_b_a', # search_by_author
'ah': author_hash}) # author hash, dirty stateful hack because of cb data limits
else:
output = u'Статей автора "{}" не найдено'.format(author)
result = {
'text': output,
'parse_mode': ParseMode.MARKDOWN,
'reply_markup': reply_markup
}
return result
def get_search_by_text_response(query_text, cur_page):
reply_markup = None
cursor = ArticleIndex.search_by_text(query_text)
count = cursor.count()
if count:
offset, limit, total = get_pagination(cursor, cur_page)
output = get_count_header(offset, limit, total)
output += get_search_by_text_response_text(cursor, offset, limit)
query_hash = hash(query_text)
query_by_hash[query_hash] = query_text
reply_markup = get_reply_markup(cur_page, offset, limit, total,
# callback data len is limited to 64b
{'meth': 's_b_t', # search_by_text
'qth': query_hash}) # query_text hash, dirty stateful hack because of cb data limits
else:
output = u'Статей по запросу "{}" не найдено'.format(query_text)
result = {
'text': output,
'parse_mode': ParseMode.MARKDOWN,
'reply_markup': reply_markup
}
return result
def get_pagination(cursor, cur_page):
total_count = cursor.count()
offset = cur_page * ARTICLES_ON_PAGE_NUM
limit = min(ARTICLES_ON_PAGE_NUM, total_count - offset)
return offset, limit, total_count
def get_count_header(offset, limit, total):
return u'Найдено {} статей\nСтатьи {}-{}/{}:\n\n'.format(total, offset, offset + limit, total)
def get_search_by_author_response_text(cursor, offset, limit):
articles = cursor.offset(offset).limit(limit)
lines = [u'*{}* {} {}'.format(article.title, article.date, article.url) for article in articles]
return '\n\n'.join(lines)
def get_search_by_text_response_text(cursor, offset, limit):
articles = cursor.offset(offset).limit(limit)
lines = [u'*{}* {}\n{}\n{}'.format(article.title, article.date, article.snippets, article.url)
for article in articles]
return '\n\n'.join(lines)
def get_reply_markup(cur_page, offset, limit, total, cb_data_additions):
buttons = []
if cur_page:
callback_data = {'page': cur_page - 1}
callback_data.update(cb_data_additions)
callback_data = json.dumps(callback_data)
back_button = InlineKeyboardButton('<', callback_data=callback_data)
buttons.append(back_button)
if offset + limit < total:
callback_data = {'page': cur_page + 1}
callback_data.update(cb_data_additions)
callback_data = json.dumps(callback_data)
forth_button = InlineKeyboardButton('>', callback_data=callback_data)
buttons.append(forth_button)
reply_markup = InlineKeyboardMarkup([buttons]) if buttons else None
return reply_markup
def callback_handler(bot, update):
query = update.callback_query
data = json.loads(query.data)
response_opts = {'text': data}
if data['meth'] == 's_b_a':
author = query_by_hash.pop(data['ah'])
response_opts = get_search_by_author_response(author, cur_page=data['page'])
elif data['meth'] == 's_b_t':
query_text = query_by_hash.pop(data['qth'])
response_opts = get_search_by_text_response(query_text, cur_page=data['page'])
bot.edit_message_text(chat_id=query.message.chat_id,
message_id=query.message.message_id,
**response_opts)
def error_handler(bot, update, error):
log.exception(error)
def get_token():
with open('token.txt') as fh:
return fh.readline().strip()
def add_handlers(updater):
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', show_help))
dispatcher.add_handler(CommandHandler('help', show_help))
dispatcher.add_handler(CommandHandler('info', show_database_info))
dispatcher.add_handler(CommandHandler('update', rescrape))
dispatcher.add_handler(CommandHandler('author', search_by_author, pass_args=True))
dispatcher.add_handler(CallbackQueryHandler(callback_handler))
dispatcher.add_handler(MessageHandler(Filters.text, search_by_text))
dispatcher.add_error_handler(error_handler)
if __name__ == '__main__':
updater = Updater(token=get_token())
add_handlers(updater)
updater.start_polling()
updater.idle()