File size: 9,418 Bytes
530de6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import telegram
from telegram.ext import Updater,CommandHandler,MessageHandler,Filters,ConversationHandler
import os, shutil
from telegram import ReplyKeyboardRemove, ReplyKeyboardMarkup
from youtube import *
import threading

# find port of server 
PORT = int(os.environ.get('PORT',5000))
token = '5728368003:AAFGFs7r1LAJB-flrJ9et5J7Okzgw1_4s_Y'

START_CO, GET_WORD, GET_NUMBER,GET_CHANNEL_URL, GET_URL, CONFIRMATION = range(1, 7)

reply_keyboeard_start = [['Download entire channel'],['Download with searching word'], ['Download one video'], ['See processes'], ['exit']]
markup_start = ReplyKeyboardMarkup(reply_keyboeard_start,resize_keyboard=True, one_time_keyboard=True)

reply_keyboeard_back = [['back', '🏠 home', 'exit']]
markup_back = ReplyKeyboardMarkup(reply_keyboeard_back,resize_keyboard=True, one_time_keyboard=True)

reply_keyboeard_confirmation = [['I confirm'], ['🏠 home', 'exit']]
markup_confirmation = ReplyKeyboardMarkup(reply_keyboeard_confirmation,resize_keyboard=True, one_time_keyboard=True)



def start(update,context):
    update.message.reply_text('Choose between options : ', reply_markup = markup_start)
    return(START_CO)

def start_co(update, context):
    user = update.message.from_user
    text = update.message.text

    remake_folder(str(user.id))

    if text == 'Download entire channel':
        update.message.reply_text('Enter URL of one video on channel you want to download all of that videos.', reply_markup = markup_back)
        return(GET_CHANNEL_URL)

    elif text == 'Download with searching word':
        update.message.reply_text('Enter word you want to search.', reply_markup = markup_back)
        return(GET_WORD)

    elif text == 'Download one video':
        update.message.reply_text('Enter link of that video.', reply_markup = markup_back)
        return(GET_URL)

def get_channel_url(update,context):
    user_data = context.user_data
    text = update.message.text

    if text == 'back':
        update.message.reply_text('Choose ...', reply_markup = markup_start)
        return(START_CO)
    id = find_channel_id(text)
    if id :
        list_of_urls = get_videos_from_channel(id)
        if list_of_urls:
            user_data['list_of_urls'] = list_of_urls
            update.message.reply_text(f'There is {len(list_of_urls)} videos on this channel', reply_markup = markup_confirmation)
            return(CONFIRMATION)
    else:
        update.message.reply_text('Can not find id of channel', reply_markup = markup_start)
        return(START_CO)

def get_word_for_search(update, context):
    user_data = context.user_data
    text = update.message.text

    if text == 'back':
        update.message.reply_text('Choose ...', reply_markup = markup_start)
        return(START_CO)
    
    user_data['search_word'] = text
    update.message.reply_text('How many videos you wanna download ?', reply_markup = markup_back)
    return(GET_NUMBER)

def get_number_of_videos(update, context):
    user_data = context.user_data
    number = update.message.text

    if number == 'back':
        update.message.reply_text('Enter word you want to search.', reply_markup = markup_back)
        return(GET_WORD)
    
    try:
        number = int(number)
    except:
        update.message.reply_text('Wrong input', reply_markup = markup_back)
        return(GET_NUMBER) 

    list_of_urls = find_videos_with_search(user_data['search_word'], number)
    if list_of_urls:
        user_data['list_of_urls'] = list_of_urls
    
    text = f'''
    Search word : {user_data['search_word']}
    Number of videos : {number}
    If it is ok pleas confirm.'''
    update.message.reply_text(text, reply_markup = markup_confirmation)
    return(CONFIRMATION)

def one_video_download(update, context):
    user = update.message.from_user
    text = update.message.text
    url = text.strip()

    if text == 'back':
        update.message.reply_text('Choose ...', reply_markup = markup_start)
        return(START_CO)

    try:
        status = Download(url, user.id)
        if status:
            update.message.reply_video(video = open(status, 'rb'), reply_markup = markup_start)
            # os.remove(status)
            return(START_CO)
        else:
            update.message.reply_text(f"could not download the video {url}", reply_markup = markup_start)
            return(START_CO)
    except:
        update.message.reply_text(f"could not download {url}", reply_markup = markup_start)
        return(START_CO)
        

# test
def do_downloading(user_data, user, update):

    for url in user_data['list_of_urls']:
        try:
            status = Download(url['url'], user.id)
            if status:
                update.message.reply_video(video = open(status, 'rb'), caption = url['title'])
                # os.remove(status)
            else:
                update.message.reply_text(f"could not download the video {url['url']}")
                continue
        except:
            update.message.reply_text(f"could not download {url['url']}", reply_markup = ReplyKeyboardRemove())
            continue

def how_many_thread_is_alive(update, context):
    user_data = context.user_data

    counter = 0
    if user_data.get('thread'):
        for i in user_data['thread']:
            if i.is_alive():
                counter += 1

    update.message.reply_text(f'there is {counter} process is going.', reply_markup = markup_start)
    return(START_CO)

def confirmation(update, context):
    user_data = context.user_data
    user = update.message.from_user
    text = update.message.text

    if text != 'I confirm':
        update.message.reply_text('Choose ...', reply_markup = markup_start)
        return(START_CO)

    t = threading.Thread(target=do_downloading, args=(user_data, user, update))
    t.start()
    user_data['thread'].append(t)


    update.message.reply_text('finish proces', reply_markup = markup_start)
    return(START_CO)


def stop_conversation(update,context):
    update.message.reply_text('goodbye' , reply_markup = ReplyKeyboardRemove())
    return(ConversationHandler.END)

def cancle(update,context):
    update.message.reply_text('bye' , reply_markup = ReplyKeyboardRemove())
    return(ConversationHandler.END)

def timeout(update, context):
    user = update.message.from_user
    try:
        remake_folder(str(user.id))
    except:
        pass

    update.message.reply_text('the time is out.',reply_markup = ReplyKeyboardRemove())

def error(update,context):
    print(update,context.error)















# info of bot and chanal
bot = telegram.Bot(token=token)

def main():
    updater = Updater(token, use_context=True)
    dp = updater.dispatcher

    # ---------------------------------------------->>>> User Bot Handler
    conv_handler = ConversationHandler(
        entry_points = [CommandHandler('start', start)],


        states = states,

        fallbacks = [CommandHandler('cancle', start), CommandHandler('start', start), MessageHandler(Filters.regex('^exit$'), stop_conversation),
                    MessageHandler(Filters.regex('^🏠 home$'), start_co)],

        conversation_timeout = 50000, 
    )


    dp.add_handler(conv_handler)

    dp.add_error_handler(error)

    print('trying to connect to telegram api ...')

    updater.start_polling()
    

    # updater.start_webhook(listen='0.0.0.0',port=PORT,url_path=TOKEN)
    # updater.bot.set_webhook('https://clashbazar.com/' + TOKEN )

    print('connected to telegram api : 200 ')

    updater.idle()



def remake_folder(folder_name):

    folder_name = f'Downloads/{folder_name}'        

    if os.path.exists(folder_name):
        for filename in os.listdir(folder_name):
            file_path = os.path.join(folder_name, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print('Failed to delete %s. Reason: %s' % (file_path, e))

    else:
        os.mkdir(folder_name)



if __name__ == '__main__':


    same = [CommandHandler('cancle', cancle), MessageHandler(Filters.regex('^exit$'), stop_conversation), MessageHandler(Filters.regex('^🏠 home$'), start)]


    states = {
            START_CO : [CommandHandler('start', start),
                        MessageHandler(Filters.regex('^Download entire channel$'), start_co),
                        MessageHandler(Filters.regex('^Download with searching word$'), start_co),
                        MessageHandler(Filters.regex('^Download one video$'), start_co),
                        MessageHandler(Filters.regex('^See processes$'), how_many_thread_is_alive),
                        ],
            
            GET_WORD : same + [CommandHandler('start', start), MessageHandler(Filters.text , get_word_for_search)],

            GET_NUMBER : same + [CommandHandler('start', start), MessageHandler(Filters.text , get_number_of_videos)],

            GET_CHANNEL_URL : same + [CommandHandler('start', start), MessageHandler(Filters.text , get_channel_url)],

            GET_URL : same + [CommandHandler('start', start), MessageHandler(Filters.text , one_video_download)],

            CONFIRMATION : [CommandHandler('start', start), MessageHandler(Filters.regex('^I confirm$'), confirmation)],

            

    }

    main()