首页 > 解决方案 > 在 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)

我不知道我做错了什么。

标签: pythonsyntax-errordiscord.pyunexpected-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

推荐阅读