Playlist playback error. Discord py. Youtube dl - discord

I'm writing a Discord bot to play music
When trying to play a playlist, it throws the error 'Command raised an exception: KeyError: 'webpage_url'. What could be the problem?
It won't even load the first video
def __init__(self, ctx: commands.Context, source: discord.FFmpegPCMAudio, *, data: dict, volume: float = 0.5):
super().__init__(source, volume)
self.requester = ctx.author
self.channel = ctx.channel
self.data = data
self.title = data.get('title')
self.tags = data.get('tags')
self.url = data.get('webpage_url')
self.stream_url = data.get('url')
def __str__(self):
return '**{0.title}** by **{0.uploader}**'.format(self)
#classmethod
async def create_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.BaseEventLoop = None):
loop = loop or asyncio.get_event_loop()
partial = functools.partial(cls.ytdl.extract_info, search, download=False, process=False)
data = await loop.run_in_executor(None, partial)
if data is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
if 'entries' not in data:
process_info = data
else:
process_info = None
for entry in data['entries']:
if entry:
process_info = entry
break
if process_info is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
webpage_url = process_info['webpage_url']
partial = functools.partial(cls.ytdl.extract_info, webpage_url, download=False)
processed_info = await loop.run_in_executor(None, partial)
if processed_info is None:
raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))
if 'entries' not in processed_info:
info = processed_info
else:
info = None
while info is None:
try:
info = processed_info['entries'].pop(0)
except IndexError:
raise YTDLError('Couldn\'t retrieve any matches for `{}`'.format(webpage_url))
return cls(ctx, discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS), data=info)
i'm newbie. sorry for what might be a stupid question

Related

object has no attribute 'to_components'

I'm trying to make a blackjack command for my Discord Bot in python, I'm making small codes and little by little testing and improving, see below:
import discord
from discord.ext import commands
from discord import app_commands
import random, json, datetime
class bj(discord.ui.Button):
def __init__(self, game ,gamesum, player_cards):
super().__init__()
self.value = None
#discord.ui.button (label="Hit", style=discord.ButtonStyle.blurple)
async def confirm(self, button: discord.ui.Button, interaction: discord. Interaction):
self.value = True
self.stop()
value_1=["A", 1,2,3,4,5,6,7,8,9,10,"J","Q","K",]
nype_1=["♦️","♠️","♥️","♣️"]
card_value_3 = random.randint(0, len(value_1) - 1)
nype_card_3 = random.randint(0, len(nype_1) - 1)
card_3 = f"{card_value_3[card_value_3]} {card_value_3[nype_card_3]}"
await match.edit()
match.edit_field(name='Your hand', value=f"{player_cards} {card_value_3}{nype_card_3}")
if type(card_value_3)==str:
if value_card_3=="A":
value_letter_3=11
else:
value_letter_3=10
else:
value_letter_3=value_card_3
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def setup_hook(self) -> None:
self.add_view(DropdownView())
async def on_ready(self):
await aclient.change_presence(activity = discord.Streaming(name = "/news", url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"We entered as {self.user}!")
print(f"That has the ID {self.user.id}")
client = client()
tree = app_commands.CommandTree(aclient)
#tree.command(name='blackjack', description='Play a game of blackjack')
async def blackjack(interaction: discord.Interaction, amount:int):
await open_account(interaction.user)
money = await add_money(interaction.user)
if amount>money[0]:
await interaction.response.send_message(f"You don't have all this amount {interaction.user.mention}.")
else:
if quantity<0:
await interaction.response.send_message(f"You must enter a positive value")
else:
value_1=["A",2,3,4,5,6,7,8,9,10,'J','Q',"K"]
nype_1=["♦️","♠️","♥️","♣️"]
value_card_a = random.randint(0, len(value_1) - 1)
nype_card_a = random.randint(0, len(nype_1) - 1)
letter_a = f"{value_1[value_card_a]}{nype_1[nype_letter_a]}"
b_card_value = random.randint(0, len(1_value) - 1)
nype_card_b = random.randint(0, len(nype_1) - 1)
letter_b = f"{value_1[value_card_b]}{nype_1[nype_letter_a]}"
player_cards = f"{card_a} {card_b}"
if type(value_card_a)==str:
if value_card_a=="A":
value_letter_a=11
else:
value_letter_a=10
else:
value_card_a=value_card_a
if type(value_card_b)==str:
if value_card_b=="A":
value_letter_b=11
else:
value_letter_b=10
else:
value_card_b=value_card_b
sum_of_game=value_card_a+value_card_b
await add_money(interaction.user, -1*amount)
if sum_of_game==21:
result='Blackjack'
titulo_resultado=f'You won ~~K~~ {1.5*amount}'
else:
result=sum_of_game
titulo_resultado=f'You invested ~~K~~ {amount} in this blackjack'
departure=discord.Embed(
description=f'{result_title}',
colour=discord.Color.random()
)
match.add_field(name='Your hand', value=f"{player_cards}\n{result}")
if result=='Blackjack':
await add_money(interaction.user, 1.5*amount)
await interaction.response.send_message(embed=game, view=bj(game ,gamesum, player_cards))
async def open_account(user):
users = await bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]['wallet'] = 0
users[str(user.id)]['bank']= 0
with open("money.json", "w") as f:
json.dump(users, f)
return true
async def bank_data():
with open("money.json", "r") as f:
users = json.load(f)
return users
async def add_money(user, change=0, mode = "wallet"):
users = await bank_data()
users[str(user.id)][mode] +=change
with open("money.json", "w") as f:
json.dump(users, f)
money = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
return money
aclient.run(Token)
But in await interaction.response.send_message(embed=match, view=bj(match ,game_sum, player_cards)) is reporting the error
2023-02-06 19:14:31 ERROR discord.app_commands.tree Ignoring exception in command 'blackjack'
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 1155, in blackjack
await interaction.response.send_message(embed=partida, view=bj(partida ,soma_de_jogo, cartas_jogador))
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/interactions.py", line 754, in send_message
params = interaction_message_response_params(
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 577, in interaction_message_response_params
data['components'] = view.to_components()
AttributeError: 'bj' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'blackjack' raised an exception: AttributeError: 'bj' object has no attribute 'to_components'
I tried to interpret the error, as I recently started programming, it didn't help much, I asked in ChatGPT, and it also didn't help much (the error didn't even change), so the artificial intelligence itself suggested that I come and ask here, I hope it helps me help(Oh, and sorry for not leaving everything organized and well separated, they said there was a lot of code and little information).

'RawReactionActionEvent' object has no attribute 'member'

Im having this issue and i still cant find a solution this is the code
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
await payload.member.add_roles(commands.reaction_role)
#commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.remove_roles(commands.reaction_role)
#commands.command()
async def set_reaction_message(self, ctx, message_id=None, role_id=None):
for channel in ctx.guild.channels:
try:
commands.reaction_message = await channel.fetch_message(int(message_id))
break
except:
pass
problem: File "c:\Users\MY-NAME\Desktop\Overige en school\Discord Bot\cogs\reaction.py", line 17, in on_raw_reaction_add
await payload.member.add_roles(commands.reaction_role)
AttributeError: 'RawReactionActionEvent' object has no attribute 'member'
can someone please help me this is been bothering me now for 2days and i can't even find a solution
I know according to the documentation discord.RawReactionActionEvent payload has the object member. But why don't you make it easier for yourself and get the member in the same way as in your on_raw_reaction_remove event? The following should work.
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.add_roles(commands.reaction_role)
#commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
if payload.message_id == commands.reaction_message.id and commands.reaction_role != None:
guild = self.client.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
await member.remove_roles(commands.reaction_role)
#commands.command()
async def set_reaction_message(self, ctx, message_id=None, role_id=None):
for channel in ctx.guild.channels:
try:
commands.reaction_message = await channel.fetch_message(int(message_id))
break
except:
pass

Discord bot ctx is being displayed as argument

Thats a test code where im trying to work in classes. Even tho in commands it displayes ctx as required arg instead and it works only if i put it before self.
class Quiz:
def __init__(self, question, answer):
self.question = question
self.answer = answer
#bot.command(pass_context=True)
async def quiz(self, ctx):
fido = Quiz("Starter mass?", "yeah")
nope = Quiz("WHAT?", "lel")
await ctx.send(fido.question)
def check(m):
return m.content == 'heh'
msg = await bot.wait_for('message', check=check)
await ctx.send('Right {.author}!'.format(msg))
Error:
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
How can I fix this?
As crazy as it sounds, remove the self argument from your method. The commands decorator will take care of this. (You can also use a command cog)
class Quiz:
def __init__(self, question, answer):
self.question = question
self.answer = answer
#bot.command(pass_context=True)
async def quiz(ctx):
fido = Quiz("Starter mass?", "yeah")
nope = Quiz("WHAT?", "lel")
await ctx.send(fido.question)
def check(m):
return m.content == 'heh'
msg = await bot.wait_for('message', check=check)
await ctx.send('Right {.author}!'.format(msg))
Also your check function doesn't work correctly. It always uses the fido question and says you are correct only after responding with 'heh'.
#bot.command(pass_context=True)
async def quiz(ctx):
fido = Quiz("Starter mass?", "yeah")
nope = Quiz("WHAT?", "lel")
question = random.choice((fido, nope))
await ctx.send(question.question)
check = lambda m: m.content.lower() == question.answer
msg = await bot.wait_for('message', check=check)
await ctx.send(f'Right **{msg.author.name}**!')

Discord.py Music player loop

i'm looking for advice on how to make a player loop process that takes The songs from my queue and automatically plays them. The ones that ive tried making are only possible if the bot is used in 1 server. ive got alot more than 1 server that my bot is in. Im just looking for some advice on where to start
my code right now.
import wavelink
import discord
import asyncio
import random
from discord.ext import commands
import humanize as h
class MusicQueue(asyncio.Queue):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._queue = []
self.index = 0
self.repeat_start = None
def reset(self):
while len(self._queue)-1 > self.index:
self._queue.pop()
self.repeat_start = None
#dont reset the index, keep the history
def hard_reset(self):
self._queue.clear()
self.index = 0
self.repeat_start = None
def shuffle(self):
if self.repeat_start is not None:
n = self.repeat_start
else:
n = self.index
shuffle = self._queue[n:]
random.shuffle(shuffle)
old = self._queue[:n]
self._queue = old + shuffle
def repeat(self):
if self.repeat_start is not None:
self.repeat_start = None
else:
self.repeat_start = self.index
def _get(self):
if self.repeat_start is not None:
if len(self._queue) == 1:
# it doesnt seem to like it when only one item is in the queue, so dont increase the index
return self._queue[0]
diff = self.index - self.repeat_start
self.index += 1
if len(self._queue) <= self.index:
self.index = self.repeat_start
return self._queue[diff]
else:
r = self._queue[self.index]
self.index += 1
return r
def putleft(self, item):
self._queue.insert(self.index+1, item)
def empty(self):
if self.repeat_start is not None:
if len(self._queue) <= self.index:
self.index = self.repeat_start
return len(self._queue) <= self.index
#property
def q(self):
return self._queue[self.index:]
#property
def history(self):
return self._queue[:self.index]
class music(commands.Cog):
def __init__(self, client):
self.client = client
self.queues = {}
if not hasattr(client, 'wavelink'):
self.client.wavelink : wavelink.Client = wavelink.Client(self.client)
self.client.loop.create_task(self.start_nodes())
async def start_nodes(self):
await self.client.wait_until_ready()
await self.client.wavelink.initiate_node(host='0.0.0.0',
port=2333,
rest_uri='http://0.0.0.0:2333',
password='youshallnotpass',
identifier='DRIZZI',
region='us_central')
def getQueue(self,ctx):
if not self.queues[ctx.guild.id]:
self.queues[ctx.guild.id] = MusicQueue()
queue = self.queues[ctx.guild.id]
return queue
#commands.command(name='connect')
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
if not channel:
try:
channel = ctx.author.voice.channel
except AttributeError:
raise discord.DiscordException('No channel to join. Please either specify a valid channel or join one.')
player = self.client.wavelink.get_player(ctx.guild.id)
await ctx.send(f'Connecting to **`{channel.name}`**')
await player.connect(channel.id)
#commands.command()
async def play(self, ctx, *, query: str):
def convert_from_ms( milliseconds ):
seconds, milliseconds = divmod(milliseconds,1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
seconds = seconds
return hours, minutes, seconds
queue : MusicQueue = self.getQueue(ctx)
tracks = await self.client.wavelink.get_tracks(f'ytsearch:{query}')
song : wavelink.Track = tracks[0]
if song.duration > 600000:
return await ctx.send("Song may not be more than 10 minutes")
if not tracks:
return await ctx.send('Could not find any songs with that query.')
player = self.client.wavelink.get_player(ctx.guild.id)
if not player.is_connected:
await ctx.invoke(self.connect_)
emb = discord.Embed(title = f'Added {str(song)} to the queue')
emb.set_thumbnail(url=song.thumb)
time=convert_from_ms(song.duration)
emb.add_field(name='Duration', value=f'{time[1]}:{time[2]}')
emb.add_field(name='Uploaded by', value=song.author)
await ctx.send(embed=emb)
await queue.put((song,player))
def setup(client):
client.add_cog(music(client))```

How to make use of filter using ContentType to check if model instance is already present or not

I am trying to implement like functionality based on this . I want to restrict user to hit like on a event only once. But I am getting the following error. I have added full error details at bottom
Exception Type: AttributeError at /api/event/likes/create/
Exception Value: 'str' object has no attribute '_meta'
models.py
class ThumbsUpManager(models.Manager):
def create_by_model_type(self, model_type, slug, content, user, parent_obj=None):
model_qs = ContentType.objects.filter(model=model_type)
if model_qs.exists():
some_model = model_qs.first().model_class()
obj_qs = some_model.objects.filter(slug=slug)
if obj_qs.exists() and obj_qs.count() == 1:
instance = self.model()
instance.content = content
instance.user = user
instance.content_type = model_qs.first()
instance.object_id = obj_qs.first().id
if parent_obj:
instance.parent = parent_obj
instance.save()
return instance
return None
class Thumbsup(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
content = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=True)
objects = ThumbsUpManager()
class Meta:
ordering = ['-timestamp']
def __str__(self):
return str(self.user.username)
#property
def is_parent(self):
if self.parent is not None:
return False
return True
urls.py
urlpatterns = [
path('create/', ThumbsUpCreateAPIView.as_view(), name='create'),
]
view.py
class ThumbsUpCreateAPIView(CreateAPIView):
queryset = Thumbsup.objects.all()
permission_classes = [IsAuthenticated, ]
def get_serializer_class(self):
model_type = self.request.GET.get("type")
slug = self.request.GET.get("slug")
obj_qs = Thumbsup.objects.all()
print(obj_qs)
parent_id = self.request.GET.get("parent_id", None)
return create_thumbs_up_serializer(
model_type=model_type,
slug=slug,
parent_id=parent_id,
user=self.request.user
)
serializers.py
def create_thumbs_up_serializer(model_type=None, slug=None, parent_id=None, user=None):
class ThumbsUpCreateSerializer(ModelSerializer):
class Meta:
model = Thumbsup
fields = [
'id',
'content',
'timestamp',
]
def __init__(self, *args, **kwargs):
self.model_type = model_type
self.slug = slug
self.parent_obj = None
self.user = user
if parent_id:
parent_qs = Thumbsup.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
self.parent_obj = parent_qs.first()
return super(ThumbsUpCreateSerializer, self).__init__(*args, **kwargs)
def validate(self, data):
model_type = self.model_type
slug = self.slug
model_qs = ContentType.objects.filter(model=model_type)
if not model_qs.exists() or model_qs.count() != 1:
raise ValidationError("This is not a valid content type")
SomeModel = model_qs.first().model_class()
obj_qs = SomeModel.objects.filter(slug=self.slug)
if not obj_qs.exists() or obj_qs.count() != 1:
raise ValidationError("This is not a slug for this content type")
######################### ######################### #########################
How do I need to make query here to check if the user already liked the Event or not?
I tried the following way, but it is not working.
user_act = Thumbsup.objects.filter(user=self.user, content_type=ContentType.objects.get_for_model(model_type))
if user_act.exists():
raise ValidationError("You have already liked the event")
return data
def create(self, validated_data):
content = validated_data.get("content")
if user:
main_user = user
else:
main_user = User.objects.all().first()
model_type = self.model_type
slug = self.slug
parent_obj = self.parent_obj
thumbsup = Thumbsup.objects.create_by_model_type(
model_type, slug, content, main_user,
parent_obj=parent_obj,
)
return thumbsup
return ThumbsUpCreateSerializer
Traceback:
File "E:\GIT\blog\backend\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "E:\GIT\blog\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "E:\GIT\blog\backend\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\GIT\blog\backend\venv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "E:\GIT\blog\backend\venv\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
497. response = self.handle_exception(exc)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\views.py" in handle_exception
457. self.raise_uncaught_exception(exc)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception
468. raise exc
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\views.py" in dispatch
494. response = handler(request, *args, **kwargs)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\generics.py" in post
190. return self.create(request, *args, **kwargs)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\mixins.py" in create
18. serializer.is_valid(raise_exception=True)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\serializers.py" in is_valid
235. self._validated_data = self.run_validation(self.initial_data)
File "E:\GIT\blog\backend\venv\lib\site-packages\rest_framework\serializers.py" in run_validation
433. value = self.validate(value)
File "E:\GIT\test-heroku4\thumbsup\api\serializers.py" in validate
124. user_act = Thumbsup.objects.filter(user=self.user, content_type=ContentType.objects.get_for_model(model_type))
File "E:\GIT\blog\backend\venv\lib\site-packages\django\contrib\contenttypes\models.py" in get_for_model
40. opts = self._get_opts(model, for_concrete_model)
File "E:\GIT\blog\backend\venv\lib\site-packages\django\contrib\contenttypes\models.py" in _get_opts
27. model = model._meta.concrete_model
Exception Type: AttributeError at /api/event/likes/create/
Exception Value: 'str' object has no attribute '_meta'
I checked the model instance before saving in model manager like below and it is working fine. I do not know whether this is the correct way to do the task or not (I'm very new to django. Suggestions are most welcome)
def create_by_model_type(self, model_type, slug, content, user, parent_obj=None):
model_qs = ContentType.objects.filter(model=model_type)
if model_qs.exists():
some_model = model_qs.first().model_class()
obj_qs = some_model.objects.filter(slug=slug)
if obj_qs.exists() and obj_qs.count() == 1:
instance = self.model()
instance.content = content
instance.user = user
instance.content_type = model_qs.first()
instance.object_id = obj_qs.first().id
if parent_obj:
instance.parent = parent_obj
#### Here I have checked for existence before saving the instance ####
if Thumbsup.objects.filter(object_id=instance.object_id, user=instance.user).exists():
raise ValidationError({'already_liked': 'You have already liked the item'})
instance.save()
return instance
return None

Resources