我正在尝试使用 Python 编写 discord 机器人,我遇到了这个机器人并将其拼凑在一起。
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
这是为什么呢?我之前测试时从未收到过。
最佳答案
2021 年的更新答案(discord.py 1.x - 2.x):
discord.py 目前支持 Python 3.5 及更高版本。如果您收到 SyntaxError
,则表示您使用的是旧版本的 Python,并且不被 discord.py 支持。
首先,安装更高版本的 Python(在此消息中首选 3.8.x),然后运行 python3.8 bot.py
或 py -3.8 bot.py运行机器人时的
(适用于 Windows)。注意:安装时不要忘记选择“Add Python to PATH”。
原答案
Asynchronous requests were introduced to Python in v3.3 ,如果您运行的是 v3.3(包括 v2.X)之前的 Python,则必须安装更新版本的 Python。
仅在您运行 Python 3.3 时:asyncio
不是标准库的一部分,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,(不支持 3.3-3.4.1,截至 2019 年 1 月为 3.7)。
对于使用 discord.py 进行开发,我建议使用 discord.py 重写分支:
discord.py-rewrite支持3.5.3-3.7。
关于带有 async def 的 Python [无效语法],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43948454/