0

Как мне начать переходить на библиотеку aiogram, не могу понять как устанавливать вебхук

import logging
import os

import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from telebot import TeleBot, types
from telebot import custom_filters
from telebot.handler_backends import State, StatesGroup
from telebot.storage import StateMemoryStorage
from aiogram.fsm.storage.memory import MemoryStorage
from handlers import get_inn, start_ex, date, description, screenshot_request, confirm_sending_screenshot, \
    sending_without_screenshot, sending_with_screenshot, canceling_msg, welcome_script, name_info
from handlers import buttons, create_email_msg

app = FastAPI()
logging.basicConfig(level=logging.INFO)

bot = TeleBot(os.getenv('TOKEN'))
storage = MemoryStorage()
load_dotenv()
state_storage = StateMemoryStorage()
bot.state_storage = state_storage


class UserState(StatesGroup):
    welcome_script = State()
    phone_info = State()
    inn = State()
    ie_or_llc = State()
    date = State()
    description = State()
    screenshot = State()
    with_screen = State()
    confirm_without_screen = State()
    confirm_with_screen = State()


@app.on_event("startup")
def bot_start():
    webhook_url = os.getenv('URL')
    bot.remove_webhook()
    bot.set_webhook(url=webhook_url)


# Чтение списка разрешенных чатов из .env
allowed_chats_str = os.getenv('ALLOWED_CHATS', '')
allowed_chats = [int(chat_id) for chat_id in allowed_chats_str.split(',')]


@app.post("/")
async def telegram_webhook(request: Request):
    data = await request.json()
    update = types.Update.de_json(data)

    # Проверка, является ли обновление сообщением
    if update.message and update.message.chat:
        # Проверка, является ли ID чата отправителя разрешенным
        if update.message.chat.id not in allowed_chats:
            return {"status": "ok"}

    try:
        bot.process_new_updates([update])
    except Exception as e:
        return {"status": "error", "error": str(e)}

    return {"status": "ok"}


problem = {}


def is_group_message(message: types.Message):
    ignored_chat_id = int(os.getenv('CHAT_FOR_REQUESTS'))

    return (
            message.chat.type in ['group', 'supergroup'] and
            message.chat.id != ignored_chat_id and
            message.chat.id in allowed_chats
    )


@bot.message_handler(commands=['stop'], func=is_group_message)
def canceling(message):
    canceling_msg(message, bot, problem)


@bot.message_handler(commands=['start'], func=is_group_message)
def start_ex_wrapper(message):
    welcome_script(message, bot, UserState, problem)


@bot.message_handler(state=UserState.phone_info, func=is_group_message)
def getting_phone(message):
    name_info(message, bot, UserState, problem)


@bot.message_handler(state=UserState.welcome_script, func=is_group_message)
def company_info(message):
    start_ex(message, bot, UserState, problem)


@bot.message_handler(state=UserState.inn, func=is_group_message)
def get_inn_wrapper(message):
    get_inn(message, bot, problem, UserState)


@bot.message_handler(state=UserState.date, func=is_group_message)
def get_date(message):
    date(message, bot, problem, UserState)


@bot.message_handler(state=UserState.description, func=is_group_message)
def get_description(message):
    description(message, bot, problem, UserState, buttons)


@bot.message_handler(state=UserState.screenshot, func=is_group_message)
def get_screenshot(message):
    screenshot_request(message, bot, problem, UserState, buttons)


@bot.message_handler(state=UserState.with_screen, content_types=['photo', 'document'], func=is_group_message)
def confirm_sending(message):
    confirm_sending_screenshot(message, bot, problem, UserState, buttons)


@bot.message_handler(state=UserState.confirm_without_screen, func=is_group_message)
def without_screen(message):
    sending_without_screenshot(message, bot, problem, buttons, create_email_msg, UserState)


@bot.message_handler(state=UserState.confirm_with_screen, func=is_group_message)
def send_screen(message):
    sending_with_screenshot(message, bot, problem, buttons, create_email_msg, UserState)


@bot.message_handler(func=lambda message: 'гриша' in message.text.lower() and is_group_message(message))
def start_ex_wrapper(message):
    welcome_script(message, bot, UserState, problem)


bot.add_custom_filter(custom_filters.StateFilter(bot))
bot.add_custom_filter(custom_filters.IsDigitFilter())

if __name__ == '__main__':
    uvicorn.run(app)

1
  • Так вы ж перед вебхуками на полинг хотя бы перейдите.
    – CausonQ
    Commented 30 янв. в 12:44

0

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Посмотрите другие вопросы с метками или задайте свой вопрос.