首页 > 解决方案 > 带有异步错误的 Discord 机器人

问题描述

当我运行代码时遇到错误时async,我已导入asyncio以尝试修复此问题,但错误不断涌入

import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio

bot = command.Bot(command_prefix="=")

@bot.event
async def on_ready():
    print ("Bot Onine!")
    print ("Hello I Am " + bot.user.name)
    print ("My ID Is " + bot.user.id)

我得到的错误:

async def on_ready():
    ^
SyntaxError: invalid syntax

请如果有人知道修复

标签: pythonpython-3.xdiscorddiscord.py

解决方案


要使用async关键字,您需要 python 3.5 或更高版本。如果您使用的是 python 3.4 或更低版本,则不能使用async.

另一种方法是用coroutine. 这段代码

@bot.event
async def on_ready():
    ...

变成:

@bot.event
@asyncio.coroutine
def on_ready():
    ....

由于不和谐事件已经需要bot.event装饰器,因此discord.pyapi 提供了async_event装饰器以在一次调用中同时完成协程和事件装饰,因此您也可以这样编写:

@bot.async_event
def on_ready():
    ....

同样,你不能使用await任何一个,所以你必须使用yield from

await bot.say('Some response')

变成

yield from bot.say('Some response')

推荐阅读