This repository has been archived by the owner on Dec 9, 2022. It is now read-only.
forked from cbrgm/telegram-robot-rss
-
Notifications
You must be signed in to change notification settings - Fork 1
/
robotrss.py
345 lines (283 loc) · 13.4 KB
/
robotrss.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# /usr/bin/env python3
# encoding: utf-8
from uuid import uuid4
from telegram.ext import Updater, InlineQueryHandler, CommandHandler, MessageHandler, Filters
from telegram import ParseMode, InlineQueryResultPhoto
from telegram.error import Unauthorized, TelegramError, BadRequest
from util.database import DatabaseHandler
from util.processing import BatchProcess
from util.feedhandler import FeedHandler
from util.inventoryhandler import InventoryHandler
from util.scheduler import Scheduler
import logging
import os
class RobotRss(object):
def __init__(self, telegram_token, update_interval):
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Initialize bot internals
self.db = DatabaseHandler("resources/userdata/datastore.db")
self.inventory = InventoryHandler()
# Register webhook to telegram bot
self.updater = Updater(telegram_token)
self.dispatcher = self.updater.dispatcher
# Add Commands to bot
self._add_command(CommandHandler("start", self.start))
self._add_command(CommandHandler("stop", self.stop))
self._add_command(CommandHandler("help", self.help))
self._add_command(CommandHandler("list", self.list))
self._add_command(CommandHandler("about", self.about))
self._add_command(CommandHandler("add", self.add, pass_args=True))
self._add_command(CommandHandler("get", self.get, pass_args=True))
self._add_command(CommandHandler("remove", self.remove, pass_args=True))
self._add_command(CommandHandler("addgroup", self.add_group, pass_args=True))
self._add_command(CommandHandler("search", self.inventory_search, pass_args=True))
self._add_command(CommandHandler("aanmeld_status", self.aanmeld_status))
self._add_command(MessageHandler(Filters.text, self.text_message))
self._add_command(InlineQueryHandler(self.inlinequery))
# Start the Bot
self.processing = BatchProcess(
database=self.db, update_interval=update_interval, bot=self.dispatcher.bot)
self.scheduler = Scheduler(bot=self.dispatcher.bot)
self.processing.start()
self.scheduler.start()
self.updater.start_polling()
self.updater.idle()
def _add_command(self, command):
"""
Registers a new command to the bot
"""
self.updater.dispatcher.add_handler(command)
def inlinequery(self, update, context):
query = update.inline_query.query
print(query)
searchresults = self.inventory.search_many(query)
print(searchresults)
queryresults = []
for result in searchresults:
queryresult = InlineQueryResultPhoto(
id=str(uuid4()),
title=result[0],
description=result[1],
caption="<b>Voorwerp</b>: {}\n<b>Omschrijving:</b> {}\n<b>Locatie:</b> {}".format(result[0], result[1],
result[2]),
parse_mode="HTML",
photo_url=result[3],
thumb_url=result[3])
queryresults.append(queryresult)
update.inline_query.answer(queryresults)
def start(self, update, context):
"""
Send a message when the command /start is issued.
"""
telegram_user = update.message.from_user
# Add new User if not exists
if not self.db.get_user(telegram_id=telegram_user.id):
message = "Hee, jou ken ik nog niet.. Ik stop je ff in mijn database, momentje."
update.message.reply_text(message)
self.db.add_user(telegram_id=telegram_user.id,
username=telegram_user.username,
firstname=telegram_user.first_name,
lastname=telegram_user.last_name,
language_code=telegram_user.language_code,
is_bot=telegram_user.is_bot,
is_active=1)
self.db.update_user(telegram_id=telegram_user.id, is_active=1)
message = "Je krijgt nu persoonlijk nieuws. Tik /help voor de commando's"
update.message.reply_text(message)
def add(self, update, context):
"""
Adds a rss subscription to user
"""
telegram_user = update.message.from_user
if len(context.args) != 2:
message = "Ja, daar snap dus ik dus niks van. Probeer dit eens:\n" \
" /add <url> <naampje>"
update.message.reply_text(message)
return
arg_url = FeedHandler.format_url_string(string=context.args[0])
arg_entry = context.args[1]
# Check if argument matches url format
if not FeedHandler.is_parsable(url=arg_url):
message = "Die url lijkt niet helemaal lekker!"
update.message.reply_text(message)
return
# Check if entry does not exists
entries = self.db.get_urls_for_user(telegram_id=telegram_user.id)
if any(arg_url.lower() in entry for entry in entries):
message = "Deze url heb je al toegevoegd!"
update.message.reply_text(message)
return
if any(arg_entry in entry for entry in entries):
message = "Je hebt hetzelfde naampje gebruikt als een andere url, da ga nie"
update.message.reply_text(message)
return
self.db.add_user_bookmark(
telegram_id=telegram_user.id, url=arg_url.lower(), alias=arg_entry)
message = "Hij staat erbij! Gebruik /list als je me niet gelooft"
update.message.reply_text(message)
def get(self, update, context):
"""
Manually parses an rss feed
"""
telegram_user = update.message.from_user
if len(context.args) > 2:
message = "To get the last news of your subscription please use /get <entryname> [optional: <count 1-10>]. Make sure you first add a feed using the /add command."
update.message.reply_text(message)
return
if len(context.args) == 2:
args_entry = context.args[0]
args_count = int(context.args[1])
else:
args_entry = context.args[0]
args_count = 4
url = self.db.get_user_bookmark(
telegram_id=telegram_user.id, alias=args_entry)
if url is None:
message = "I can not find an entry with label " + \
args_entry + " in your subscriptions! Please check your subscriptions using /list and use the delete command again!"
update.message.reply_text(message)
return
entries = FeedHandler.parse_feed(url[0], args_count)
for entry in entries:
message = "[" + url[1] + "] <a href='" + \
entry.link + "'>" + entry.title + "</a>"
print(message)
try:
update.message.reply_text(message, parse_mode=ParseMode.HTML)
except Unauthorized:
self.db.update_user(telegram_id=telegram_user.id, is_active=0)
except TelegramError as e:
# handle all other telegram related errors
print("Telegram error: {0}".format(e.message))
pass
def remove(self, update, context):
"""
Removes an rss subscription from user
"""
telegram_user = update.message.from_user
if len(context.args) != 1:
message = "To remove a subscriptions from your list please use /remove <entryname>. " \
"To see all your subscriptions along with their entry names use /list !"
update.message.reply_text(message)
return
entry = self.db.get_user_bookmark(
telegram_id=telegram_user.id, alias=context.args[0])
if entry:
self.db.remove_user_bookmark(
telegram_id=telegram_user.id, url=entry[0])
message = "I removed " + context.args[0] + " from your subscriptions!"
update.message.reply_text(message)
else:
message = "I can not find an entry with label " + \
context.args[0] + " in your subscriptions! Please check your subscriptions using /list and use the delete command again!"
update.message.reply_text(message)
def list(self, update, context):
"""
Displays a list of all user subscriptions
"""
telegram_user = update.message.from_user
message = "Hier is het lijstje met url's en groepen/users:"
update.message.reply_text(message)
# Group URL's
entries = self.db.get_channels()
for entry in entries:
message = "[" + entry[0] + "]\n " + entry[1]
update.message.reply_text(message)
# User URL's
entries = self.db.get_urls_for_user(telegram_id=telegram_user.id)
for entry in entries:
message = "[" + entry[1] + "]\n " + entry[0]
update.message.reply_text(message)
def help(self, update, context):
"""
Send a message when the command /help is issued.
"""
message = "Ik snap de volgende commando's:\n" \
"/help: Deze helptekst\n" \
"/about: Info over deze bot\n" \
"/start: Zet het sturen van nieuwsupdates aan\n" \
"/stop: Stop met sturen van nieuwsupdates\n" \
"/list: Geef een lijst van feeds\n" \
"/add <url> <naam>: Voeg een nieuwe feed toe\n" \
"/addgroup <url> <@grouphandle>\n" \
"/search <keyword>: Zoek in de DJO inventaris\n" \
"/aanmeld_status: Rapporteer de aanmeld status in de DJO chat"
update.message.reply_text(message)
def stop(self, update, context):
"""
Stops the bot from working
"""
telegram_user = update.message.from_user
self.db.update_user(telegram_id=telegram_user.id, is_active=0)
message = "Jahaaa, ik stop al."
update.message.reply_text(message)
def about(self, update, context):
"""
Shows about information
"""
message = "Dit is de officiele DJO Amersfoort Telegram Bot. Hier staat mijn source: " \
" <a href='https://github.com/djoamersfoort/djo-telegram-bot'>Github</a>."
update.message.reply_html(message)
def add_group(self, update, context):
if len(context.args) != 2:
message = "Ja, daar snap ik dus helemaal niks van. Probeer dit eens:\n" \
"/addgroup <url> <groupame>"
update.message.reply_text(message)
return
arg_url = FeedHandler.format_url_string(string=context.args[0])
arg_channel = context.args[1]
# Check if argument matches url format
if not FeedHandler.is_parsable(url=arg_url):
message = "Die url lijkt niet helemaal lekker!"
update.message.reply_text(message)
return
if not arg_channel.startswith('@'):
message = "Een groepnaam moet met @ starten"
update.message.reply_text(message)
return
channels = self.db.get_channels()
if any(channel[0] == arg_channel and channel[1] == arg_url for channel in channels):
update.message.reply_text("Deze url is al aanwezig voor deze groep!")
return
# Add the channel + url
self.db.add_url(arg_url)
self.db.add_channel(arg_channel, arg_url)
message = "Channel en url zijn toegevoegd!"
update.message.reply_text(message)
def inventory_search(self, update, context):
if not len(context.args) >= 1:
update.message.reply_text('Waar wil je naar zoeken?')
return
keyword = ' '.join(context.args[0:])
(text, image) = self.inventory.search(keyword)
if image is not None:
print(image)
try:
update.message.reply_photo(image, quote=False, caption=text, parse_mode=ParseMode.HTML)
except BadRequest as e:
# Photo url unreachable / broken -> send text version
text += '\n<b>OEI</b>: Er is ook een foto, maar die kon niet opgehaald worden :('
update.message.reply_html(text, quote=False)
else:
update.message.reply_html(text, quote=False)
def aanmeld_status(self, update, context):
sender = update.message.from_user
print(f"Aanmeld status called by: {sender.id}, {sender.username}, {sender.first_name}, {sender.last_name}")
if sender.id == 517935455:
self.scheduler.send_free_member_slots()
else:
update.message.reply_text("Stout!")
def text_message(self, update, context):
if "kom vechten" in update.message.text.lower():
print("Iemand wil vechten")
update.message.reply_document('https://i.kym-cdn.com/photos/images/original/001/356/324/914.gif')
if "joch" in update.message.text.lower():
message = "je bent zelf een joch"
update.message.reply_text(message)
if __name__ == '__main__':
# Load Credentials
telegram_bot_token = os.environ.get("BOT_TOKEN", "invalid")
update_interval = os.environ.get("UPDATE_INTERVAL", 300)
# Pass Credentials to bot
RobotRss(telegram_token=telegram_bot_token, update_interval=update_interval)