Задать вопрос
@JewrySoft

Что происходит с данным кодом?

Пишу бота, он будет шифровать файлы.
Код:
import telebot, requests, random, pyAesCrypt, os, config, urllib

token = config.token
bot = telebot.TeleBot(token)
chat_ids_file = 'base.txt'
users_amount = [0]
types = telebot.types
running_spams_per_chat_id = []

def get_encrypt(message):
	passw = ''
	filename = ''

	def get_password(message):
		if message.text:
			passw = message.text
			try:
				bufferSize = 512 * 1024
				bot.send_message(message.chat.id, 'Отлично! Начинаем шифровать файл :)')
				pyAesCrypt.encryptFile (filename, filename + ' ENCRYPTED BY @encrypter_robot.aes', passw, bufferSize)
				print(filename + ' Зашифрован!')
				bot.send_document(filename + ' ENCRYPTED BY @encrypter_robot.aes')
				os.remove(filename)
			except:
				bot.send_message(message.chat.id, 'К сожалению, произошла какая-то ошибка!')
				os.remove(filename)

	if message.document:
		document_id = message.document.file_id
		file_info = bot.get_file(document_id)
		filename = message.document.file_name
		urllib.request.urlretrieve(f'http://api.telegram.org/file/bot{token}/{file_info.file_path}', file_info.file_path)
		a = bot.send_message(message.chat.id, 'Файл получил. Введите желаемый пароль для защиты шифрования:')
		bot.register_next_step_handler(a, get_password)

def save_chat_id(chat_id, message):
    chat_id = str(chat_id)
    with open(chat_ids_file,"a+") as ids_file:
        ids_file.seek(0)
        ids_list = [line.split('\n')[0] for line in ids_file]

        if chat_id not in ids_list:
            aha = message.from_user.username
            ids_file.write(f'{chat_id} {aha}\n')
            ids_list.append(chat_id)
            print(f'NEW USER: {chat_id}')
        else:
            print(f'chat_id {chat_id} is already saved')
        users_amount[0] = len(ids_list)
    return

def send_message_users(message):

    def send_message(chat_id):
        data = {
            'chat_id': chat_id,
            'text': message
        }
        response = requests.post(f'https://api.telegram.org/bot{TOKEN}/sendMessage', data=data)

    with open(chat_ids_file, "r") as ids_file:
        ids_list = [line.split('\n')[0] for line in ids_file]

    [send_message(chat_id) for chat_id in ids_list]

@bot.message_handler(commands=["start"])
def start(message):
	keyboard = types.InlineKeyboardMarkup()
	button1 = types.InlineKeyboardButton(text="Зашифровать файл", callback_data="button1")
	button2 = types.InlineKeyboardButton(text="Дешифровать файл", callback_data="button2")
	button3 = types.InlineKeyboardButton(text="Информация", callback_data="button3")
	msg = """<b>Вас приветствует Encrypter Bot!</b>
В нашем боте вы легко сможете зашифровать свой файл под личный ключ, и в любое время его заново дешифровать по ключу. Вся шифровка проходит AES-шифрование. Кроме вас и вашего пароля, никто не сможет получить настоящий файл.\n\nЧтобы начать работать с ботом, выберите действие:"""
	keyboard.add(button1, button2)
	keyboard.add(button3)
	bot.send_message(message.chat.id, msg, reply_markup=keyboard, parse_mode='HTML')
	save_chat_id(message.chat.id, message)

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    message = call.message

    if call.message:
        if call.data == "button1":
            lololo = bot.send_message(message.chat.id, "Просто отправь мне любой файл, введи ему пароль, и получи зашифрованную версию!")
            bot.register_next_step_handler(lololo, get_encrypt)
        elif call.data == "button2":
            hahaha = bot.send_message(message.chat.id, 'Отправь мне зашифрованный файл, введи его пароль, и я его расшифрую!')
            #bot.register_next_step_handler(hahaha, get_decrypt)
        elif call.data == "button3":
            with open('base.txt') as f:
                size=sum(1 for _ in f)
            bot.send_message(message.chat.id, 'Статистика отображается в реальном времени!\nПользователей‍♂: '+ str(size) +'\nБот запущен: 23.05.2020')
        else:
            bot.send_message(message.chat.id, '❌Я тебя не понимаю!')


if __name__ == '__main__':
	bot.infinity_polling(True, interval=0)


Когда я решаюсь запустить бота, нажать на Зашифровать файл, я отправляю файл для шифровки, и он не просит пароль, а выдает ошибку в консоле...
C:\Users\dogbert\Desktop\Encrypter Bot>

C:\Users\dogbert\Desktop\Encrypter Bot>python main.py
2020-05-22 01:03:37,972 (util.py:68 WorkerThread2) ERROR - TeleBot: "FileNotFoundError occurred, args=(2, 'No such file or directory')
Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\telebot\util.py", line 62, in run
    task(*args, **kwargs)
  File "main.py", line 32, in get_encrypt
    urllib.request.urlretrieve(f'http://api.telegram.org/file/bot{token}/{file_info.file_path}', file_info.file_path)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 257, in urlretrieve
    tfp = open(filename, 'wb')
FileNotFoundError: [Errno 2] No such file or directory: 'documents/file_5.exe'


Прошу, помогите с этим кодом. Буду очень благодарен, так как давно хотел сделать такого бота.
  • Вопрос задан
  • 296 просмотров
Подписаться 1 Средний Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы