How can I resolve the error 'str' object has no attribute 'is_paused' in discord.py?

huangapple go评论100阅读模式
英文:

How can I resolve the error 'str' object has no attribute 'is_paused' in discord.py?

问题

以下是您要翻译的内容:

[2023-02-19 05:14:12] [ERROR] discord.ext.commands.bot: Ignoring exception in command play
Traceback (most recent call last):
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\toto\PycharmProjects\pythonProject\music_bot-main\main.py", line 101, in play
elif self.is_paused:
AttributeError: 'str' object has no attribute 'is_paused'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'is_paused'

import discord
from discord.ext import commands
import os
import asyncio

import all of the cogs

from help_cog import help_cog

from music_cog import music_cog

intents = discord.Intents.all()
client = commands.Bot(command_prefix='.', intents=intents)

@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print('------')

remove the default help command so that we can write out own

client.remove_command('help')

register the class with the bot

bot.add_cog(help_cog(bot))

client.add_cog(music_cog(client))

code du bot

class music_cog(commands.Cog):
def init(self, bot):
self.bot = bot

  1. # all the music related stuff
  2. self.is_playing = False
  3. self.is_paused = False
  4. # 2d array containing [song, channel]
  5. self.music_queue = []
  6. self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
  7. self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
  8. 'options': '-vn'}
  9. self.vc = None
  10. # searching the item on youtube
  11. def search_yt(self, item):
  12. with YoutubeDL(self.YDL_OPTIONS) as ydl:
  13. try:
  14. info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
  15. except Exception:
  16. return False
  17. return {'source': info['formats'][0]['url'], 'title': info['title']}
  18. def play_next(self):
  19. if len(self.music_queue) > 0:
  20. self.is_playing = True
  21. # get the first url
  22. m_url = self.music_queue[0][0]['source']
  23. # remove the first element as you are currently playing it
  24. self.music_queue.pop(0)
  25. self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
  26. else:
  27. self.is_playing = False
  28. # infinite loop checking
  29. async def play_music(self, ctx):
  30. if len(self.music_queue) > 0:
  31. self.is_playing = True
  32. m_url = self.music_queue[0][0]['source']
  33. # try to connect to voice channel if you are not already connected
  34. if self.vc == None or not self.vc.is_connected():
  35. self.vc = await self.music_queue[0][1].connect()
  36. # in case we fail to connect
  37. if self.vc == None:
  38. await ctx.send("Could not connect to the voice channel")
  39. return
  40. else:
  41. await self.vc.move_to(self.music_queue[0][1])
  42. # remove the first element as you are currently playing it
  43. self.music_queue.pop(0)
  44. self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
  45. else:
  46. self.is_playing = False

@client.command(name="play", aliases=["p", "playing"], help="Plays a selected song from youtube")
async def play(ctx, self, *args):
query = " ".join(args)

  1. voice_channel = ctx.author.voice.channel
  2. if voice_channel is None:
  3. # you need to be connected so that the bot knows where to go
  4. await ctx.send("Connect to a voice channel!")
  5. elif self.is_paused:
  6. self.vc.resume()
  7. else:
  8. song = self.search_yt(query)
  9. if type(song) == type(True):
  10. await ctx.send(
  11. "Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
  12. else:
  13. await ctx.send("Song added to the queue")
  14. self.music_queue.append([song, voice_channel])
  15. if self.is_playing == False:
  16. await self.play_music(ctx)

@client.command(name="pause", help="Pauses the current song being played")
async def pause(self, ctx, *args):
if self.is_playing:
self.is_playing = False
self.is_paused = True
self.vc.pause()
elif self.is_paused:
self.is_paused = False
self.is_playing = True
self.vc.resume()

@client.command(name="resume", aliases=["r"], help="Resumes playing with the discord bot")
async def resume(self, ctx, *args):
if self.is_paused:
self.is_paused = False
self.is_playing = True
self.vc.resume()

@client.command(name="skip", aliases=["s"], help="Skips the current song being played")
async def skip(self, ctx):
if self.vc != None and self.vc:
self.vc.stop()
# try to play next in the queue if it exists
await self.play_music(ctx)

@client.command(name="queue", aliases=["q"], help="Displays the current songs in queue")
async def queue(self, ctx):
retval = ""
for i in range(0, len(self.music_queue)):
# display a max of 5 songs in the current queue
if (i > 4): break
retval += self.music_queue[i][0]['title'] + "\n"

  1. if retval != "":
  2. await ctx.send(retval)
  3. else:
英文:

> [2023-02-19 05:14:12] [ERROR ] discord.ext.commands.bot: Ignoring exception in command play
Traceback (most recent call last):
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\toto\PycharmProjects\pythonProject\music_bot-main\main.py", line 101, in play
elif self.is_paused:
AttributeError: 'str' object has no attribute 'is_paused'

> The above exception was the direct cause of the following exception:

>Traceback (most recent call last):
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\toto\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'is_paused'

  1. import discord
  2. from discord.ext import commands
  3. import os
  4. import asyncio
  5. # import all of the cogs
  6. # from help_cog import help_cog
  7. # from music_cog import music_cog
  8. intents = discord.Intents.all()
  9. client = commands.Bot(command_prefix='.', intents=intents)
  10. @client.event
  11. async def on_ready():
  12. print(f'Logged in as {client.user} (ID: {client.user.id})')
  13. print('------')
  14. # remove the default help command so that we can write out own
  15. client.remove_command('help')
  16. # register the class with the bot
  17. # bot.add_cog(help_cog(bot))
  18. # client.add_cog(music_cog(client))
  19. # code du bot
  20. class music_cog(commands.Cog):
  21. def __init__(self, bot):
  22. self.bot = bot
  23. # all the music related stuff
  24. self.is_playing = False
  25. self.is_paused = False
  26. # 2d array containing [song, channel]
  27. self.music_queue = []
  28. self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
  29. self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
  30. 'options': '-vn'}
  31. self.vc = None
  32. # searching the item on youtube
  33. def search_yt(self, item):
  34. with YoutubeDL(self.YDL_OPTIONS) as ydl:
  35. try:
  36. info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
  37. except Exception:
  38. return False
  39. return {'source': info['formats'][0]['url'], 'title': info['title']}
  40. def play_next(self):
  41. if len(self.music_queue) > 0:
  42. self.is_playing = True
  43. # get the first url
  44. m_url = self.music_queue[0][0]['source']
  45. # remove the first element as you are currently playing it
  46. self.music_queue.pop(0)
  47. self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
  48. else:
  49. self.is_playing = False
  50. # infinite loop checking
  51. async def play_music(self, ctx):
  52. if len(self.music_queue) > 0:
  53. self.is_playing = True
  54. m_url = self.music_queue[0][0]['source']
  55. # try to connect to voice channel if you are not already connected
  56. if self.vc == None or not self.vc.is_connected():
  57. self.vc = await self.music_queue[0][1].connect()
  58. # in case we fail to connect
  59. if self.vc == None:
  60. await ctx.send("Could not connect to the voice channel")
  61. return
  62. else:
  63. await self.vc.move_to(self.music_queue[0][1])
  64. # remove the first element as you are currently playing it
  65. self.music_queue.pop(0)
  66. self.vc.play(discord.FFmpegPCMAudio(m_url, **self.FFMPEG_OPTIONS), after=lambda e: self.play_next())
  67. else:
  68. self.is_playing = False
  69. @client.command(name="play", aliases=["p", "playing"], help="Plays a selected song from youtube")
  70. async def play(ctx, self, *args):
  71. query = " ".join(args)
  72. voice_channel = ctx.author.voice.channel
  73. if voice_channel is None:
  74. # you need to be connected so that the bot knows where to go
  75. await ctx.send("Connect to a voice channel!")
  76. elif self.is_paused:
  77. self.vc.resume()
  78. else:
  79. song = self.search_yt(query)
  80. if type(song) == type(True):
  81. await ctx.send(
  82. "Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
  83. else:
  84. await ctx.send("Song added to the queue")
  85. self.music_queue.append([song, voice_channel])
  86. if self.is_playing == False:
  87. await self.play_music(ctx)
  88. @client.command(name="pause", help="Pauses the current song being played")
  89. async def pause(self, ctx, *args):
  90. if self.is_playing:
  91. self.is_playing = False
  92. self.is_paused = True
  93. self.vc.pause()
  94. elif self.is_paused:
  95. self.is_paused = False
  96. self.is_playing = True
  97. self.vc.resume()
  98. @client.command(name="resume", aliases=["r"], help="Resumes playing with the discord bot")
  99. async def resume(self, ctx, *args):
  100. if self.is_paused:
  101. self.is_paused = False
  102. self.is_playing = True
  103. self.vc.resume()
  104. @client.command(name="skip", aliases=["s"], help="Skips the current song being played")
  105. async def skip(self, ctx):
  106. if self.vc != None and self.vc:
  107. self.vc.stop()
  108. # try to play next in the queue if it exists
  109. await self.play_music(ctx)
  110. @client.command(name="queue", aliases=["q"], help="Displays the current songs in queue")
  111. async def queue(self, ctx):
  112. retval = ""
  113. for i in range(0, len(self.music_queue)):
  114. # display a max of 5 songs in the current queue
  115. if (i > 4): break
  116. retval += self.music_queue[i][0]['title'] + "\n"
  117. if retval != "":
  118. await ctx.send(retval)
  119. else:
  120. await ctx.send("No music in queue")
  121. @client.command(name="clear", aliases=["c", "bin"], help="Stops the music and clears the queue")
  122. async def clear(self, ctx):
  123. if self.vc != None and self.is_playing:
  124. self.vc.stop()
  125. self.music_queue = []
  126. await ctx.send("Music queue cleared")
  127. @client.command(name="leave", aliases=["disconnect", "l", "d"], help="Kick the bot from VC")
  128. async def dc(self, ctx):
  129. self.is_playing = False
  130. self.is_paused = False
  131. await self.vc.disconnect()
  132. @client.command()
  133. async def bonjour(ctx):
  134. await ctx.send("Bonjour")
  135. # start the bot with our token
  136. client.run(os.getenv("TOKEN"))

答案1

得分: 1

你在很多非类方法中都加入了self参数。所以self最终变成了你的context对象,而ctx是命令参数。只需从那些不需要self的方法中移除self。也就是说,那些不属于类的每个方法。

  1. async def play(ctx, *args):
  2. ...
  3. async def pause(ctx, *args):
  4. ...
  5. async def resume(ctx, *args):
  6. ...
  7. async def skip(ctx):
  8. ...
  9. async def queue(ctx):
  10. ...
  11. async def clear(ctx):
  12. ...
  13. async def dc(ctx):
  14. ...

以上是需要更改的部分。

英文:

You've given lots of non-class methods the self parameter. So self ends up being your context object and ctx the command argument. Just remove self from the methods that don't need it. ie, every method that doesn't belong to a class.

  1. async def play(ctx, *args):
  2. ...
  3. async def pause(ctx, *args):
  4. ...
  5. async def resume(ctx, *args):
  6. ...
  7. async def skip(ctx):
  8. ...
  9. async def queue(ctx):
  10. ...
  11. async def clear(ctx):
  12. ...
  13. async def dc(ctx):
  14. ...

Above are the ones that need changing.

huangapple
  • 本文由 发表于 2023年2月19日 12:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定