-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstagramFeedBot.py
306 lines (244 loc) · 11.7 KB
/
instagramFeedBot.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
import telegram
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, InlineQueryHandler
from telegram.ext import BaseFilter, MessageHandler, Filters
import argparse
import instagramFeeder
import logging
telegramLogger = logging.getLogger('telegram')
telegramLogger.setLevel(logging.INFO)
logger = logging.getLogger()
argumentsDescMsg = 'Bot initialization parameters.'
tokenArgHelp = 'telegram token'
feederDBHelp = 'feeder DB path'
firstCheckArgHelp = 'seconds to make the first check'
checkTimeArgHelp = 'seconds to check for new publications'
numbOfPostsHelp = 'posts to check from instagram account'
maxAccsPerUserHelp = 'max accounts per telegram user'
maxKeywsPerAccHelp = 'max keywords per account'
userIdHelp = 'user id to limit the bot usage'
startMsg = 'Hello! Im the Instagram Feed bot, you can find out what I can do with /help'
helpMsg = 'This is a list of the functions I know:\n'
noParamsGivenMsg = 'Please send the command with valid parameters.'
noLastPostsMsg = 'No posts found.'
maxAccountsReachedMsg = 'The maximum subscriptions are %s. You added %s, remaining %s.'
maxKeywordsReachedMsg = 'The maximum keywords for each account is %s. You added %s to this account, remaining %s.'
functionsHelp = "/addaccounts username1 username2 username3 ...\nAdds one or more accounts by their usernames.\n\n/addkeywords username keyword1 keyword2 ...\nAdds one or more keywords to the username's account.\n\n/deleteaccounts username1 username2 username3 ...\nDeletes all accounts with given usernames.\n\n/deletekeywords username keyword1 keyword2 ...\nDeletes all given keywords from given username's account.\n\n/enableall username1 username2 username3 ...\nEnables all posts from each username's account. Set as default.\n\n/enablekeywords username1 username2 username3 ...\nEnables only posts containing each username's account keywords.\n\n/listaccounts\nI'll send a list of all present accounts.\n\n/listkeywords username\nI'll send a list of all the keywords of that username's account.\n\n/lastposts [amount] username1 username2 ...\nIll search and send you the last [amount] posts of the given username's accounts. If no amount if given, Ill use the default 2, and the maximum posts to get is 12."
checkTimeDefault = 12*60*60
firstCheckDefault = 60
numberOfPostsDef = 5
userIdDef = -1
maxAccsPerUserDef = 20
maxKeywsPerAccDef = 100
def parse_input():
parser = argparse.ArgumentParser(description=argumentsDescMsg, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('token', metavar='TOKEN', type=str, help=tokenArgHelp)
parser.add_argument('feederDB', metavar='FEEDER DB', type=str, help=feederDBHelp)
parser.add_argument('-fc', metavar='FIRST CHECK', type=int, default=firstCheckDefault, help=firstCheckArgHelp)
parser.add_argument('-ct', metavar='CHECK TIME', type=int, default=checkTimeDefault, help=checkTimeArgHelp)
parser.add_argument('-np', metavar='NUMBER OF POSTS', type=int, default=numberOfPostsDef, help=numbOfPostsHelp)
parser.add_argument('-mau', metavar='MAX ACCS PER USER', type=int, default=maxAccsPerUserDef, help=maxAccsPerUserHelp)
parser.add_argument('-mka', metavar='MAX KEYWS PER ACCOUNT', type=int, default=maxKeywsPerAccDef, help=maxKeywsPerAccHelp)
parser.add_argument('-uid', metavar='USER ID', type=int, default=userIdDef, help=userIdHelp)
args = parser.parse_args()
return args
def log_user_msg(func):
def log_and_call(bot, update):
chatId = update.message.chat_id
params = update.message.text
logger.info(str(chatId)+', '+params)
return func(bot, update)
return log_and_call
def log_errors(userId, errors):
if errors!=[]: logger.error(str(userId)+', '+str(errors))
def check_user_msg_not_empty(func):
def check_and_call(bot, update):
chatId = update.message.chat_id
params = update.message.text.split()[1::]
if len(params) != 0:
return func(bot, update)
bot.send_message(chat_id=chatId, text=noParamsGivenMsg)
return check_and_call
def tryexcept(errors, func, *args):
try:
if len(args)==2:
return func(args[0], args[1])
elif len(args)==3:
return func(args[0], args[1], args[2])
except ValueError as e:
errors.append(str(e))
except instagramFeeder.requests.exceptions.HTTPError as e:
errors.append(str(e))
def process_reply_msg(errors):
replyMsg = 'Command executed excepting: '+str(errors)[1:-1]
if errors==[]: replyMsg='Command executed successfully!'
return replyMsg
@log_user_msg
@check_user_msg_not_empty
def add_accounts(bot, update):
userId = update.message.chat_id
usernames = update.message.text.split()[1::]
crrnAccsAmnt = len(instagramFeeder.list_usernames(userId))
addAccsAmnt = len(usernames)
if crrnAccsAmnt+addAccsAmnt > botArgs.mau:
remaining = botArgs.mau-crrnAccsAmnt
bot.send_message(chat_id=userId, text=maxAccountsReachedMsg%(botArgs.mau, crrnAccsAmnt, remaining))
return
errors = []
for username in usernames:
tryexcept(errors, instagramFeeder.add_account, userId, username)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
@check_user_msg_not_empty
def add_keywords(bot, update):
userId = update.message.chat_id
userMsg = update.message.text.split()[1::]
username = userMsg[0]
keywords = userMsg[1::]
crrnKeywsAmnt = len(instagramFeeder.list_keywords(userId, username))
addKeywsAmnt = len(keywords)
if crrnKeywsAmnt+addKeywsAmnt > botArgs.mka:
remaining = botArgs.mka-crrnKeywsAmnt
bot.send_message(chat_id=userId, text=maxKeywordsReachedMsg%(botArgs.mka, crrnKeywsAmnt, remaining))
return
errors = []
for keyword in keywords:
tryexcept(errors, instagramFeeder.add_keyword, userId, username, keyword)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
@check_user_msg_not_empty
def delete_accounts(bot, update):
userId = update.message.chat_id
usernames = update.message.text.split()[1::]
errors = []
for username in usernames:
tryexcept(errors, instagramFeeder.delete_account, userId, username)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
@check_user_msg_not_empty
def delete_keywords(bot, update):
userId = update.message.chat_id
userMsg = update.message.text.split()[1::]
username = userMsg[0]
keywords = userMsg[1::]
errors = []
for keyword in keywords:
tryexcept(errors, instagramFeeder.delete_keyword, userId, username, keyword)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
def enable_all(bot, update):
userId = update.message.chat_id
usernames = update.message.text.split()[1::]
errors = []
for username in usernames:
tryexcept(errors, instagramFeeder.enable_all, userId, username)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
def enable_keywords(bot, update):
userId = update.message.chat_id
usernames = update.message.text.split()[1::]
errors = []
for username in usernames:
tryexcept(errors, instagramFeeder.enable_keywords, userId, username)
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
@log_user_msg
def list_username_accounts(bot, update):
userId = update.message.chat_id
usernames = [u for u in instagramFeeder.list_usernames(userId)]
replyMsg = '\n'.join(usernames)
if len(usernames)==0:
replyMsg = 'There are no accounts added yet.'
logger.warning(str(userId)+', '+replyMsg)
bot.send_message(chat_id=userId, text=replyMsg)
@log_user_msg
@check_user_msg_not_empty
def list_keywords(bot, update):
userId = update.message.chat_id
username = update.message.text.split()[1]
replyMsg = ''
try:
keywords = [k for k in instagramFeeder.list_keywords(userId, username)]
if keywords==[]:
replyMsg = 'There are no keywords added yet for %s.'%(username)
logger.warning(str(userId)+', '+replyMsg)
else: replyMsg = ' '.join(keywords)
except ValueError as e:
replyMsg = str(e)
logger.error(str(userId)+', '+replyMsg)
bot.send_message(chat_id=userId, text=replyMsg)
@log_user_msg
@check_user_msg_not_empty
def get_last_n_posts(bot, update):
userId = update.message.chat_id
userMsg = update.message.text.split()[1::]
nPosts = 2
usernames = userMsg[0::]
try:
nPosts = int(userMsg[0])
usernames = userMsg[1::]
except: pass
errors = []
links = []
for username in usernames:
res = tryexcept(errors, instagramFeeder.get_last_n_posts, userId, username, nPosts)
if res!=None: links+=res
if len(errors)!=0:
log_errors(userId, errors)
bot.send_message(chat_id=userId, text=process_reply_msg(errors))
if len(links)!=0:
for link in links:
logger.debug(str(userId)+', get_last_n_posts, '+link)
bot.send_message(chat_id=userId, text=link)
elif len(errors)==0: bot.send_message(chat_id=userId, text=noLastPostsMsg)
@log_user_msg
def start(bot, update):
bot.send_message(chat_id=update.message.chat_id, text=startMsg)
@log_user_msg
def help(bot, update):
bot.send_message(chat_id=update.message.chat_id, text=helpMsg+functionsHelp)
def check_feed(bot, job):
#should improve this
feedees = instagramFeeder.list_feedees_ids()
for feedee in feedees:
usernames = instagramFeeder.list_usernames(feedee)
for username in usernames:
posts = instagramFeeder.get_last_posts(feedee, username, botArgs.np)
for post in posts:
logger.debug(str(feedee)+', check_feed, '+post)
bot.send_message(chat_id=feedee, text=post)
class FilterUserId(BaseFilter):
def filter(self, message):
return botArgs.uid==-1 or botArgs.uid == message.from_user.id
def main():
logger.info('Started running')
global botArgs
botArgs = parse_input()
logger.info('Bot arguments: '+str(vars(botArgs)))
instagramFeeder.bind_db('sqlite', botArgs.feederDB)
filterUseId = FilterUserId()
updater = Updater(botArgs.token)
updater.dispatcher.add_handler(CommandHandler('start', start, filterUseId))
updater.dispatcher.add_handler(CommandHandler('help', help, filterUseId))
updater.dispatcher.add_handler(CommandHandler('addaccounts', add_accounts, filterUseId))
updater.dispatcher.add_handler(CommandHandler('addkeywords', add_keywords, filterUseId))
updater.dispatcher.add_handler(CommandHandler('listaccounts', list_username_accounts, filterUseId))
updater.dispatcher.add_handler(CommandHandler('listkeywords', list_keywords, filterUseId))
updater.dispatcher.add_handler(CommandHandler('deleteaccounts', delete_accounts, filterUseId))
updater.dispatcher.add_handler(CommandHandler('deletekeywords', delete_keywords, filterUseId))
updater.dispatcher.add_handler(CommandHandler('enableall', enable_all, filterUseId))
updater.dispatcher.add_handler(CommandHandler('enablekeywords', enable_keywords, filterUseId))
updater.dispatcher.add_handler(CommandHandler('lastposts', get_last_n_posts, filterUseId))
job = updater.job_queue
job.run_repeating(check_feed, interval=botArgs.ct, first=botArgs.fc)
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process_reply_msg receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
if __name__ == "__main__":
main()