Spaces:
Runtime error
Runtime error
File size: 11,745 Bytes
589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 589f22c cd68418 |
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 |
from telegram.ext.filters import filters
from telegram.ext.messagehandler import MessageHandler
from telegram import ParseMode
from telegram.ext import Updater, CommandHandler, ConversationHandler, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ForceReply, ReplyKeyboardMarkup
import urllib.request
from threading import Thread
from random import randint
import os
def start(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
text = ('Hello dear user!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def help(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
text = ('Hello dear user!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
thread = Thread(target=thread_function, args=(update,context))
thread.start()
# Download URL
def download_url(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
text = ('π <b>Send your file url</b>\n\n'
'β οΈ If you dont send your url before 60s the operation will cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'GET_FILE_NAME'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def get_file_name(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
context.user_data['url'] = update.message.text
try:
response = urllib.request.urlopen(urllib.request.Request(context.user_data['url'], method='HEAD'))
except:
text = ('βοΈ Sorry! Invalid url!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
if response.status != 200:
text = ('βοΈ Sorry! Unable to download the url!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
context.user_data['file_size'] = float(response.headers["Content-Length"]) / 2**20
if context.user_data['file_size'] > 50:
text = ('π« Sorry! File size is larger than 50MB!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
text = ('β
<b>All right! Send your new file name</b>\n'
'π’ If you want to set file name automatically send /None command!\n\n'
'β οΈ If you dont send your url before 60s the operation will cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'UPLOAD_FILE'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def upload_file(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
context.user_data['file_name'] = update.message.text
if update.message.text == '/None':
context.user_data['file_name'] = context.user_data['url'].split('/')[-1]
else:
context.user_data['file_name'] = update.message.text
download_dir = path + 'temp/' + context.user_data['file_name']
try:
urllib.request.urlretrieve(context.user_data['url'], download_dir)
context.bot.send_document(chat_id,
document=open(download_dir, 'rb'),
reply_markup=main_keyboard)
os.remove(download_dir)
except:
text = ('π« Sorry! Try again later!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def timeout_operation(update, context):
text = 'Timout ... π΄'
update.message.reply_text(text, reply_markup=main_keyboard)
return ConversationHandler.END
def cancel_operation(update, context):
text = 'βοΈ Operation Canceled!'
update.message.reply_text(text, reply_markup=main_keyboard)
return ConversationHandler.END
# Rename Files
def start_rename_files(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
text = ('π <b>Send your file with size less than 50MB</b>\n\n'
'β οΈ If you dont send your file before 60s the operation will /cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'GET_FILE'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def get_file(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
context.user_data['file'] = update.message.document
file_name = update.message.document.file_name
if update.message.document.file_size > 20 * 2**20:
update.message.reply_text('π« Sorry! File size larger than 20 MB!')
return ConversationHandler.END
file_extension = file_name.split('.')[-1]
if len(file_extension) > 5:
context.user_data['ext'] = 'None'
else:
context.user_data['ext'] = file_name.split('.')[-1]
text = ('π <b>Send your new file name</b>\n'
f'π’ If your name has not file extension we will add <b>.{context.user_data["ext"]}</b> to your file name\n\n'
'β οΈ If you dont send your file before 60s the operation will /cancel!')
context.bot.send_message(chat_id, text, reply_markup=ForceReply(), parse_mode=ParseMode.HTML)
return 'GO_TO_RENAME'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def rename_file_and_upload(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
file_name = update.message.text
if file_name.find('.') < 0 and context.user_data['ext']:
file_name += ('.' + context.user_data['ext'])
with open(f'{path}/temp/{file_name}', 'wb') as f:
context.bot.get_file(context.user_data['file']).download(out = f)
context.bot.send_document(chat_id, document=open(f'{path}/temp/{file_name}', 'rb'), reply_markup=main_keyboard)
os.remove(f'{path}/temp/{file_name}')
return ConversationHandler.END
thread = Thread(target=thread_function, args=(update,context))
thread.start()
# Sync Excel Files
def start_excel_sync(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
text = ('π <b>Send the firts excel file</b>\n\n'
'β οΈ If you dont send your file before 60s the operation will /cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'GET_FIRST_EXCEL'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def get_first_excel(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
context.user_data['first_excel'] = update.message.document
if update.message.document.file_name.split('.')[-1] not in ['xlsx', 'xls']:
text = ('π« Sorry! You can just send excel files!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
text = ('π <b>Send the second excel file</b>\n\n'
'β οΈ If you dont send your file before 60s the operation will /cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'GET_SECOND_EXCEL'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def get_second_excel(update, context):
def thread_function(update, context):
chat_id = update.effective_chat.id
context.user_data['second_excel'] = update.message.document
if update.message.document.file_name.split('.')[-1] not in ['xlsx', 'xls']:
text = ('π« Sorry! You can just send excel files!')
context.bot.send_message(chat_id, text, reply_markup=main_keyboard)
return ConversationHandler.END
text = ('π <b>Send the column name that you want merge on it</b>\n\n'
'β οΈ If you dont send your name before 60s the operation will /cancel!')
context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML)
return 'UPLOAD_FILE'
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def merge_and_upload(update, context):
def thread_function(update, context):
id = randint(1000000000, 9999999999)
chat_id = update.effective_chat.id
with open(f'{path}/temp/{id}_a.xlsx', 'wb') as f:
context.bot.get_file(context.user_data['first_excel']).download(out=f)
with open(f'{path}/temp/{id}_b.xlsx', 'wb') as f:
context.bot.get_file(context.user_data['second_excel']).download(out=f)
if merge_two_excel(id, update.message.document):
context.bot.send_document(chat_id,
document=open(f'{path}/temp/s_{id}.xlsx', 'rb'),
reply_markup=main_keyboard)
else:
os.remove(f'{path}/temp/{id}_a.xlsx')
os.remove(f'{path}/temp/{id}_b.xlsx')
text = 'βοΈ <b>ΩSorry! Operation has been failed</b>\n\n'
context.bot.send_message(chat_id, text, reply_markup=main_keyboard, parse_mode=ParseMode.HTML)
return ConversationHandler.END
thread = Thread(target=thread_function, args=(update,context))
thread.start()
def merge_two_excel(id, column_tag):
try:
import pandas as pd
data_1 = pd.read_excel(f'{path}/temp/{id}_a.xlsx')
data_2 = pd.read_excel(f'{path}/temp/{id}_b.xlsx')
data = data_1.merge(data_2, on=column_tag, how='outer', suffixes=('_x', '_y'))
data = (data.rename(columns = lambda x: x.replace('_x', '')).fillna(data.filter(regex='_y$')
.rename(columns = lambda x: x.replace('_y', ''))).filter(regex=r'.*(?<!_y)$'))
data.to_excel(f'{path}/temp/s_{id}.xlsx', index=False)
os.remove(f'{path}/temp/{id}_a.xlsx')
os.remove(f'{path}/temp/{id}_b.xlsx')
return True
except:
return False
# Main function
if __name__ == '__main__':
# Bot Configs
TOKEN = '5931628423:AAEztLAlYWOs-RwpN6Bb0D0Xkqt2JvSNFQY'
admin_id = 37087739
updater = Updater(token=TOKEN)
path = '/'.join(__file__.split('/')[:-1]) + '/'
# Keyboards
buttons = [['Download Url', 'Rename File'], ['Sync Excel']]
main_keyboard = ReplyKeyboardMarkup(buttons, one_time_keyboard=True, resize_keyboard=True)
# Command Handlers
updater.dispatcher.add_handler(CommandHandler('start', start, filters.chat_type.private))
# Conversation Handlers
updater.dispatcher.add_handler(ConversationHandler(
entry_points=[MessageHandler(filters.text('Download Url') , download_url)],
states={
'GET_FILE_NAME': [MessageHandler(filters.text, get_file_name)],
'UPLOAD_FILE': [MessageHandler(filters.text, upload_file)],
ConversationHandler.TIMEOUT: [MessageHandler(filters.all, timeout_operation)]
},
fallbacks=[CommandHandler('cancel', cancel_operation)],
conversation_timeout=30,
))
updater.dispatcher.add_handler(ConversationHandler(
entry_points=[MessageHandler(filters.text('Rename File') , start_rename_files)],
states={
'GET_FILE': [MessageHandler(filters.document, get_file)],
'GO_TO_RENAME': [MessageHandler(filters.text, rename_file_and_upload)],
ConversationHandler.TIMEOUT: [MessageHandler(filters.all, timeout_operation)]
},
fallbacks=[CommandHandler('cancel', cancel_operation)],
conversation_timeout=30,
))
updater.dispatcher.add_handler(ConversationHandler(
entry_points=[MessageHandler(filters.text('Sync Excel'), start_excel_sync)],
states={
'GET_FIRST_EXCEL': [MessageHandler(filters.document, get_first_excel)],
'GET_SECOND_EXCEL': [MessageHandler(filters.document, get_second_excel)],
'UPLOAD_FILE': [MessageHandler(filters.text, merge_and_upload)],
ConversationHandler.TIMEOUT: [MessageHandler(filters.all, timeout_operation)]
},
fallbacks=[CommandHandler('cancel', cancel_operation)],
conversation_timeout=120,
))
# Message Handlers
updater.dispatcher.add_handler(MessageHandler(filters.text('Help') & filters.chat_type.private, help))
#updater.dispatcher.add_handler(MessageHandler(filters.text & filters.chat_type.private, other))
# Start Bot
updater.start_polling()
print('Bot is started ...')
updater.idle() |