我有一个小项目,是用电报自动化工作任务。 我用的是aiogram 3.5版本
#function for write updated excel_data dict to excel
def process_excel_data_to_bytesio():
try:
# Create a BytesIO buffer
buffer = io.BytesIO()
# Write the updated DataFrames to the buffer
with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
for sheet_name, df in excel_data.items():
df.to_excel(writer, sheet_name=sheet_name, index=False)
print(f"{sheet_name} is written")
# Seek to the beginning of the stream
buffer.seek(0)
return buffer
except Exception as e:
logging.error(f"Error processing Excel file: {e}")
return None
@file_router.callback_query(F.data == "download_ip_file")
async def download_updated_ipfile_touser(query: CallbackQuery):
try:
if is_admin(query.from_user.id):
await query.answer("📎📊📈 Faylni serverdan qabul qilib oling\n yuklanmoqda...", reply_markup=ReplyKeyboardRemove())
# Process the Excel data to a BytesIO object
buffer = process_excel_data_to_bytesio()
await query.message.answer("ok", reply_markup=ReplyKeyboardRemove())
# Check if the buffer was processed successfully
if buffer is not None:
# Send the processed file to the user
with open('updated.xlsx', 'wb') as file:
file.write(buffer.getvalue())
await query.message.answer("faylga yozildi", reply_markup=ReplyKeyboardRemove())
await bot.send_document(chat_id=query.from_user.id, document=open('updated.xlsx', 'rb'))
await query.message.answer("fayl yuborildi", reply_markup=ReplyKeyboardRemove())
file_downloaded(user_id=query.from_user.id, user_firstname=query.from_user.first_name)
else:
await query.message.reply("❌ Faylni yozishda xatolik yuz berdi")
else:
await query.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
except Exception as e:
await query.message.reply(f"❌❓Возникло ошибка ! : <b>{str(e)}</b>\n")
当用户点击按钮以获得更新的文件时,他们应该通过提供更新的Excel文件来服务
解决方案已找到。
#ozgartirilgan excel_data dict ni yangi excel fayl yaratib,foydalanuvchiga yuborish hendleri @file_router.callback_query(lambda c: c.data == "download_ip_file") 异步 def download_ip_file(查询: CallbackQuery): 尝试: 如果 is_admin(query.from_user.id): 等待查询.answer("📎📊📈 Faylni serverdan qabul qilib oling 尤克兰莫克达...", reply_markup=ReplyKeyboardRemove()) file_path = f'ip_plan_file{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.xlsx'
# Write the DataFrames to the Excel file
with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
for sheet_name, df in excel_data.items():
df.to_excel(writer, sheet_name=sheet_name, index=False)
# Check if the file was processed successfully
if file_path is not None and os.path.exists(file_path):
# Send the processed file to the user
# Fetch the action before sending the file
await query.bot.send_chat_action(
chat_id=query.message.chat.id,
action=ChatAction.UPLOAD_DOCUMENT,
)
await bot.send_document(query.from_user.id, BufferedInputFile.from_file(file_path))
# Remove the file after sending it
os.remove(file_path)
file_downloaded(user_id=query.from_user.id, user_firstname=query.from_user.first_name)
else:
await query.message.reply("❌ Faylni yozishda xatolik yuz berdi")
else:
await query.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
await query.message.answer("🚫Siz admin emassiz, fayl yuklolmaysiz!", reply_markup=ReplyKeyboardRemove())
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
await query.message.reply(f"❌❓Возникло ошибка ! : <b>{str(e)}</b>\n")
finally:
# Always remove the file after the operation
if os.path.exists(file_path):
os.remove(file_path)
logging.info("Temporary file deleted.")
await query.message.answer("Temporary file deleted.", reply_markup=ReplyKeyboardRemove())