aheskandani commited on
Commit
cd68418
Β·
1 Parent(s): 305604a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -0
app.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telegram.ext.filters import Filters
2
+ from telegram.ext.messagehandler import MessageHandler
3
+ from telegram import ParseMode
4
+ from telegram.ext import Updater, CommandHandler, ConversationHandler, CallbackQueryHandler
5
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ForceReply, ReplyKeyboardMarkup
6
+ import urllib.request
7
+ from threading import Thread
8
+ from random import randint
9
+ import os
10
+
11
+
12
+ def start(update, context):
13
+ def thread_function(update, context):
14
+ chat_id = update.effective_chat.id
15
+ text = ('Hello dear user!')
16
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
17
+ thread = Thread(target=thread_function, args=(update,context))
18
+ thread.start()
19
+
20
+ def help(update, context):
21
+ def thread_function(update, context):
22
+ chat_id = update.effective_chat.id
23
+ text = ('Hello dear user!')
24
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
25
+ thread = Thread(target=thread_function, args=(update,context))
26
+ thread.start()
27
+ # Download URL
28
+
29
+ def download_url(update, context):
30
+ def thread_function(update, context):
31
+ chat_id = update.effective_chat.id
32
+ text = ('πŸ“ <b>Send your file url</b>\n\n'
33
+ '⚠️ If you dont send your url before 60s the operation will cancel!')
34
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
35
+ return 'GET_FILE_NAME'
36
+ thread = Thread(target=thread_function, args=(update,context))
37
+ thread.start()
38
+
39
+ def get_file_name(update, context):
40
+ def thread_function(update, context):
41
+ chat_id = update.effective_chat.id
42
+ context.user_data['url'] = update.message.text
43
+ try:
44
+ response = urllib.request.urlopen(urllib.request.Request(context.user_data['url'], method='HEAD'))
45
+ except:
46
+ text = ('⁉️ Sorry! Invalid url!')
47
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
48
+ return ConversationHandler.END
49
+ if response.status != 200:
50
+ text = ('⁉️ Sorry! Unable to download the url!')
51
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
52
+ return ConversationHandler.END
53
+ context.user_data['file_size'] = float(response.headers["Content-Length"]) / 2**20
54
+ if context.user_data['file_size'] > 50:
55
+ text = ('🚫 Sorry! File size is larger than 50MB!')
56
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
57
+ return ConversationHandler.END
58
+ text = ('βœ… <b>All right! Send your new file name</b>\n'
59
+ 'πŸ’’ If you want to set file name automatically send /None command!\n\n'
60
+ '⚠️ If you dont send your url before 60s the operation will cancel!')
61
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
62
+ return 'UPLOAD_FILE'
63
+ thread = Thread(target=thread_function, args=(update,context))
64
+ thread.start()
65
+
66
+ def upload_file(update, context):
67
+ def thread_function(update, context):
68
+ chat_id = update.effective_chat.id
69
+ context.user_data['file_name'] = update.message.text
70
+ if update.message.text == '/None':
71
+ context.user_data['file_name'] = context.user_data['url'].split('/')[-1]
72
+ else:
73
+ context.user_data['file_name'] = update.message.text
74
+ download_dir = path + 'temp/' + context.user_data['file_name']
75
+ try:
76
+ urllib.request.urlretrieve(context.user_data['url'], download_dir)
77
+ context.bot.send_document(chat_id,
78
+ document=open(download_dir, 'rb'),
79
+ reply_markup=main_keyboard)
80
+ os.remove(download_dir)
81
+ except:
82
+ text = ('🚫 Sorry! Try again later!')
83
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
84
+ return ConversationHandler.END
85
+ thread = Thread(target=thread_function, args=(update,context))
86
+ thread.start()
87
+
88
+ def timeout_operation(update, context):
89
+ text = 'Timout ... 😴'
90
+ update.message.reply_text(text, reply_markup=main_keyboard)
91
+ return ConversationHandler.END
92
+
93
+ def cancel_operation(update, context):
94
+ text = '⁉️ Operation Canceled!'
95
+ update.message.reply_text(text, reply_markup=main_keyboard)
96
+ return ConversationHandler.END
97
+
98
+ # Rename Files
99
+
100
+ def start_rename_files(update, context):
101
+ def thread_function(update, context):
102
+ chat_id = update.effective_chat.id
103
+ text = ('πŸ“ <b>Send your file with size less than 50MB</b>\n\n'
104
+ '⚠️ If you dont send your file before 60s the operation will /cancel!')
105
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
106
+ return 'GET_FILE'
107
+ thread = Thread(target=thread_function, args=(update,context))
108
+ thread.start()
109
+
110
+ def get_file(update, context):
111
+ def thread_function(update, context):
112
+ chat_id = update.effective_chat.id
113
+ context.user_data['file'] = update.message.document
114
+ file_name = update.message.document.file_name
115
+ if update.message.document.file_size > 20 * 2**20:
116
+ update.message.reply_text('🚫 Sorry! File size larger than 20 MB!')
117
+ return ConversationHandler.END
118
+ file_extension = file_name.split('.')[-1]
119
+ if len(file_extension) > 5:
120
+ context.user_data['ext'] = 'None'
121
+ else:
122
+ context.user_data['ext'] = file_name.split('.')[-1]
123
+ text = ('πŸ“ <b>Send your new file name</b>\n'
124
+ f'πŸ’’ If your name has not file extension we will add <b>.{context.user_data["ext"]}</b> to your file name\n\n'
125
+ '⚠️ If you dont send your file before 60s the operation will /cancel!')
126
+ context.bot.send_message(chat_id, text, reply_markup=ForceReply(), parse_mode=ParseMode.HTML)
127
+ return 'GO_TO_RENAME'
128
+ thread = Thread(target=thread_function, args=(update,context))
129
+ thread.start()
130
+
131
+ def rename_file_and_upload(update, context):
132
+ def thread_function(update, context):
133
+ chat_id = update.effective_chat.id
134
+ file_name = update.message.text
135
+ if file_name.find('.') < 0 and context.user_data['ext']:
136
+ file_name += ('.' + context.user_data['ext'])
137
+ with open(f'{path}/temp/{file_name}', 'wb') as f:
138
+ context.bot.get_file(context.user_data['file']).download(out = f)
139
+ context.bot.send_document(chat_id, document=open(f'{path}/temp/{file_name}', 'rb'), reply_markup=main_keyboard)
140
+ os.remove(f'{path}/temp/{file_name}')
141
+ return ConversationHandler.END
142
+ thread = Thread(target=thread_function, args=(update,context))
143
+ thread.start()
144
+
145
+ # Sync Excel Files
146
+
147
+ def start_excel_sync(update, context):
148
+ def thread_function(update, context):
149
+ chat_id = update.effective_chat.id
150
+ text = ('πŸ“ <b>Send the firts excel file</b>\n\n'
151
+ '⚠️ If you dont send your file before 60s the operation will /cancel!')
152
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
153
+ return 'GET_FIRST_EXCEL'
154
+ thread = Thread(target=thread_function, args=(update,context))
155
+ thread.start()
156
+
157
+ def get_first_excel(update, context):
158
+ def thread_function(update, context):
159
+ chat_id = update.effective_chat.id
160
+ context.user_data['first_excel'] = update.message.document
161
+ if update.message.document.file_name.split('.')[-1] not in ['xlsx', 'xls']:
162
+ text = ('🚫 Sorry! You can just send excel files!')
163
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
164
+ return ConversationHandler.END
165
+ text = ('πŸ“ <b>Send the second excel file</b>\n\n'
166
+ '⚠️ If you dont send your file before 60s the operation will /cancel!')
167
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
168
+ return 'GET_SECOND_EXCEL'
169
+ thread = Thread(target=thread_function, args=(update,context))
170
+ thread.start()
171
+
172
+ def get_second_excel(update, context):
173
+ def thread_function(update, context):
174
+ chat_id = update.effective_chat.id
175
+ context.user_data['second_excel'] = update.message.document
176
+ if update.message.document.file_name.split('.')[-1] not in ['xlsx', 'xls']:
177
+ text = ('🚫 Sorry! You can just send excel files!')
178
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
179
+ return ConversationHandler.END
180
+ text = ('πŸ“ <b>Send the column name that you want merge on it</b>\n\n'
181
+ '⚠️ If you dont send your name before 60s the operation will /cancel!')
182
+ context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
183
+ return 'UPLOAD_FILE'
184
+ thread = Thread(target=thread_function, args=(update,context))
185
+ thread.start()
186
+
187
+ def merge_and_upload(update, context):
188
+ def thread_function(update, context):
189
+ id = randint(1000000000, 9999999999)
190
+ chat_id = update.effective_chat.id
191
+ with open(f'{path}/temp/{id}_a.xlsx', 'wb') as f:
192
+ context.bot.get_file(context.user_data['first_excel']).download(out=f)
193
+ with open(f'{path}/temp/{id}_b.xlsx', 'wb') as f:
194
+ context.bot.get_file(context.user_data['second_excel']).download(out=f)
195
+ if merge_two_excel(id, update.message.document):
196
+ context.bot.send_document(chat_id,
197
+ document=open(f'{path}/temp/s_{id}.xlsx', 'rb'),
198
+ reply_markup=main_keyboard)
199
+ else:
200
+ os.remove(f'{path}/temp/{id}_a.xlsx')
201
+ os.remove(f'{path}/temp/{id}_b.xlsx')
202
+ text = '⁉️ <b>Ω‘Sorry! Operation has been failed</b>\n\n'
203
+ context.bot.send_message(chat_id, text, reply_markup=main_keyboard, parse_mode=ParseMode.HTML)
204
+ return ConversationHandler.END
205
+ thread = Thread(target=thread_function, args=(update,context))
206
+ thread.start()
207
+
208
+ def merge_two_excel(id, column_tag):
209
+ try:
210
+ import pandas as pd
211
+ data_1 = pd.read_excel(f'{path}/temp/{id}_a.xlsx')
212
+ data_2 = pd.read_excel(f'{path}/temp/{id}_b.xlsx')
213
+ data = data_1.merge(data_2, on=column_tag, how='outer', suffixes=('_x', '_y'))
214
+ data = (data.rename(columns = lambda x: x.replace('_x', '')).fillna(data.filter(regex='_y$')
215
+ .rename(columns = lambda x: x.replace('_y', ''))).filter(regex=r'.*(?<!_y)$'))
216
+ data.to_excel(f'{path}/temp/s_{id}.xlsx', index=False)
217
+ os.remove(f'{path}/temp/{id}_a.xlsx')
218
+ os.remove(f'{path}/temp/{id}_b.xlsx')
219
+ return True
220
+ except:
221
+ return False
222
+
223
+ # Main function
224
+ if __name__ == '__main__':
225
+ # Bot Configs
226
+ TOKEN = '5931628423:AAEztLAlYWOs-RwpN6Bb0D0Xkqt2JvSNFQY'
227
+ admin_id = 37087739
228
+ updater = Updater(token=TOKEN)
229
+ path = '/'.join(__file__.split('/')[:-1]) + '/'
230
+ # Keyboards
231
+ buttons = [['Download Url', 'Rename File'], ['Sync Excel']]
232
+ main_keyboard = ReplyKeyboardMarkup(buttons, one_time_keyboard=True, resize_keyboard=True)
233
+ # Command Handlers
234
+ updater.dispatcher.add_handler(CommandHandler('start', start, Filters.chat_type.private))
235
+ # Conversation Handlers
236
+ updater.dispatcher.add_handler(ConversationHandler(
237
+ entry_points=[MessageHandler(Filters.text('Download Url') , download_url)],
238
+ states={
239
+ 'GET_FILE_NAME': [MessageHandler(Filters.text, get_file_name)],
240
+ 'UPLOAD_FILE': [MessageHandler(Filters.text, upload_file)],
241
+ ConversationHandler.TIMEOUT: [MessageHandler(Filters.all, timeout_operation)]
242
+ },
243
+ fallbacks=[CommandHandler('cancel', cancel_operation)],
244
+ conversation_timeout=30,
245
+ ))
246
+ updater.dispatcher.add_handler(ConversationHandler(
247
+ entry_points=[MessageHandler(Filters.text('Rename File') , start_rename_files)],
248
+ states={
249
+ 'GET_FILE': [MessageHandler(Filters.document, get_file)],
250
+ 'GO_TO_RENAME': [MessageHandler(Filters.text, rename_file_and_upload)],
251
+ ConversationHandler.TIMEOUT: [MessageHandler(Filters.all, timeout_operation)]
252
+ },
253
+ fallbacks=[CommandHandler('cancel', cancel_operation)],
254
+ conversation_timeout=30,
255
+ ))
256
+ updater.dispatcher.add_handler(ConversationHandler(
257
+ entry_points=[MessageHandler(Filters.text('Sync Excel'), start_excel_sync)],
258
+ states={
259
+ 'GET_FIRST_EXCEL': [MessageHandler(Filters.document, get_first_excel)],
260
+ 'GET_SECOND_EXCEL': [MessageHandler(Filters.document, get_second_excel)],
261
+ 'UPLOAD_FILE': [MessageHandler(Filters.text, merge_and_upload)],
262
+ ConversationHandler.TIMEOUT: [MessageHandler(Filters.all, timeout_operation)]
263
+ },
264
+ fallbacks=[CommandHandler('cancel', cancel_operation)],
265
+ conversation_timeout=120,
266
+ ))
267
+ # Message Handlers
268
+ updater.dispatcher.add_handler(MessageHandler(Filters.text('Help') & Filters.chat_type.private, help))
269
+ #updater.dispatcher.add_handler(MessageHandler(Filters.text & Filters.chat_type.private, other))
270
+ # Start Bot
271
+ updater.start_polling()
272
+ print('Bot is started ...')
273
+ updater.idle()