-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
269 lines (221 loc) · 7.91 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import argparse
import logging
from datetime import timedelta
from enum import IntEnum, auto
from functools import partial
from typing import List, Type, Union
from decouple import config
from telegram import Bot, BotCommand, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
CallbackContext,
CallbackQueryHandler,
CommandHandler,
ConversationHandler,
Updater,
)
from hnread import filters, items, repos, services
from hnread.topics import Topic
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
BOT_TOKEN = config("BOT_TOKEN")
REDIS_URL = config("REDIS_URL")
class BaseStoriesEventHandler(services.EventHandler):
def __init__(self, bot: Bot) -> None:
self.bot = bot
def get_display_class(self) -> Type[items.StoryDisplay]:
pass
def handle(
self,
subscribers: List[repos.Subscriber],
item: Union[items.Story, items.Job, items.Poll],
):
display_text = str(self.get_display_class()(item))
for subscriber in subscribers:
self.bot.send_message(subscriber.id, display_text, parse_mode="HTML")
class TopStoriesEventHandler(BaseStoriesEventHandler):
def get_display_class(self) -> Type[items.TopStoryDisplay]:
return items.TopStoryDisplay
class BestStoriesEventHandler(BaseStoriesEventHandler):
def get_display_class(self) -> Type[items.BestStoryDisplay]:
return items.BestStoryDisplay
def help_command(update: Update, context: CallbackContext) -> None:
if (message := update.message) is not None:
message.reply_text("help")
def ping_command(update: Update, context: CallbackContext) -> None:
if (message := update.message) is not None:
message.reply_text("Pong!")
class SubscribeState(IntEnum):
FIRST = auto()
class UnSubscribeState(IntEnum):
FIRST = auto()
def list_topic(update: Update, context: CallbackContext) -> int:
sub_service = services.HNSubscribeService(repos.RedisPubSubRepository(REDIS_URL))
inline_keyboard_bottons = [
InlineKeyboardButton(text, callback_data=f"{enum}")
for enum, text, in sub_service.list_topic().items()
]
keyboard = [inline_keyboard_bottons]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
"Subscribe a topic from the list below:", reply_markup=reply_markup
)
return SubscribeState.FIRST
def list_subscribed_topic(update: Update, context: CallbackContext):
sub_service = services.HNSubscribeService(repos.RedisPubSubRepository(REDIS_URL))
inline_keyboard_bottons = [
InlineKeyboardButton(text, callback_data=f"{enum}")
for enum, text in sub_service.list_subscribed_topic(
update.message.chat_id
).items()
]
keyboard = [inline_keyboard_bottons]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
"Here is your subscribed topics, you can click botton to unsubscribe topic.",
reply_markup=reply_markup,
)
return UnSubscribeState.FIRST
def subscribe(
update: Update,
context: CallbackContext,
topic: Topic,
) -> int:
query = update.callback_query
query.answer()
sub_service = services.HNSubscribeService(repos.RedisPubSubRepository(REDIS_URL))
sub_service.subscribe(topic, repos.Subscriber(id=query.message.chat_id))
query.edit_message_text(f"Subscribed {sub_service.list_topic()[topic]} !")
return ConversationHandler.END
def unsubscribe(
update: Update,
context: CallbackContext,
topic: Topic,
) -> int:
query = update.callback_query
query.answer()
sub_service = services.HNSubscribeService(repos.RedisPubSubRepository(REDIS_URL))
sub_service.unsubscribe(topic, repos.Subscriber(id=query.message.chat_id))
query.edit_message_text(f"Unsubscribed {sub_service.list_topic()[topic]} !")
return ConversationHandler.END
def publish_topstories(context: CallbackContext):
(
services.NHPublishService(
hn_repo=repos.HNRepository(),
pubsub_repo=repos.RedisPubSubRepository(REDIS_URL),
filters=filters.norm_filter,
)
.add_handler(Topic.top, TopStoriesEventHandler(context.bot))
.publish_stories(Topic.top)
)
def publish_beststories(context: CallbackContext):
(
services.NHPublishService(
hn_repo=repos.HNRepository(),
pubsub_repo=repos.RedisPubSubRepository(REDIS_URL),
filters=filters.norm_filter,
)
.add_handler(Topic.best, BestStoriesEventHandler(context.bot))
.publish_stories(Topic.best)
)
def clear_old_published(context: CallbackContext):
background_serv = services.BackgroundService(
hn_repo=repos.HNRepository(),
pubsub_repo=repos.RedisPubSubRepository(REDIS_URL),
)
for topic in Topic:
background_serv.reduce_published_set_size(topic)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--reset_db",
default=lambda: repos.RedisPubSubRepository(REDIS_URL).flush(),
help="reset db",
action="store_true",
)
parser.parse_args()
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(BOT_TOKEN)
updater.bot.set_my_commands(
[
BotCommand("ping", "ping"),
BotCommand("subscribe", "subscribe topics"),
BotCommand("list_subscribed", "list subscribed topics"),
]
)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("ping", ping_command))
dispatcher.add_handler(
ConversationHandler(
entry_points=[CommandHandler("subscribe", list_topic)],
states={
SubscribeState.FIRST: [
CallbackQueryHandler(
partial(subscribe, topic=Topic.top),
pattern=f"^{Topic.top}$",
),
CallbackQueryHandler(
partial(subscribe, topic=Topic.best),
pattern=f"^{Topic.best}$",
),
]
},
fallbacks=[CommandHandler("subscribe", list_topic)],
)
)
dispatcher.add_handler(
ConversationHandler(
entry_points=[
CommandHandler(
"list_subscribed",
list_subscribed_topic,
)
],
states={
UnSubscribeState.FIRST: [
CallbackQueryHandler(
partial(unsubscribe, topic=Topic.top),
pattern=f"^{Topic.top}$",
),
CallbackQueryHandler(
partial(unsubscribe, topic=Topic.best),
pattern=f"^{Topic.best}$",
),
]
},
fallbacks=[
CommandHandler(
"list_subscribed",
list_subscribed_topic,
)
],
)
)
job_queue = updater.job_queue
job_queue.run_repeating(
publish_topstories,
interval=timedelta(seconds=60),
name="publish_topstories",
)
job_queue.run_repeating(
publish_beststories,
interval=timedelta(seconds=360),
name="publish_beststories",
)
job_queue.run_repeating(
clear_old_published,
interval=timedelta(days=1),
name="clear_old_published",
)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == "__main__":
main()