Discord机器人突发Unexpected Token错误及Rich Presence图片不显示求助
Discord机器人问题排查与修复
一、Unexpected Token错误修复
你的代码最后一行存在语法错误:
client. Run(TOKEN)
问题在于Run首字母大写,且方法名与括号之间多了空格,正确写法应为:
client.run(TOKEN)
这是导致语法解析报错的直接原因。
二、Rich Presence图片不显示修复
当前代码设置Rich Presence的方式不符合discord.py API规范,且图片使用逻辑错误:
- Activity类型不匹配:
discord.ActivityType.playing类型不支持assets、details这类参数,若要显示带图片的Rich Presence,需使用discord.ActivityType.streaming类型。 - 图片调用规则:Discord Rich Presence的图片不能直接使用外部URL,必须先将图片上传到机器人的开发者应用面板的Rich Presence资产中,之后用图片的名称(而非URL)调用。
修正后的on_ready事件代码:
@client.event async def on_ready(): print(f"Logged in as {client.user}!") await client.change_presence( status=discord.Status.dnd, activity=discord.Activity( type=discord.ActivityType.streaming, name="Dynamically", details="Dreams of Desires", url="https://twitch.tv/example", # 必填流媒体链接,可填任意合法URL assets={ "large_text": "details", "large_image": "welcome" # 替换为你上传到开发者面板的图片名称 } ) )
图片上传步骤:
- 打开Discord开发者门户,找到你的机器人应用
- 进入Rich Presence > Art Assets页面,上传目标图片,记住图片名称
- 等待Discord审核完成(通常几分钟),即可在代码中使用该名称调用图片
完整修正后的代码
import discord from webserver import keep_alive import os intents = discord.Intents.all() client = discord.Client(intents=intents) welcome_channel = None prefix = "&" @client.event async def on_ready(): print(f"Logged in as {client.user}!") await client.change_presence( status=discord.Status.dnd, activity=discord.Activity( type=discord.ActivityType.streaming, name="Dynamically", details="Dreams of Desires", url="https://twitch.tv/example", assets={ "large_text": "details", "large_image": "welcome" # 替换为你上传的图片名称 } ) ) @client.event async def on_message(message): if message.content.startswith(prefix): command = message.content[len(prefix):] if command.startswith("setwelcomechannel"): if not message.author.guild_permissions.administrator: await message.channel.send("你必须是管理员才能设置欢迎频道。") return global welcome_channel welcome_channel = message.channel await message.channel.send(f"欢迎频道已设置为 {welcome_channel.name}。") if command.startswith("getwelcomechannel"): if welcome_channel is None: await message.channel.send("欢迎频道未设置。") else: await message.channel.send(f"欢迎频道当前设置为 {welcome_channel.name}。") if command.startswith("hello"): await message.channel.send("嗨!") if command.startswith("dead"): await message.channel.send("latom!") @client.event async def on_member_join(member): if welcome_channel: embed = discord.Embed( title="欢迎!", description=f"Ara ara! {member.mention}, 欢迎来到 {member.guild.name}\n希望你在这里找到安宁!", color=0x8438e8 ) embed.set_image(url='https://cdn.discordapp.com/attachments/998612463492812822/1063409897871511602/welcome.png') await welcome_channel.send(embed=embed) keep_alive() TOKEN = os.environ.get("DISCORD_BOT_SECRET") client.run(TOKEN)
内容的提问来源于stack exchange,提问作者Kenny Blinder
相关产品推荐
相关产品推荐

