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

Python开发Discord机器人如何通过独立函数实现消息发送?

错误原因

你遇到的SyntaxError: 'await' outside async function报错是因为await关键字只能在异步函数(声明时带async前缀的函数)中使用,你当前的spam是普通同步函数,不能使用await。同时你使用的同步阻塞方法time.sleep会卡住整个Discord机器人的事件循环,导致其他功能无法正常响应,需要替换为异步等待方法。

调整步骤

  • 首先导入asyncio库,用于实现异步等待
  • 给spam函数的定义前加async关键字,将其改为异步函数
  • 调用spam函数时添加await关键字,正确触发异步函数执行
  • 将time.sleep(1)替换为await asyncio.sleep(1),避免阻塞事件循环

修改后完整代码

import discord
import os
import asyncio
token = os.environ['token']

client = discord.Client()
keywords = ["spam"]

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


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

    if message.content.startswith(prefix):
        mcontent = str(message.content)[1:]
        for i in range(len(keywords)):
          if keywords[0] in mcontent:
            await spam(mcontent, message)


async def spam(mcontent, message):
  n = int(mcontent[4:])
  n2 = 0
  while n2 < n:
    await message.channel.send(f"spam")
    n2 += 1
    await asyncio.sleep(1)

client.run(token)

补充优化:原代码中字符串切片[1:len(str(message.content))]可以简化为[1:],效果完全一致,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:03