test_bot.py 3.2 KB
Newer Older
S
superyan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
import os
import logging
import asyncio
from telegram import Bot
from telegram.error import TelegramError, NetworkError, TimedOut
from config import TELEGRAM_BOT_TOKEN

# 设置日志记录
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

async def handle_message(bot: Bot, chat_id: int, text: str, retry_count=0):
    """处理接收到的消息,带重试机制"""
    try:
        if text == '/start':
            await bot.send_message(chat_id=chat_id, text="你好!我是测试机器人。")
        else:
            await bot.send_message(chat_id=chat_id, text=f"你说: {text}")
    except (NetworkError, TimedOut) as e:
        if retry_count < 3:
            logger.warning(f"发送消息失败,正在重试 ({retry_count + 1}/3): {str(e)}")
            await asyncio.sleep(1)
            return await handle_message(bot, chat_id, text, retry_count + 1)
        else:
            logger.error(f"发送消息失败,已达到最大重试次数: {str(e)}")
            raise

async def main():
    """持续运行的主函数"""
    retry_count = 0
    while True:
        try:
            logger.info(f"使用 token: {TELEGRAM_BOT_TOKEN}")
            bot = Bot(token=TELEGRAM_BOT_TOKEN)
            
            # 获取机器人信息
            me = await bot.get_me()
            logger.info(f"机器人信息: {me.to_dict()}")
            
            # 记录最后处理的更新ID
            last_update_id = 0
            
            while True:
                try:
                    # 获取新的更新
                    updates = await bot.get_updates(
                        offset=last_update_id + 1,
                        timeout=30,
                        allowed_updates=['message']
                    )
                    
                    for update in updates:
                        if update.message and update.message.text:
                            chat_id = update.message.chat_id
                            text = update.message.text
                            logger.info(f"收到消息 [{chat_id}]: {text}")
                            await handle_message(bot, chat_id, text)
                        
                        # 更新最后处理的更新ID
                        last_update_id = update.update_id
                    
                except (NetworkError, TimedOut) as e:
                    logger.warning(f"网络错误,等待后重试: {str(e)}")
                    await asyncio.sleep(5)
                    continue
                except Exception as e:
                    logger.error(f"处理消息时发生错误: {str(e)}", exc_info=True)
                    continue
                
                # 短暂休息,避免过于频繁的请求
                await asyncio.sleep(1)
                
        except Exception as e:
            retry_count += 1
            if retry_count > 5:
                logger.error(f"发生严重错误,程序退出: {str(e)}", exc_info=True)
                raise
            
            logger.error(f"发生错误,{retry_count}/5 次重试: {str(e)}", exc_info=True)
            await asyncio.sleep(5)

if __name__ == '__main__':
    asyncio.run(main())