-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
470 lines (391 loc) · 15.8 KB
/
main.py
File metadata and controls
470 lines (391 loc) · 15.8 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import psycopg2
import profile
from instaloader import Instaloader, Profile, Post
import logging
from typing import Dict
import instaloader
import hashlib
import post
import story
from telegram import (
ReplyKeyboardMarkup,
TelegramError,
Update,
ReplyKeyboardRemove,
Bot,
User
)
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
# ======= Enable logging ==========
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
global Username
global Password
global instagram
instagram = instaloader.Instaloader()
# ======= add bot token ========
admin_id = 111111 # put your user id in telegram
TOKEN = "Your Token"
bot = Bot(TOKEN)
logger = logging.getLogger(__name__)
# ======== add keyboard =========
CHOOSING, TYPING_REPLY_FOR_PROFILE, GET_LOGIN_DATA, LOGIN, TYPING_REPLY_FOR_POST, TYPING_REPLY_FOR_STORY , TYPING_REPLY_FOR_REELS, TYPING_REPLY_FOR_HIGHLIGHT, CHOOSING_DOWNLOAD_STORY, CHOOSING_ADMIN, USER_COUNT, SEND_MESSAGE_TO_ALL = range(12)
reply_keyboard = [
['Download Post', 'Download Story', 'Download Reels'],
['Download Profile', 'Login'],
['About']
]
story_keyboard = [
['Download Story' , 'Download Highlight'],
['Back']
]
admin_keyboard = [
['User Count', 'Send Message To All'],
['Back']
]
admin_markup = ReplyKeyboardMarkup(
admin_keyboard, one_time_keyboard=True, resize_keyboard=True)
story_markup = ReplyKeyboardMarkup(
story_keyboard, one_time_keyboard=True, resize_keyboard=True)
markup = ReplyKeyboardMarkup(
reply_keyboard, one_time_keyboard=True, resize_keyboard=True)
# ====== when start bot call this function ========
def start(update: Update, context: CallbackContext) -> int:
user_id = update.effective_user.id
first_name = update.effective_user.first_name
last_name = update.effective_user.last_name
connection = psycopg2.connect(database="database name", user="user name", password="password", host="host name", port="5432")
cursor = connection.cursor()
query = "CREATE TABLE IF NOT EXISTS user (userId INTEGER PRIMARY KEY,first_name varchar (60),last_family varchar (60));"
cursor.execute(query)
try:
cursor.execute(f'INSERT INTO user (userId,first_name, last_family) Values (%s, %s, %s)',(user_id,first_name,last_name))
except psycopg2.IntegrityError:
pass
connection.commit()
"""Start the conversation and ask user for input."""
update.message.reply_text(
f"hi {first_name} welcome to instagram downloader bot\n"
"\n"
"You can download anything you want from Instagram through this robot\n"
"\n"
"If you want to download posts, stories and rails in high quality, first log in to your Instagram account via the login button and then download your profile or post via the download button.",
reply_markup=markup,
)
return CHOOSING
def choice_download_profile(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Please enter your Instagram idea in the following format:\n'
"\n"
"@username")
return TYPING_REPLY_FOR_PROFILE
def received_information_profile(update: Update, context: CallbackContext) -> int:
try:
username = update.message.text
username_corrected = username.split('@')
profile.download_profile_hd(
username_corrected, bot, update, Username, Password)
return CHOOSING
except NameError:
profile.download_profile_sd(
username_corrected, bot, update)
return CHOOSING
def choice_download_post(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Please send the post link :')
return TYPING_REPLY_FOR_POST
def received_information_post(update: Update, context: CallbackContext) -> int:
try:
global Username
global Password
message = update.message.text
link_of_post = message.split('/')
post.download(link_of_post[4],bot,update,Username, Password)
return CHOOSING
except NameError:
bot.sendMessage(update.effective_user.id, "To download the first post, you must log in via the 'Login' button")
return CHOOSING
except IndexError:
bot.sendMessage(update.effective_user.id, "There is a problem, try again ...")
return CHOOSING
def choice_download_story_or_highlight(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Do you want to download a regular story or highlight stories ?', reply_markup=story_markup)
return CHOOSING_DOWNLOAD_STORY
def choice_download_story(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Send the story link :', reply_markup=markup)
return TYPING_REPLY_FOR_STORY
def choice_download_highlight(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Please enter your Instagram idea in the following format :\n'
"\n"
"@username", reply_markup=markup)
return TYPING_REPLY_FOR_HIGHLIGHT
def received_information_story(update: Update, context: CallbackContext) -> int:
try:
global Username
global Password
message = update.message.text.split('/')
username = message[4]
if username == 'highlights':
bot.sendMessage(update.effective_user.id, "The link entered is incorrect !")
return CHOOSING
story.download(username,bot,update,Username, Password)
return CHOOSING
except NameError:
bot.sendMessage(update.effective_user.id, "To download the first story, you must log in via the 'Login' button")
return CHOOSING
except IndexError:
bot.sendMessage(update.effective_user.id, "There is a problem, try again ...")
return CHOOSING
except instaloader.exceptions.ProfileNotExistsException:
bot.sendMessage(update.effective_user.id, "The link entered is incorrect!")
return CHOOSING
def received_information_highlight(update: Update, context: CallbackContext) -> int:
try:
global Username
global Password
message = update.message.text.split('@')
username = message[1]
story.download_highlight(username,bot,update,Username, Password)
return CHOOSING
except NameError:
bot.sendMessage(update.effective_user.id, "To download the first story, you must log in via the 'Login' button")
return CHOOSING
except IndexError:
bot.sendMessage(update.effective_user.id, "There is a problem, try again ...")
return CHOOSING
except instaloader.exceptions.ProfileNotExistsException:
bot.sendMessage(update.effective_user.id, "The link entered is incorrect!")
return CHOOSING
def choice_download_reels(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Please send the reels link:')
return TYPING_REPLY_FOR_REELS
def received_information_reels(update: Update, context: CallbackContext) -> int:
try:
global Username
global Password
message = update.message.text
link_of_post = message.split('/')
post.download(link_of_post[4],bot,update,Username, Password)
return CHOOSING
except NameError:
bot.sendMessage(update.effective_user.id, "To download the first rails, you must enter through the 'Login' button")
return CHOOSING
except IndexError:
bot.sendMessage(update.effective_user.id, "There is a problem, try again ...")
return CHOOSING
def done(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
" ✔ دانلود شما تموم شد",
reply_markup=markup,
)
return CHOOSING
def back(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
"Return to Home",
reply_markup=markup
)
return CHOOSING
def about(update: Update, context: CallbackContext) -> int:
bot.send_message(update.message.chat.id, """
\n You can also help me develop this robot:
\n https://github.com/rzashakeri/instagram-downloader-bot
""", parse_mode='Markdown')
return CHOOSING
def connect_instagram(update: Update, context: CallbackContext) -> int:
bot.sendMessage(update.effective_user.id, "Note that your information is stored as a session in the robot and to ensure you can use a fake account to download quality content")
update.message.reply_text('Please enter your Instagram username and password in the following format:\n'
"\n"
"username\n"
"password")
bot.sendMessage(update.effective_user.id, "Enter your username instead of username and your password instead of password")
return LOGIN
def login_instagram(update: Update, context: CallbackContext) -> int:
try:
message = update.message.text.split('\n')
global Username
Username = message[0]
global Password
Password = message[1]
if instagram.load_session_from_file(Username, filename=f'sessions/{Username}_{update.effective_user.id}') is None:
update.message.reply_text(
"You have already logged in",
reply_markup=markup,
)
except FileNotFoundError:
try:
instagram.login(Username,Password)
update.message.reply_text(
"You are logged in\nClick the profile download button and download the profile picture in high quality",
reply_markup=markup,
)
instagram.save_session_to_file(filename=f'sessions/{Username}_{update.effective_user.id}')
except instaloader.BadCredentialsException:
update.message.reply_text(
"Please enter your username or password correctly",
reply_markup=markup,
)
return GET_LOGIN_DATA
except instaloader.exceptions.TwoFactorAuthRequiredException:
bot.sendMessage(update.effective_user.id, "Two-step verification is enabled, please disable it first and try again later")
return CHOOSING
except IndexError:
bot.sendMessage(update.effective_user.id, "There is a problem, try again ...")
return CHOOSING
return CHOOSING
def admin(update: Update, context: CallbackContext) -> int:
if update.effective_user.id == admin_id:
update.message.reply_text('You are logged in as admin', reply_markup=admin_markup)
return CHOOSING_ADMIN
else:
pass
return CHOOSING
def user_count(update: Update, context: CallbackContext) -> int:
connection = psycopg2.connect(database="database name", user="user name", password="password", host="host name", port="5432")
cursor = connection.cursor()
query = "SELECT COUNT(*) FROM user"
cursor.execute(query)
user_count = cursor.fetchone()
bot.sendMessage(update.effective_user.id, f"user count : {user_count[0]}")
return CHOOSING_ADMIN
def get_message(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Enter the message you want to send to everyone :', reply_markup=admin_markup)
return SEND_MESSAGE_TO_ALL
def send_message_to_all(update: Update, context: CallbackContext) -> int:
connection = psycopg2.connect(database="database name", user="user name", password="password", host="host name", port="5432")
cursor = connection.cursor()
query = "SELECT userid FROM user"
cursor.execute(query)
users = cursor.fetchall()
message = update.message.text
for user in users:
bot.sendMessage(chat_id=user[0], text=message)
bot.sendMessage(update.effective_user.id, 'Your message has been successfully sent')
return CHOOSING_ADMIN
def main() -> None:
"""Run the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSING: [
MessageHandler(
Filters.regex(
'^(Download Profile)$'), choice_download_profile
),
MessageHandler(
Filters.regex(
'^(About)$'), about
),
MessageHandler(
Filters.regex(
'^(Login)$'), connect_instagram
),
MessageHandler(
Filters.regex(
'^(Download Post)$'), choice_download_post
),
MessageHandler(
Filters.regex(
'^(Download Story)$'), choice_download_story_or_highlight
),
MessageHandler(
Filters.regex(
'^(Download Reels)$'), choice_download_reels
),
CommandHandler('admin', admin)
],
TYPING_REPLY_FOR_PROFILE: [
MessageHandler(
Filters.text,
received_information_profile,
)
],
LOGIN: [
MessageHandler(
Filters.text,
login_instagram,
)
],
GET_LOGIN_DATA:[
MessageHandler(
Filters.text,
connect_instagram,
)
],
TYPING_REPLY_FOR_POST:[
MessageHandler(
Filters.text,
received_information_post,
)
],
TYPING_REPLY_FOR_STORY:[
MessageHandler(
Filters.text,
received_information_story,
)
],
TYPING_REPLY_FOR_REELS:[
MessageHandler(
Filters.text,
received_information_reels,
)
],
CHOOSING_DOWNLOAD_STORY:[
MessageHandler(
Filters.regex(
'^(Download Story)$'), choice_download_story
),
MessageHandler(
Filters.regex(
'^(Download Highlight)$'), choice_download_highlight
),
MessageHandler(
Filters.regex(
'^(Back)$'), back
)
],
TYPING_REPLY_FOR_HIGHLIGHT:[
MessageHandler(
Filters.text,
received_information_highlight,
)
],
CHOOSING_ADMIN:[
MessageHandler(
Filters.regex(
'^(User Count)$'), user_count
),
MessageHandler(
Filters.regex(
'^(Back)$'), back
),
MessageHandler(
Filters.regex(
'^(Send Message To All)$'), get_message
)
],
SEND_MESSAGE_TO_ALL:[
MessageHandler(
Filters.text,
send_message_to_all
)
],
},
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)]
)
dispatcher.add_handler(conv_handler)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()