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

开发Discord+CharacterAI机器人遇RuntimeError:asyncio.run()无法在运行事件循环中调用

解决Discord机器人与CharacterAI集成时的asyncio事件循环错误

问题场景

开发一款模拟CharacterAI角色对话的Discord机器人,基于非官方CharacterAI API和discord.py库,运行代码时触发RuntimeError: asyncio.run() cannot be called from a running event loop错误。

现有代码

import tracemalloc
tracemalloc.start()
import asyncio
import discord
from discord.ext import commands
import characterai

character_ai_token = "character ai token here"
intents = discord.Intents.all()
client = characterai.pyCAI(character_ai_token)
bot = commands.Bot(command_prefix='!', intents=intents)


@bot.event
async def on_ready():
    print(f'Bot is ready. Logged in as {bot.user.name}')


target_channel_id = "channel_id_here"


@bot.event
async def on_message(message):
    data = await client.chat.send_message('CHAR', message, wait=True)
    if message.author == bot.user:
        return
    if message.channel.id != target_channel_id:
        return
    if message.content.startswith(bot.command_prefix):
        await bot.process_commands(message)
        return

    response = await data['replies'][0]['text']
    await message.channel.send(response)


async def start_bot():
    await bot.start("bot token")

async def main():
    await asyncio.create_task(start_bot())

asyncio.run(main())

报错信息

Traceback (most recent call last):
  File "C:\Users\hp\Desktop\projects\discoBotchai\main.py", line 43, in <module>
    asyncio.run(main())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 33, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'main' was never awaited
Object allocated at (most recent call last):
  File "C:\Users\hp\Desktop\projects\discoBotchai\main.py", lineno 43

Process finished with exit code 1

解决方案

关键修改点

  1. 简化启动逻辑:discord.py的Bot.start()本身是持续运行的协程,无需用asyncio.create_task()包装
  2. 调整消息处理顺序:先过滤无效消息,再调用CharacterAI API,减少无效请求
  3. 修正参数传递:传递消息文本而非消息对象给CharacterAI接口
  4. 移除多余await:data已是异步调用结果,无需再次await
  5. 修正频道ID类型:Discord频道ID为整数,需改为数值类型

修改后完整代码

import tracemalloc
tracemalloc.start()
import asyncio
import discord
from discord.ext import commands
import characterai

character_ai_token = "character ai token here"
intents = discord.Intents.all()
client = characterai.pyCAI(character_ai_token)
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Bot is ready. Logged in as {bot.user.name}')

# 频道ID改为整数类型
target_channel_id = 123456789012345678

@bot.event
async def on_message(message):
    # 先过滤自身消息、非目标频道、命令消息
    if message.author == bot.user:
        return
    if message.channel.id != target_channel_id:
        return
    if message.content.startswith(bot.command_prefix):
        await bot.process_commands(message)
        return

    # 仅符合条件时调用CharacterAI接口
    data = await client.chat.send_message('CHAR', message.content, wait=True)
    response = data['replies'][0]['text']
    await message.channel.send(response)

async def main():
    # 直接await bot.start,无需额外任务包装
    await bot.start("bot token")

asyncio.run(main())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:33:00