Discord机器人登录报错:static token与401 Unauthorized问题求助
问题
启动Discord机器人时持续报错,尝试重置Bot Token、新建机器人均无法解决。不清楚static token的含义,报错包含discord.errors.LoginFailure: Improper token has been passed和401 Unauthorized,完整报错栈和机器人代码如下:
报错信息
Traceback (most recent call last): File "C:\Python39\lib\site-packages\discord\http.py", line 300, in static_login data = await self.request(Route('GET', '/users/@me')) File "C:\Python39\lib\site-packages\discord\http.py", line 254, in request raise HTTPException(r, data) discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Löpold\PycharmProjects\pythonProject1\main.py", line 59, in <module> bot.run(token) File "C:\Python39\lib\site-packages\discord\client.py", line 723, in run return future.result() File "C:\Python39\lib\site-packages\discord\client.py", line 702, in runner await self.start(*args, **kwargs) File "C:\Python39\lib\site-packages\discord\client.py", line 665, in start await self.login(*args, bot=bot) File "C:\Python39\lib\site-packages\discord\client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) File "C:\Python39\lib\site-packages\discord\http.py", line 304, in static_login raise LoginFailure('Improper token has been passed.') from exc discord.errors.LoginFailure: Improper token has been passed. Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001F03CF823A0> Traceback (most recent call last): File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon self._check_closed() File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed
机器人代码
import json import asyncio import datetime import discord from discord.ext import commands from io import BytesIO from numpy import resize client = commands.Bot(command_prefix=".", intents=discord.Intents.all()) prefix = "." async def status_task(): while True: await client.change_presence( activity=discord.Activity( type=discord.ActivityType.watching, name="Leon"), status=discord.Status.online) await asyncio.sleep(2) await client.change_presence( activity=discord.Activity( type=discord.ActivityType.watching, name=f"A master at work"), status=discord.Status.online) await asyncio.sleep(2) @client.command() async def helps(ctx): await ctx.message.delete() embed = discord.Embed(title="E", description=f""" `███████╗██████╗ ██████╗ ██████╗ ██████╗ ██╔════╝██╔══██╗██╔══██╗██╔═══██╗██╔══██╗ █████╗ ██████╔╝██████╔╝██║ ██║██████╔╝ ██╔══╝ ██╔══██╗██╔══██╗██║ ██║██╔══██╗ ███████╗██║ ██║██║ ██║╚██████╔╝██║ ██║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝` """, color=discord.Colour.blue(), timestamp=datetime.datetime.utcnow(), inline="true") embed.set_footer(icon_url=ctx.author.avatar_url) await ctx.channel.send(embed=embed) @client.command() async def createchannel(ctx, channelName): guild = ctx.guild embed = discord.Embed(title="Succesfully created a new Channel", description="{} has been created".format(channelName)) if ctx.author.guild_permissions.manage_channels: await guild.create_text_channel(name='{}'.format(channelName)) await ctx.send(embed=embed) client.run('')
排查与解决思路
1. 核心问题定位
报错里的static_login是discord.py库中验证Token合法性的核心方法,它会向Discord API发送请求验证Token,返回401说明Token无效或未正确传递。这里的static token就是指从Discord开发者后台获取的固定Bot Token,和动态临时令牌相对,用于机器人持续验证身份。
2. 针对性修复步骤
- 填充有效Token:代码最后一行
client.run('')是空字符串,必须将Discord开发者后台复制的Bot Token填入引号内,注意不要带多余空格、换行或全角符号。 - 确认Token获取正确:在Discord开发者后台进入机器人页面,点击
Reset Token后复制的字符串才是有效的Bot Token,不要误用OAuth2的客户端ID、密钥或邀请链接参数。 - 排查账号状态:若重置Token后仍报错,确认机器人账号未被Discord封禁,可尝试新建机器人并重新复制Token测试。
- 检查编码/格式问题:若从文件或环境变量读取Token,确保无编码错误,比如混入中文空格、特殊字符。
3. 代码额外修复点
- 启动状态任务:
status_task未被触发,需在on_ready事件中启动:
@client.event async def on_ready(): print(f'Logged in as {client.user}') client.loop.create_task(status_task())
- 更新头像URL调用:新版本discord.py中
avatar_url已弃用,改用display_avatar.url:
embed.set_footer(icon_url=ctx.author.display_avatar.url)
- 清理无用依赖:
from numpy import resize未被使用,可删除以减少不必要的依赖。
内容的提问来源于stack exchange,提问作者LPLDWE
相关产品推荐
相关产品推荐

