引入crm_router后Aiogram Telegram机器人无法启动求助
Aiogram机器人引入crm_router后无法启动问题
我在使用Aiogram开发Telegram机器人时遇到一个问题:当在Dispatcher中引入crm_router后,机器人无法启动;但替换成auto_responder_router就能正常运行,且没有明确的报错信息。
相关代码
run.py
from dotenv import load_dotenv import os from aiogram import Bot, Dispatcher from aiogram.types import Message from aiogram.filters import CommandStart import asyncio from auto_responder import * from crm import crm_router, init_db from orders import * from reminders import * from admin_panel import * import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) load_dotenv() bot = Bot(token=os.getenv('BOT_TOKEN')) dp = Dispatcher() @dp.message(CommandStart()) async def start(message: Message): await message.answer('Hello! I am a bot. I can help you with your business. Please choose one of the following options: /auto_responder, /crm, /orders, /reminders, /admin_panel') async def main(): dp.include_routers( crm_router, auto_responder_router ) await init_db() await dp.start_polling(bot) if __name__ == "__main__": try: asyncio.run(main()) except (KeyboardInterrupt, SystemExit): print("Bot stopped!")
crm.py
import asyncpg import os from dotenv import load_dotenv from aiogram.types import Message from aiogram import Router, F from aiogram.filters import Command crm_router = Router() load_dotenv() # Глобальная переменная для пула соединений DB_POOL = None async def init_db(): global DB_POOL DB_POOL = await asyncpg.create_pool(os.getenv('DB_URL')) async with DB_POOL.acquire() as conn: await conn.execute(''' CREATE TABLE IF NOT EXISTS clients ( id SERIAL PRIMARY KEY, name TEXT NOT NULL, phone TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); ''') await conn.execute(''' CREATE TABLE IF NOT EXISTS messages ( id SERIAL PRIMARY KEY, client_id INTEGER REFERENCES clients(id) ON DELETE CASCADE, message TEXT NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); ''') async def get_db(): global DB_POOL if DB_POOL is None: await init_db() @crm_router.message(Command('crm')) async def crm(message: Message): await message.answer('Welcome to the CRM system! Write your name and phone number in the format: `Name|Phone` (example: `Jane Doe|+1234567890`)') @crm_router.message(F.text) async def handle_crm_message(message:Message): """Обработчик текстовых сообщений для CRM""" print("CRM text message received") if message.text.startswith('/'): return data = message.text.split('|') if len(data) != 2: await message.answer('Invalid format! Please use: `Name|Phone`') return name, phone = data[0].strip(), data[1].strip() if not phone.startswith('+'): await message.answer('Invalid phone number! Please use the format: `+1234567890`') return await save_data(name, phone) await message.answer(f'Thank you, {name}! Your phone number {phone} has been saved.') async def save_data(name: str, phone: str): await get_db() async with DB_POOL.acquire() as conn: await conn.execute( "INSERT INTO clients (name, phone) VALUES ($1, $2) ON CONFLICT (phone) DO NOTHING", name, phone ) async def save_message(client_id: int, message: str): """Сохраняет сообщение клиента""" async with DB_POOL.acquire() as conn: await conn.execute( "INSERT INTO messages (client_id, message) VALUES ($1, $2)", client_id, message )
已尝试的排查操作
- 检查crm.py语法错误,未发现问题
- 确认crm_router初始化正常
- 单独运行init_db()验证数据库连接和表创建功能可用
- 添加打印语句调试,但未捕获到任何错误信息
内容的提问来源于stack exchange,提问作者Сырым Байгельдинов
相关产品推荐
相关产品推荐

