我正在尝试使用Python编写不和谐的bot,我遇到了这个机器人.
import discord
import asyncio
import random
client = discord.Client()
inEmail = input("Email:")
inPassword = input("Passwd:")
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("************")
messages = ["Hello!", "How are you doing?", "Testing!!"]
await client.send_message(channel, random.choice(messages))
await asyncio.sleep(120)
client.loop.create_task(background_loop())
client.run(inEmail, inPassword)
但是,当我尝试运行它时,我收到了SyntaxError:
File "1.py", line 7
async def background_loop():
^
SyntaxError: invalid syntax
这是为什么?在测试之前,我从未收到过它.
解决方法:
Asynchronous requests were introduced to Python in v3.3,如果您运行的是v3.3之前的Python(包括v2.X),则必须安装更高版本的Python.
仅在运行Python 3.3时:asyncio不属于stdlib,you’ll need to install it manually from pypi:
pip install asyncio
async和await关键字仅对Python 3.5或更高版本有效.如果您使用的是Python 3.3或3.4,则需要对代码进行以下更改:
>使用@ asyncio.coroutine装饰器而不是async语句:
async def func():
pass
# replace to:
@asyncio.coroutine
def func():
pass
>使用yield from而不是await:
await coroutine()
# replace to:
yield from coroutine()
这是您的函数需要更改为的示例(如果您使用的是3.3-3.4版本):
import asyncio
@asyncio.coroutine
def background_loop():
yield from client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("************")
messages = ["Hello!", "How are you doing?", "Testing!!"]
yield from client.send_message(channel, random.choice(messages))
yield from asyncio.sleep(120)
较新版本的Python 3仍支持上述语法,但是如果不需要支持Python 3.3-3.4,则建议使用await和async.您可以参考此documentation,这是一个简短的代码段:
The
async def
type of coroutine was added in Python 3.5, and is
recommended if there is no need to support older Python versions.
在旁边:
discord.py当前支持3.4.2-3.6.6(截至2019年1月,它不支持3.3-3.4.1,3.7).
对于使用discord.py进行开发,我建议使用discord.py rewrite分支:
discord.py-rewrite支持3.5.3-3.7.