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

Replit上Discord Bot出现429请求超限错误求助

解决Discord Bot在Replit出现的429限速错误

问题描述

我在Replit平台搭建了一个Discord Bot,初始运行一切正常,但一天后出现无法识别的错误,我怀疑可能与Token有关,但不确定。这是我的第一个Python项目,基于教程修改了部分内容,以下是我的Bot代码及报错信息:

Bot代码

import os

import discord
from discord import app_commands
from discord.ext import commands
TOKEN = os.environ.get("TOKEN")

from keep_alive import keep_alive

bot = commands.Bot(command_prefix="!", intents = discord.Intents.all())

@bot.event
async def on_ready():
    print("Bot is Up and Ready!")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
    except Exception as e:
        print(e)


@bot.tree.command(name="hello")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"Hey {interaction.user.mention}! This is a slash command!",
    ephemeral=True)

@bot.tree.command(name="say")
@app_commands.describe(thing_to_say="What should I say?")
async def say(interaction: discord.Interaction, thing_to_say: str):
    await interaction.response.send_message(f" {interaction.user.name} said: `{thing_to_say}`")


keep_alive()
bot.run(TOKEN)

报错信息

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    bot.run(TOKEN)
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "/home/runner/IncredibleX/venv/lib/python3.8/site-packages/discord/http.py", line 680, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): <!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en-US"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<head>
<title>Access denied | discord.com used Cloudflare to restrict access</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/main.css" />


<script>
(function(){if(document.addEventListener&&window.XMLHttpRequest&&JSON&&JSON.stringify){var e=function(a){var c=document.getElementById("error-feedback-survey"),d=document.getElementById("error-feedback-success"),b=new XMLHttpRequest;a={event:"feedback clicked",properties:{errorCode:1015,helpful:a,version:1}};b.open("POST","https://sparrow.cloudflare.com/api/v1/event");b.setRequestHeader("Content-Type","application/json");b.setRequestHeader("Sparrow-Source-Key","c771f0e4b54944bebf4261d44bd79a1e");
b.send(JSON.stringify(a));c.classList.add("feedback-hidden");d.classList.remove("feedback-hidden")};document.addEventListener("DOMContentLoaded",function(){var a=document.getElementById("error-feedback"),c=document.getElementById("feedback-button-yes"),d=document.getElementById("feedback-button-no");"classList"in a&&(a.classList.remove("feedback-hidden"),c.addEventListener("click",function(){e(!0)}),d.addEventListener("click",function(){e(!1)}))})}})();
</script>

<script defer src="https://performance.radar.cloudflare.com/beacon.js"></script>
</head>
<body>
  <div id="cf-wrapper">
    <div class="cf-alert cf-alert-error cf-cookie-error hidden" id="cookie-alert" data-translate="enable_cookies">Please enable cookies.</div>
    <div id="cf-error-details" class="p-0">
      <header class="mx-auto pt-10 lg:pt-6 lg:px-8 w-240 lg:w-full mb-15 antialiased">
         <h1 class="inline-block md:block mr-2 md:mb-2 font-light text-60 md:text-3xl text-black-dark leading-tight">
           <span data-translate="error">Error</span>
           <span>1015</span>
         </h1>
         <span class="inline-block md:block heading-ray-id font-mono text-15 lg:text-sm lg:leading-relaxed">Ray ID: 781d76eadf5df341 &bull;</span>
         <span class="inline-block md:block heading-ray-id font-mono text-15 lg:text-sm lg:leading-relaxed">2022-12-30 20:18:25 UTC</span>
        <h2 class="text-gray-600 leading-1.3 text-3xl lg:text-2xl font-light">You are being rate limited</h2>
      </header>

      <section class="w-240 lg:w-full mx-auto mb-8 lg:px-8">
          <div id="what-happened-section" class="w-1/2 md:w-full">
            <h2 class="text-3xl leading-tight font-normal mb-4 text-black-dark antialiased" data-translate="what_happened">What happened?</h2>
            <p>The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>
            
          </div>

          
      </section>

      <div class="feedback-hidden py-8 text-center" id="error-feedback">
    <div id="error-feedback-survey" class="footer-line-wrapper">
        Was this page helpful?
        <button class="border border-solid bg-white cf-button cursor-pointer ml-4 px-4 py-2 rounded" id="feedback-button-yes" type="button">Yes</button>
        <button class="border border-solid bg-white cf-button cursor-pointer ml-4 px-4 py-2 rounded" id="feedback-button-no" type="button">No</button>
    </div>
    <div class="feedback-success feedback-hidden" id="error-feedback-success">
        Thank you for your feedback!
    </div>
</div>


      <div class="cf-error-footer cf-wrapper w-240 lg:w-full py-10 sm:py-4 sm:px-8 mx-auto text-center sm:text-left border-solid border-0 border-t border-gray-300">
  <p class="text-13">
    <span class="cf-footer-item sm:block sm:mb-1">Cloudflare Ray ID: <strong class="font-semibold">781d76eadf5df341</strong></span>
    <span class="cf-footer-separator sm:hidden">&bull;</span>
    <span id="cf-footer-item-ip" class="cf-footer-item hidden sm:block sm:mb-1">
      Your IP:
      <button type="button" id="cf-footer-ip-reveal" class="cf-footer-ip-reveal-btn">Click to reveal</button>
      <span class="hidden" id="cf-footer-ip">34.138.198.247</span>
      <span class="cf-footer-separator sm:hidden">&bull;</span>
    </span>
    <span class="cf-footer-item sm:block sm:mb-1"><span>Performance &amp; security by</span> <a rel="noopener noreferrer" href="https://www.cloudflare.com/5xx-error-landing" id="brand_link" target="_blank">Cloudflare</a></span>
    
  </p>
  <script>(function(){function d(){var b=a.getElementById("cf-footer-item-ip"),c=a.getElementById("cf-footer-ip-reveal");b&&"classList"in b&&(b.classList.remove("hidden"),c.addEventListener("click",function(){c.classList.add("hidden");a.getElementById("cf-footer-ip").classList.remove("hidden")}))}var a=document;document.addEventListener&&a.addEventListener("DOMContentLoaded",d)})();</script>
</div><!-- /.error-footer -->


    </div><!-- /#cf-error-details -->
  </div><!-- /#cf-wrapper -->

错误原因

这不是Token的问题,核心原因是Replit免费实例的共享IP被Discord的Cloudflare防护系统临时封禁。Replit的免费用户共享同一IP池,大量Bot从这些IP发起连接,触发了Discord的请求速率限制(429错误),进而被Cloudflare判定为恶意访问,给出1015临时封禁错误。

解决办法

1. 配置Replit内置代理

给Discord的HTTP客户端设置Replit内置代理,绕过共享IP的限制。在你的代码中,import discord之后添加以下代码:

from discord.http import HTTPClient
import os

# 覆盖HTTPClient的初始化,加入代理设置
original_init = HTTPClient.__init__
def new_init(self, *args, **kwargs):
    original_init(self, *args, proxy="http://proxy.server:3128", **kwargs)

HTTPClient.__init__ = new_init

或者更简单的方式,在bot.run()前设置全局代理环境变量:

os.environ['http_proxy'] = 'http://proxy.server:3128'
os.environ['https_proxy'] = 'http://proxy.server:3128'

2. 减少命令同步次数

你的代码每次启动都会同步slash命令,这会额外增加请求次数。可以改成仅在修改命令后手动同步:

@bot.event
async def on_ready():
    print("Bot is Up and Ready!")
    # 仅在修改命令后取消注释同步,平时保持注释
    # try:
    #     synced = await bot.tree.sync()
    #     print(f"Synced {len(synced)} command(s)")
    # except Exception as e:
    #     print(e)

3. 验证Token有效性

虽然不是本次问题的原因,但可以加个判断确保Token存在:

TOKEN = os.environ.get("TOKEN")
if not TOKEN:
    print("错误:未设置TOKEN环境变量!")
    exit()

4. 临时等待封禁过期

如果是短期限速,等待1-2小时后重启Bot可能自动恢复,但这只是临时方案,共享IP的问题会反复出现,建议优先使用代理方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:10:20