You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置aiogram 3.16机器人使用服务器代理的问题

解决Aiogram机器人服务器代理连接问题

报错ClientConnectorDNSError是因为服务器无法直接访问Telegram API,需通过你已验证可用的代理连接。以下是完整配置示例,实现/start命令返回hello:

import asyncio
from aiogram import Bot, Dispatcher, Router
from aiogram.types import Message
from aiogram.filters import CommandStart

# 代理配置(与你测试通过的地址一致)
PROXY_URL = "http://172.16.2.11:8080"
# 替换为你的机器人Token
BOT_TOKEN = "你的机器人Token"

# 初始化路由
router = Router()

# 处理/start命令
@router.message(CommandStart())
async def start_handler(message: Message):
    await message.answer("hello")

async def main():
    # 初始化Bot时指定代理
    bot = Bot(token=BOT_TOKEN, proxy=PROXY_URL)
    dp = Dispatcher()
    dp.include_router(router)
    
    # 启动机器人
    await dp.start_polling(bot)

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

关键配置说明

  • 在Bot初始化时传入proxy参数,aiogram会自动通过该代理发起所有Telegram API请求
  • 务必替换代码中的BOT_TOKEN为你从BotFather获取的真实机器人令牌
  • 若使用Aiogram v2版本,需调整初始化逻辑:
    from aiogram import Bot, Dispatcher, executor, types
    
    bot = Bot(token=BOT_TOKEN, proxy=PROXY_URL)
    dp = Dispatcher(bot)
    
    @dp.message_handler(commands=['start'])
    async def start_handler(message: types.Message):
        await message.reply("hello")
    
    if __name__ == "__main__":
        executor.start_polling(dp, skip_updates=True)
    

内容的提问来源于stack exchange,提问作者Red Yonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 09:56:02