在 Visual Studio 中添加 discord.py 文件时,出现语法错误,提示“意外的令牌”

问题描述

所以我通常用 C++ 编写代码,这是我第一次使用 python。我正在尝试编写一个 Discord 机器人,并且正在学习教程。它说要将此行添加到我的代码顶部

py -3 -m pip install -U discord.py

我在 pip 和 discord.py 下收到四个语法错误,都说“意外的令牌”。我查看了多个其他教程以及我正在关注的教程,但没有一个提到这一点。我使用的是 python 3.7.8 版,所以我很确定这不是问题。我尝试切换到 Repl.it IDE 并遵循告诉我使用的不同教程

import discord

由于我不太了解的原因,这不起作用。所有这一切都是我的代码的样子

py -3 -m pip install -U discord.py

client = discord.Client()

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

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

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run(My bot's token)

我不知道我做错了什么。

解决方法

确保您已安装 pip,您可以在终端中执行此操作。如果您使用的是 Unix/macOS,请尝试 python -m pip install -U pip。如果您使用的是 Windows,请尝试 py -m pip install -U pip。然后,在代码的开头添加:

try:
    import discord
except ImportError:
    import pip
    pip.main(['install','discord'])
    import discord

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...