对于 Spotify discord.py API 有问题



对于代码elif isinstance(activity == None, Spotify)&await ctx.send(f'{user.name} is not listening to anything :shrug:')运行时没有错误代码,但如果我的spotify没有播放,当我输入命令时,它不会打印它

以下完整代码:

@commands.command()
async def spot(self, ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title=f"{user.name}'s Spotify",
description="Currently listening to {}".format(activity.title),
color=user.color)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(name="Artist", 
value=activity.artist,
inline=False)
embed.add_field(name="Album", 
value=activity.album,
inline=False)

m1, s1 = divmod(int(activity.duration.seconds), 60)
song_length = f'{m1}:{s1}'
embed.add_field(name="Song Duration",
value=song_length,
inline=True)                   
embed.add_field(name="Track Link", 
value=f"[{activity.title}](https://open.spotify.com/track/{activity.track_id})",
inline=True)
embed.set_footer(text=f'Requested by : {ctx.author}',
icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
elif isinstance(activity == None, Spotify):
await ctx.send(f'{user.name} is not listening to anything :shrug:')

我复制了您的代码并亲自尝试。将线路elif isinstance(activity == None, Spotify):改为else:为我修复了它。

但我注意到你的代码中有一个错误,它检查用户的每个活动,并为每个活动发送一条消息。因此,当你在听Spotify时,它会说你在听和不在听。所以我修改了你的代码,让它首先检查是否有Spotify活动,然后根据它发送消息。

这是重新编写的代码:

@commands.command()
async def spot(self, ctx, user: discord.Member=None):
user = user if user else ctx.author
activity = None
for act in user.activities:
if isinstance(act, Spotify):
activity = act
break

if activity:
embed = discord.Embed(
title=f"{user.name}'s Spotify",
description="Currently listening to {}".format(activity.title),
color=user.color
)
embed.set_thumbnail(url=activity.album_cover_url)
embed.add_field(
name="Artist", 
value=activity.artist,
inline=False
)
embed.add_field(
name="Album", 
value=activity.album,
inline=False
)

m1, s1 = divmod(int(activity.duration.seconds), 60)
song_length = f'{m1}:{s1}'
embed.add_field(
name="Song Duration",
value=song_length,
inline=True
)                   
embed.add_field(
name="Track Link", 
value=f"[{activity.title}](https://open.spotify.com/track/{activity.track_id})",
inline=True
)
embed.set_footer(text=f'Requested by : {ctx.author}', icon_url=ctx.author.avatar_url)

await ctx.send(embed=embed)
else:
await ctx.send(f'{user.name} is not listening to anything :shrug:')

您只需完全删除elif,即可将消息保存在变量中,然后检查是否发送了消息。即使用户没有user.activities,此方法也是有效的

@commands.command()
async def spot(self, ctx, user: discord.Member = None):
if user == None:
user = ctx.author
pass
if user.activities:
for activity in user.activities:
if isinstance(activity, Spotify):
embed = discord.Embed(
title=f"{user.name}'s Spotify",
description="Currently listening to {}".format(activity.title),
color=user.color)
# add fields here
msg = await ctx.send(embed=embed)
break
if not msg:
await ctx.send('nothing')

最新更新