main.py не видит метод из handlers.py

Пишу телеграм-бота для вычисления математических выражений. Пытаюсь связать handlers с main. Выводит следующую ошибку. dp.register_message_handler(handlers.calculate_handler, commands=['calc']) AttributeError: module 'handlers' has no attribute 'calculate_handler'

main.py

from aiogram import Bot, Dispatcher, executor
import handlers

API_TOKEN = '5988312066:AAHlgiu3pLy6l5rILhyJVK0V06odzA_mX5c'
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
dp.register_message_handler(handlers.start, commands=["start"])
dp.register_message_handler(handlers.bye, commands=["bye"])
# Обработчик команды /calc [выражение]
dp.register_message_handler(handlers.calculate_handler, commands=['calc'])
if __name__ == '__main__':

    executor.start_polling(dp, skip_updates=True)

handlers.py

from aiogram import types
from utils import *
import re

async def start(message: types.Message):
    await message.answer("Привет!")

async def calculate(expression: str) -> str:
    try:
        # Извлекаем только допустимые символы, чтобы избежать выполнения удаленного кода
        expression = re.sub(r"[^\d+\-*/(). ]", "", expression)
        result = eval(expression)
        return f"Результат: {result}"
    except:
        return "Ошибка при вычислении"

# Обработчик команды /calc [выражение]
async def calculate_handler(message: types.Message):
    # Извлекаем выражение из текста сообщения
    expression = message.get_args()
    # Вычисляем результат и отправляем ответ в чат
    await message.answer(await calculate(expression))

async def bye(message: types.Message):
    await message.answer("Пока!")

utils.py

import requests
from telethon import TelegramClient, sync, events, types
import sqlite3


class BotHandler:

    def __init__(self, token):
        self.token = token
        self.api_url = "https://t.me/Lev_9PO301_bot".format(token)

    def get_updates(self, offset=None, timeout=30):
        method = 'getUpdates'
        params = {'timeout': timeout, 'offset': offset}
        resp = requests.get(self.api_url + method, params)
        result_json = resp.json()['result']
        return result_json

    def send_message(self, chat_id, text):
        params = {'chat_id': chat_id, 'text': text}
        method = 'sendMessage'
        resp = requests.post(self.api_url + method, params)
        return resp

    def get_last_update(self):
        try:
            get_result = self.get_updates()
            if len(get_result) > 0:
                last_update = get_result[-1]
            else:
                last_update = get_result[len(get_result)]
            return last_update
        except IndexError:
            print('except')


your_bot = BotHandler('5988312066:AAHlgiu3pLy6l5rILhyJVK0V06odzA_mX5c')

lastdate = ''
lastid = ''
print('start')


def main(lastdate, lastid):
    new_offset = None

    while True:
        your_bot.get_updates(new_offset)
        last_update = your_bot.get_last_update()
        last_update_id = last_update['update_id']
        last_chat_text = last_update['message']['text']
        last_chat_id = last_update['message']['chat']['id']
        last_chat_name = last_update['message']['chat']['first_name']
        last_chat_date = last_update['message']['date']
        if (last_chat_date != lastdate):
            lastdate = last_chat_date
            message(last_update, last_update_id, last_chat_text, last_chat_id, last_chat_name, last_chat_date)


def message(last_update, last_update_id, last_chat_text, last_chat_id, last_chat_name, last_chat_date):
    if (last_chat_text == '/start'):
        lastid = last_chat_id;
        your_bot.send_message(last_chat_id, '''Привет, я бот ''')

    else:
        your_bot.send_message(last_chat_id, 'ты написал иное сообщение')


if __name__ == '__main__':
    try:
        main(lastdate, lastid)
    except KeyboardInterrupt:
        exit()

Какая ошибка здесь может быть, из-за которой main.py не видит метод calculate_handler из handlers.py?


Ответы (0 шт):