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

discord.py部署Heroku遇RuntimeError及RuntimeWarning问题求助

修复Discord.py部署到Heroku时的事件循环错误

错误根源解析

  • RuntimeError: no running event loop:代码尝试在无活跃事件循环的上下文里执行异步操作
  • RuntimeWarning: coroutine 'Loop._loop' was never awaited:存在未被正确调度执行的协程对象

具体修复方案

1. 统一异步代码的启动方式

本地环境可能兼容不规范的异步调用,但Heroku对事件循环管理要求更严格。必须使用标准的异步启动流程,避免手动创建/管理循环:

错误写法(易触发环境兼容问题)

import asyncio
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=intents)

# 手动创建循环,易导致环境冲突
loop = asyncio.get_event_loop()
loop.run_until_complete(bot.start('YOUR_TOKEN'))
loop.close()

正确写法(适配所有环境)

import asyncio
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True  # 根据你的机器人需求调整权限

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')

async def main():
    async with bot:
        await bot.start('YOUR_BOT_TOKEN')

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

2. 确保所有异步操作被正确await

检查代码中所有异步函数/方法的调用:

  • 禁止直接调用协程对象(如some_async_func()),必须添加await(如await some_async_func())
  • 若需在同步上下文调用异步代码,用asyncio.run()包裹,但禁止嵌套调用asyncio.run()

3. 修正Heroku Procfile配置

Discord机器人属于后台进程,需使用worker进程类型,而非web类型。在项目根目录创建Procfile文件,内容如下:

worker: python your_bot_script.py

替换your_bot_script.py为你的机器人主文件名。

4. 排查第三方依赖的异步调用

若代码中使用了自定义工具函数或第三方库,确认其内部异步操作是否被正确处理,避免引入未被await的协程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:01:04