How to make this remove role command work properely? - discord.py

#client.command()
async def number_4(ctx, role):
role = discord.utils.get(ctx.guild.roles, name = role)
await ctx.author.remove_roles(role)
I'm not really sure how to make this work properly...

I've made a few changes. When calling the command you want to mention the role: #role
Keep in mind this will only work if the bot has a role higher up than the role you are trying to remove.
#client.command()
async def number_4(ctx, role: discord.Role):
await ctx.message.author.remove_roles(role)

Related

Discord.py: Guild object has no attribute create_scheduled_event

Discord.py is handy to automate things and I am trying to create a scheduled discord event by command. But it seems that I cannot call the function create_scheduled_event of the Guild object while other functions work fine.
For example, the function fetch_roles() works fine and returns the roles of my guild.
But calling the function create_scheduled_event raises the error 'Guild' object has no attribute 'create_scheduled_event'.
Does anybody have an idea what I am missing, here?
Thanks in advance!
Here's the code
import discord
client = discord.Client()
#client.event
async def on_message(message):
# ...
if message.content.startswith('!newevent'):
myguild = client.guilds[0]
roles = await myguild.fetch_roles()
print(roles)
newevt = await myguild.create_scheduled_event(...)
client.run(TOKEN)

Adding a single role to all server members

So I am trying to make the bot give all the server members a single role. Code:
#commands.command(pass_context = True)
async def test(self, ctx, role: discord.Role):
for user in ctx.guild.members:
await user.add_roles(role)
print(f'{user.name} {role.name}')
However, it only printsOdysea(the name of my bot) test role And only gives the role to itself.
Any ideas how to fix this?
By the comment section you can do like this.
Ps. Im using client variable instead bot, that's up to you
In main file
client = commands.Bot(command_prefix=[your_prefix], intents=discord.Intents().all())
In cogs
#commands.command()
async def test(self, ctx, role:discord.Role):
for member in ctx.guild.members:
try:
await member.add_role(role)
except:
pass
print(f"{member.name}, {role.name}")

How to use django groups and perms in django-rest-framework

How to handle complex required permissions in any API using django-rest-framework?
For example, you have three tier support operators who have access to APIs, but they should only have access to respective endpoint and as the last tier, superadmin should have everything in hands.
How to solve this simple problem by django group and permissions?
There are lots of answers being related to AND or OR the perms in permission_classes like
def get_permissions(self):
return (
IsAuthenticated & (IsCommitteeHead|IsCommitteeMember|IsAdminUser)
)()
or
permission_classes = [IsAuthenticated &(IsCommitteeHead|IsCommitteeMember|IsAdminUser)]
but I think hard coding always makes the code a complete mess!
Create new permission model permission from django base model permission like this:
from rest_framework.permissions import DjangoModelPermissions
class FullDjangoModelPermissions(DjangoModelPermissions):
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
And in view class like this:
class SomeAwuful(GenericAPIView):
...
permission_classes = [FullDjangoModelPermissions]
...
Then you can go in Django admin dashboard and set who has access to what, or creating group to access features, like this:

User's avatar discord.py 2.0

How to get member's avatar in discord.py v2?
Before, it was like this:
#client.command(aliases=["av"])
async def avatar(ctx, *, avamember : discord.Member=None):
userAvatarUrl = avamember.avatar_url
embed2 = discord.Embed(title=f"{avamember}")
embed2.set_image(url=userAvatarUrl)
await ctx.send(embed=embed2)
Error I got:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
Thanks!
You need to replace avamember.avatar_url with avamember.avatar.url.
Here's the link to the 2.0 docs if you're interested:
https://discordpy.readthedocs.io/en/master/api.html#discord.Asset

check OTP before registration in Django Rest Auth

I am using Django Rest Auth plugin for registration and login in Django Rest Framework. I want to check OTP (unique key) while user registration.
We are sending OTP based on Mobile number to users. Django checks OTP after registration. I want to set those condition before registration.
If conditions are true then registration should be done.
class SignupForm(forms.Form):
otp_no = forms.CharField(label='OptNo', required=True)
def signup(self, request, user):
try:
otpobj = Otp.objects.get(pk=self.cleaned_data['otp_no'])
if otpobj.phone_number == self.cleaned_data['phone_number']:
user_number = UserNumber(user=user, phone_number=self.cleaned_data['phone_number'])
user_number.save()
else:
raise forms.ValidationError('Number is not valid')
except ObjectDoesNotExist:
raise forms.ValidationError('OTP is not valid')
I have added def create() and def update() method in UserSerializer but still it doesn't work. Please guide me for this solution and thanks in advance.

Resources