#bot.command(aliasses=['QUEUE', 'queue', 'q', 'Q'])
async def queue(ctx):
member = ctx.message.author
voice_state = ctx.member.voice
QAPI = ctx.message.author.id
if voice_state is None:
await ctx.send(f'You need to be in "<#1022558265348980796>" Channel to use that ')
else:
await ctx.send(f'You been putted in Queue. "<#{QAPI}')
AttributeError: 'Context' object has no attribute 'member'
i can't get it. i setted the member, i specify what is voice_state.. any ideeas?
Related
I am trying to add websockets to my app. I use JWT tokens so I have to overide middleware for it.
#database_sync_to_async
def get_user(token):
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=ALGORITHM)
except:
return AnonymousUser()
token_exp = datetime.fromtimestamp(payload['exp'])
if token_exp < datetime.utcnow():
return AnonymousUser()
try:
response = requests.get(settings.OAUTH_URL, headers={'Authorization': f"Bearer {token}"})
if response.status_code == 200:
user = response.json()
return user
except:
error_logger.exception("Server is not available!")
class TokenAuthMiddleware(BaseMiddleware):
async def __call__(self, scope, receive, send):
close_old_connections()
try:
token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None)
except ValueError:
token_key = None
scope['user'] = await get_user(token_key)
return await super().__call__(scope, receive, send)
def JwtAuthMiddlewareStack(inner):
return TokenAuthMiddleware(AuthMiddlewareStack(inner))
My service is a microservice so the User model is located in another service. So I have to send a request to the service where the instance model is located. When I try to add "user" dict-like object to scope it returns me an error:
helpdesk_web | File "/usr/local/lib/python3.10/site-packages/channels/auth.py", line 176, in resolve_scope
helpdesk_web | scope["user"]._wrapped = await get_user(scope)
helpdesk_web | AttributeError: 'dict' object has no attribute '_wrapped'
If I delete this line scope['user'] = await get_user(token_key) or pass to the function model instance everything works.
Is there a way to add 'users' dict-like object instead of model instance to scope?
Code
#bot.command()
async def avatar(ctx, *, avamember : discord.Member=None):
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)
error:
Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
#bot.command()
async def avatar(ctx, *, member: discord.Member = None):
if not member:
member = ctx.message.author
em = discord.Embed(title=str(member), color=0xAE0808)
em.set_image(url=member.avatar_url)
await ctx.reply(embed=em, mention_author=False)
On responds on your comment: "AttributeError: 'Member' object has no attribute 'avatar_url'"
In my IDE you will see I used "client" rather than "bot", but that does not have anything to do with your code. Besides that, I am using the prefix ">" which can be obviously different for you.
Results:
Code in IDE:
import discord
from discord.ext import commands
class GetRole(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(name = '역할')
async def GetRoles(self, ctx):
m = await ctx.send(':one: 을 눌러 <#&817598594009661450> 역할을 얻으세요.\n:two: 를 눌러 <#&817978024700018719> 역할을 얻으세요.\n:three: 를 눌러 <#&817978098531172362> 역할을 얻으세요.')
await m.add_reaction('1️⃣')
#commands.Cog.listener()
async def on_raw_reaction_add(self, ctx, payload: discord.RawReactionActionEvent):
user = self.bot.get_user(payload.id)
if user.bot:
return
if str(payload.reaction.emoji) == "1️⃣":
role = self.bot.get_role(817598594009661450)
await user.add_roles(role)
await user.send('DONE!')
def setup(bot):
bot.add_cog(GetRole(bot))
yeah. i tried it, but error has occured
TypeError: on_raw_reaction_add() missing 1 required positional argument: 'payload'
How I fix this error?
The raw_reaction_add event does not receive both a Context and a RawReactionActionEvent object; only the payload is given, so your listener should only have two arguments in it which is self, and payload.
So I'm working on a reaction role cog, and the commands work so far. There's just one problem. When I create two different reaction roles, it only works for the second one. It's because I only have one dictionary and it updates that every time. I think I've seen people use a payload for reaction roles, but I have no idea what that does and if it would fix my problem. Is there a way to use payload to fix my problem? Thanks!! Here's my code:
import discord
from discord.ext import commands
from discord.ext.commands import BucketType, cooldown, CommandOnCooldown
import random
import json
reaction_title = ""
reactions = {}
reaction_message_id = ""
class ReactionRoles(commands.Cog):
"""Reaction roles!!\nYou need manage roles permissions to use these"""
def __init__(self, bot):
self.bot = bot
# Bot Commands
#commands.command(aliases=['rcp'])
async def reaction_create_post(self, ctx):
"""Creates an embed that shows all the reaction roles commands"""
embed = discord.Embed(title="Create Reaction Post", color=discord.Colour.dark_purple())
embed.set_author(name="Botpuns")
embed.add_field(name="Set Title", value=".rst [New Title]", inline=False)
embed.add_field(name="Add Role", value=".rar [#Role] [EMOJI]", inline=False)
embed.add_field(name="Remove Role", value=".rrr [#Role]", inline=False)
embed.add_field(name="Reaction Send Post", value=".rsp", inline=False)
await ctx.send(embed=embed)
await ctx.message.delete()
#commands.command(aliases=['rst'])
async def reaction_set_title(self, ctx, *, new_title):
global reaction_title
reaction_title = new_title
await ctx.send(f"The title for the message is now `{new_title}`")
await ctx.message.delete()
#commands.command(aliases=['rar'])
async def reaction_add_role(self, ctx, role: discord.Role, reaction):
global reactions
reactions[role.name] = reaction
await ctx.send(f"Role `{role.name}` has been added with the emoji {reaction}")
await ctx.message.delete()
print(reactions)
#commands.command(aliases=['rrr'])
async def reaction_remove_role(self, ctx, role: discord.Role):
if role.name in reactions:
del reactions[role.name]
await ctx.send(f"Role `{role.name}` has been deleted")
await ctx.message.delete()
else:
await ctx.send("That role wasn't even added smh")
print(reactions)
#commands.command(aliases=['rsp'])
async def reaction_send_post(self, ctx):
description = "React to add roles\n"
for role in reactions:
description += f"`{role}` - {reactions[role]}\n"
embed = discord.Embed(title=reaction_title, description=description, color=discord.Colour.purple())
embed.set_author(name="Botpuns")
message = await ctx.send(embed=embed)
global reaction_message_id
reaction_message_id = str(message.id)
for role in reactions:
await message.add_reaction(reactions[role])
await ctx.message.delete()
#commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
if not user.bot:
message = reaction.message
if str(message.id) == reaction_message_id:
# Add roles to user
role_to_give = ""
for role in reactions:
if reactions[role] == reaction.emoji:
role_to_give = role
role_for_reaction = discord.utils.get(user.guild.roles, name=role_to_give)
await user.add_roles(role_for_reaction)
#commands.Cog.listener()
async def on_reaction_remove(self, reaction, user):
if not user.bot:
message = reaction.message
if str(message.id) == reaction_message_id:
# Add roles to user
role_to_remove = ""
for role in reactions:
if reactions[role] == reaction.emoji:
role_to_remove = role
role_for_reaction = discord.utils.get(user.guild.roles, name=role_to_remove)
await user.remove_roles(role_for_reaction)
def setup(bot):
bot.add_cog(ReactionRoles(bot))
I've tried 3 times to do this code, my plan is removing all roles from an user, writing the roles in an ctx.send() to send a message with the old roles in the channel, after that, send a message that says the user was imprisoned and the reason and give the prisoner role.
'BabaYaga' is the adm's role; 'D 001' is the prisoner role
Code 01:
# Detentos 3
#client.command()
#commands.has_any_role('BABAYAGA')
async def det(ctx, member: discord.Member = None, role = discord.Guild.roles, *, reason = None):
if member == None:
await ctx.send('Say the user')
return
if reason == None:
await ctx.send('Say the reason')
return
Roles = member.roles
for _ in Roles:
print(Roles)
await client.remove_roles(member, *Roles)
await member.add_role(ctx, member, role)
await ctx.send(f'{member} was arrested for {reason}')
Code 02:
# Detentos 2
#client.command()
#commands.has_any_role('BABAYAGA')
async def det(ctx, member: discord.Member, *,reason):
role = discord.utils.get(ctx.guild.roles, name = 'D 001')
await ctx.send(f'{member.roles}')
for _ in member.roles:
await member.remove_roles(member.top_role)
await ctx.message.add_reaction(emoji=self.tick)
await member.add_roles(role)
await ctx.send(f'{member} was arrested for {reason}')
Code 03:
# Detentos
#client.command()
#commands.has_any_role('BABAYAGA')
async def det(self, ctx, member: discord.Member, *, reason = None):
if reason == None:
await ctx.send('Say the reason!')
return
roles = discord.utils.get(member.guild.roles) # member's roles
role = discord.utils.get(ctx.guild.roles, name = 'D 001') # Det's role
await ctx.message.add_reaction(emoji=self.tick)
await member.edit(member.guild.roles)
await ctx.send(f'{discord.Member} preso por {reason}')
await ctx.send(f'cargos do {discord.Member}: {member.roles}')
Code 04:
# Detentos
#client.command()
#commands.has_any_role('BABAYAGA')
async def det(self, ctx, member: discord.Member = None, *, reason = None):
if reason == None:
await ctx.send('Say the reason! :angry: :angry:')
return
if member == None:
await ctx.send('Say the user')
return
rolesserver = ['D 001', 'D 002', 'D 003', 'D 004', 'testers']
await ctx.send(f'{member.roles}')
for roles in rolesserver:
await client.remove_roles(member, *roles)
await ctx.send(f'<#{member.id}> was arrested for {reason}')
I don't know what is my error there. Can anyone help me?
There are a lot of mistakes in your code snippets. Here's a correct way of doing it:
#client.command()
#commands.has_any_role('BABAYAGA')
async def det(ctx, member: discord.Member, *, reason):
await ctx.send(f'Removed ", ".join([role.name for role in member.roles])')
for role in member.roles:
await member.remove_roles(role)
await ctx.message.add_reaction(emoji=self.tick)
role = discord.utils.get(ctx.guild.roles, name = 'D 001')
await member.add_roles(role)
await ctx.send(f'{member} was arrested for {reason}')
Some advices:
The get method returns a single item from an iterable so writing get(member.guild.roles) won't work, you can just type roles = member.guild.roles
You must set a variable in your for loops or else, you can't cycle through your member's roles, so your for _ in member.roles must become for role in member.roles.
To have a nice message with all your member's roles, you can use the join method combined with list comprehension (eg. ', '.join([role.name for role in member.roles]))
remove_roles is a discord.Member method so you have to use it this way: member.remove_roles(role)