简体   繁体   中英

How to use discord.spotify class in discord.py

The discord.py documentation has a spotify class ( https://discordpy.readthedocs.io/en/stable/api.html#spotify ) And I'm wondering how to set this activity to a profile. There are no examples in the documentation. I tried using this activity in on_ready event

@client.event
async def on_ready():
  print("Bot was connected to the server")
  
  await bot.change_presence(activity=discord.Spotify(title = "Test"))

And my output is wrong.

Bot was connected to the server

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/runner/Russian-field-of-experiments-on-the-island-of-Python/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 13, in on_ready
    await bot.change_presence(activity=discord.Spotify(title = "Test"))
  File "/home/runner/Russian-field-of-experiments-on-the-island-of-Python/venv/lib/python3.8/site-packages/discord/activity.py", line 527, in __init__
    self._sync_id = data.pop('sync_id')
KeyError: 'sync_id'

full source code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!")

@bot.event
async def on_ready():
  print("Bot was connected to the server")

 await bot.change_presence(activity=discord.Spotify(title = "Test"))

bot.run("token")

How to use the Spotify class in discord.py?

To change the bot's status to "listening to Spotify" you can do this:

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Spotify"))

If you want to set it to what a specific user is listening to you can do this:

from discord import Spotify

@bot.event
async def on_ready():
user = bot.get_user(user_id) # Make sure to change this to the users ID.
while True:
 for activity in user.activities:
        if isinstance(activity, Spotify):
           await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{activity.title} by {activity.artist}"))
        else:
             await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"Nothing")) # User isn't listening to Spotify

For the above to work, the user you define must be listening to Spotify. If they're not listening to Spotify, the status will change to Nothing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM