Discord自机器人登录失败:传入令牌无效问题求助
问题
运行Discord自机器人脚本时持续触发登录失败错误,错误栈如下:
Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 803, in static_login data = await self.request(Route('GET', '/users/@me')) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 745, in request raise HTTPException(response, 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\Downloads\Compressed\tes\selfbot.py", line 88, in <module> bot.run(TOKEN) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 860, in run asyncio.run(runner()) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete return future.result() File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 849, in runner await self.start(token, reconnect=reconnect) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 777, in start await self.login(token) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 612, in login data = await self.http.static_login(token) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 807, in static_login raise LoginFailure('Improper token has been passed.') from exc discord.errors.LoginFailure: Improper token has been passed.
使用的完整脚本代码:
import discord from discord.ext import commands from pyzbar.pyzbar import decode from PIL import Image from io import BytesIO import aiohttp import asyncio # Replace 'YOUR_DISCORD_TOKEN' with your actual user token TOKEN = 'YOUR_DISCORD_TOKEN' # Replace 'YOUR_CHANNEL_ID' with the ID of your designated channel in your server MY_CHANNEL_ID = 'YOUR_CHANNEL_ID' intents = discord.Intents.default() intents.messages = True intents.guilds = True intents.message_content = True # This intent is needed to read message content bot = commands.Bot(command_prefix='!', self_bot=True, intents=intents) @bot.event async def on_ready(): print(f'Logged in as {bot.user}') async def process_message(message): # Ignore messages sent by the bot itself if message.author == bot.user: return # Check if the message has attachments if message.attachments: for attachment in message.attachments: # Ensure the attachment is an image if attachment.content_type and attachment.content_type.startswith('image'): try: # Retry logic for downloading the image image_data = None for attempt in range(3): try: # Download the image asynchronously async with aiohttp.ClientSession() as session: async with session.get(attachment.url) as response: image_data = await response.read() break # Exit retry loop if successful except aiohttp.ClientConnectorError as e: print(f'Error downloading image: {str(e)}. Retrying...') await asyncio.sleep(5) # Wait before retrying else: print(f'Failed to download image after 3 attempts. Skipping...') return # Check if the image contains a QR code if image_data and has_qr_code(image_data): # Decode the image asynchronously decoded_urls = await decode_image(image_data) # Send the decoded URLs to your designated channel with a note about the source server and channel channel = bot.get_channel(MY_CHANNEL_ID) for decoded_url in decoded_urls: note = f'Decoded URL from {message.author.name} in #{message.channel.name} ({message.guild.name}):' await channel.send(f'{note} {decoded_url}') else: # Print that the image does not contain a QR code note = f'Image from {message.author.name} in #{message.channel.name} ({message.guild.name}) does not contain a QR code.' print(note) except Exception as e: print(f'Error processing image: {str(e)}') def has_qr_code(image_data): img = Image.open(BytesIO(image_data)) decoded_objects = decode(img) return bool(decoded_objects) async def decode_image(image_data): img = Image.open(BytesIO(image_data)) decoded_objects = decode(img) decoded_urls = [obj.data.decode("utf-8") for obj in decoded_objects] return decoded_urls @bot.event async def on_message(message): try: await process_message(message) await bot.process_commands(message) except Exception as e: print(f'Error: {str(e)}') bot.run(TOKEN)
已尝试更换多个账号令牌,均出现相同错误。
解决方案
1. 降级Discord.py版本
Discord官方已禁止自机器人,v2.0及以上版本的Discord.py完全移除了自机器人支持,即使传入正确令牌也会触发登录失败。
- 执行命令降级到兼容版本:
pip install discord.py==1.7.3 - 注意:使用自机器人违反Discord服务条款,可能导致账号封禁,操作需自行承担风险。
2. 验证令牌有效性
- 确保使用的是用户令牌而非机器人令牌:机器人令牌无法用于自机器人登录,用户令牌需从Discord客户端开发者工具获取(该操作同样违反Discord条款)。
- 检查令牌格式:用户令牌通常以
Nz...或MTA...开头,复制时不要包含多余空格、换行或引号。
3. 确认账号状态
- 确保账号未被封禁、限制,且能正常通过网页端登录。
- 若账号开启了双重验证,需先在当前设备完成账号验证,避免登录时触发安全拦截。
4. 修正代码细节
- 将
MY_CHANNEL_ID改为整数类型:当前代码中赋值为字符串,需替换为实际数字ID(如MY_CHANNEL_ID = 123456789012345678),否则后续发送消息时会因channel为None报错。
内容的提问来源于stack exchange,提问作者Dibo Dqe
相关产品推荐
相关产品推荐

