@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
      bufferSize = 512 * 1024
      bot.send_message(message.chat.id, 'Отлично! Начинаем шифровать файл :)')
      pyAesCrypt.encryptFile (filename, filename + ' ENCRYPTED BY @encrypter_robot.aes', passw, bufferSize)
      print(filename + ' Зашифрован!')
      file = filename + ' ENCRYPTED BY @encrypter_robot.aes'
      bot.send_document(message.chat.id, file)


  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}', filename)
    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)


Вылезает данная ошибка:
return _make_request(token, method_url, params=payload, files=files, method='post')
File "C:\Users\adm\AppData\Local\Programs\Python\Python37\lib\site-packages\telebot\apihelper.py", line 65, in _make_request
return _check_result(method_name, result)['result']
File "C:\Users\adm\AppData\Local\Programs\Python\Python37\lib\site-packages\telebot\apihelper.py", line 84, in _check_result
raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: wrong HTTP URL specified"}']
"
2020-05-22 19:45:52,119 (__init__.py:443 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: wrong HTTP URL specified"}']"


Буду ооочень благодарен, если поможете. Использую пока ради теста ВПН, все страны перепробовал
  • Вопрос задан
  • 560 просмотров
Решения вопроса 1
hottabxp
@hottabxp Куратор тега Python
Сначала мы жили бедно, а потом нас обокрали..
Дословно - 'Плохой запрос'. Обратите внимание на следующие:
file = filename + ' ENCRYPTED BY @encrypter_robot.aes'
bot.send_document(message.chat.id, file)

bot.send_document принимает в качестве аргументов 2 параметра:
1) id чата.
2) Дескриптор файла и id файла.
Вы же передаете строку с именем файла. Вот тут и ошибка. Можно сделать так:
print(filename + ' Зашифрован!')
file = filename + ' ENCRYPTED BY @encrypter_robot.aes'
f = open(file,'r+b')
bot.send_document(message.chat.id, f)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы