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

Python开发Discord Bot遇RuntimeWarning:协程handle_response未被等待

Discord Bot RuntimeWarning 错误解决:coroutine 'handle_response' was never awaited

问题概况

修改responses.py中的handle_response函数、添加频道判断逻辑后,机器人触发RuntimeWarning: coroutine 'handle_response' was never awaited错误,此前功能正常。

控制台报错详情

2023-05-09 10:57:51 INFO     discord.client logging in using static token
2023-05-09 10:57:52 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 72b086a0a3abc6a43cf540c88089c8d1).
GrafBot#0573 is now running!
Graf 72#1007 said: `hi` in other1-💬
C:\Users\betty\PycharmProjects\GrafBot\bot.py:39: RuntimeWarning: coroutine 'handle_response' was never awaited
  await send_message(message, user_message, is_private=False)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

问题根源分析

  1. 错误使用异步函数与装饰器:给handle_response添加了@client.event装饰器并改为async函数,但bot.py调用时未加await,触发协程未等待警告;且@client.event仅用于注册Discord内置事件(如on_ready、on_message),不能用于普通业务函数。
  2. 参数传递不匹配:修改后的handle_response尝试读取message.author等对象属性,但bot.py传递的是字符串类型的user_message,而非Discord的Message对象。
  3. 逻辑运算符优先级错误:if条件中or与and混用未加括号,导致逻辑判断不符合预期(and优先级高于or,会先执行p_message in 列表 and 频道判断,再与前面的or条件结合)。
  4. 列表索引越界:使用random.randint(0, len(greetings))时,上限超出列表索引范围(列表索引从0开始,正确上限应为len(greetings)-1)。

修复方案及代码修改

1. 修正responses.py

移除多余的Discord客户端实例、装饰器,调整函数参数与逻辑:

import random

def handle_response(user_message, channel) -> str:
    # 频道ID改为字符串类型,与bot.py中channel格式一致
    com_channel = "935085549029564427"
    hu_channel = "935079195242037259"
    de_channel = "935084427283947550"
    p_message = user_message.lower()

    # English
    greetings = ["Hello There! 😃", "hi!", "Hello 👋", "Hey!"]
    # 用括号包裹or条件,确保逻辑优先级正确
    if (p_message == "hello" or p_message == "hi" or p_message in greetings) \
            and channel != hu_channel and channel != de_channel:
        # 修正randint上限,避免索引越界
        return greetings[random.randint(0, len(greetings)-1)]

    if (p_message == "roll" or p_message == "roll a dice" or p_message == "roll dice") \
            and channel != hu_channel and channel != de_channel:
        return str(random.randint(1, 6))

    if p_message == "help" \
            and channel != hu_channel and channel != de_channel:
        return "`If you need help, feel free to @Mention the mods!`"

    farewells = ["Bye! 👋", "Ciao!"]
    if (p_message == "bye" or p_message in farewells) \
            and channel != hu_channel and channel != de_channel:
        return farewells[random.randint(0, len(farewells)-1)]

    # Magyar
    koszonesek = ["Szia! 😃", "Üdv!", "Hello 👋"]
    if (p_message == "hello" or p_message == "szia" or p_message == "sziasztok" or p_message == "csá" or \
        p_message in koszonesek) \
            and channel != com_channel and channel != de_channel:
        return koszonesek[random.randint(0, len(koszonesek)-1)]

    if p_message == "dobj egy kockát" \
            and channel != com_channel and channel != de_channel:
        return str(random.randint(1, 6))

    if p_message == "segítség" \
            and channel != com_channel and channel != de_channel:
        return "`Hogyha segítségre lenne szükséged, nyugodtan @Említsd meg a mod-okat!`"

    if (p_message == "megyek" or p_message == "én most megyek") \
            and channel != com_channel and channel != de_channel:
        return "Szia! 👋"

    # Deutsch
    begrussungen = ["Moin! 😃", "Hi!", "Hallo 👋"]
    if (p_message == "hallo" or p_message == "moin" or p_message == "hi" or p_message in begrussungen) \
            and channel != com_channel and channel != hu_channel:
        return begrussungen[random.randint(0, len(begrussungen)-1)]

    if (p_message == "roll ein würfel" or p_message == "rolle einen würfel" or p_message == "roll" or \
        p_message == "würfel") \
            and channel != com_channel and channel != hu_channel:
        return str(random.randint(1, 6))

    if p_message == "hilfe" \
            and channel != com_channel and channel != hu_channel:
        return "`Fals du Hilfe brauchst @Erwähne die Mods!`"

    if (p_message == "ich geh" or p_message == "ich gehe jetzt") \
            and channel != com_channel and channel != hu_channel:
        return "Tschüß! 👋"

2. 修正bot.py中的send_message函数

修改参数传递,将频道信息一并传入handle_response:

import discord
import responses

async def send_message(message, user_message, is_private):
    try:
        channel = str(message.channel)
        response = responses.handle_response(user_message, channel)
        # 仅当有返回内容时发送消息,避免空消息
        if response:
            await message.author.send(response) if is_private else await message.channel.send(response)
    except Exception as e:
        print(e)

def run_discord_bot():
    bot_token = "你的TOKEN"  # 替换为实际机器人令牌
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        print(f"{client.user} is now running!")

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        print(f"{username} said: `{user_message}` in {channel}")

        if user_message[0] == "!":
            user_message = user_message[1:]
            await send_message(message, user_message, is_private=True)
        else:
            await send_message(message, user_message, is_private=False)

    client.run(bot_token)

验证

修改完成后重新运行机器人,发送测试消息,警告消失,频道判断与多语言响应功能正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:27:07