#commands.command(aliases=['ckick'])
#commands.has_permissions(kick_members=True)
#commands.cooldown(1,3,BucketType.user)
async def chunkkick(self, ctx, members: commands.Greedy[discord.Member]):
if len(members) <= 1:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, you can only input 2 or more users. [-ban]", color=discord.Color.orange())
return await ctx.reply(embed=embed, mention_author=False)
if len(members) > 20:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, cannot kick more than 20 users at a time.", color=discord.Color.orange())
return await ctx.reply(embed=embed, mention_author=False)
if member.id == ctx.author.id:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, you can't kick yourself.", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
return
if member.top_role >= ctx.author.top_role:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, targets role in the hierarchy is higher than yours.", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
if ctx.me.top_role <= member.top_role:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, my role in the hierarchy lesser than targets.", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
if member.id == ctx.guild.owner:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, owner is unkickable.", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
return
else:
join_members = ", ".join(str(member.id) for member in members)
embed = discord.Embed(description="<:ocheckmark:839069223749812264> "+f"**Successfully chunk kicked {join_members}**", color=discord.Color.orange())
for member in members:
await member.kick(reason=f"{ctx.author} | User was in a chunk kick")
await ctx.reply(embed=embed, mention_author=False)
Error: local variable 'member' defined before assignment
Im trying to make a chunkban command (I rewrote my old one)
it worked before adding the if statements, I tried member = for member in members it didnt work.
You have to do all the ifs using member in a for member in members: loop. Also use elif instead of if, since you are only kicking the member if it's not the owner at the moment:
#commands.command(aliases=['ckick'])
#commands.has_permissions(kick_members=True)
#commands.cooldown(1,3,BucketType.user)
async def chunkkick(self, ctx, members: commands.Greedy[discord.Member]):
if len(members) <= 1:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, you can only input 2 or more users. [-ban]", color=discord.Color.orange())
return await ctx.reply(embed=embed, mention_author=False)
elif len(members) > 20:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Unsuccessful, cannot kick more than 20 users at a time.", color=discord.Color.orange())
return await ctx.reply(embed=embed, mention_author=False)
else:
embed = discord.Embed(description="<:oxmark:839069221207670804> "+f"Your chunkkick summary.", color=discord.Color.orange())
for member in members: # do that for every member
if member.id == ctx.author.id:
embed.add_field(name=member.display_name, value="<:oxmark:839069221207670804> "+f"Unsuccessful, you can't kick yourself.")
return
elif member.top_role >= ctx.author.top_role:
embed.add_field(name=member.display_name, value="<:oxmark:839069221207670804> "+f"Unsuccessful, targets role in the hierarchy is higher than yours.")
elif ctx.me.top_role <= member.top_role:
embed.add_field(name=member.display_name, value="<:oxmark:839069221207670804> "+f"Unsuccessful, my role in the hierarchy lesser than targets.")
elif member.id == ctx.guild.owner:
embed.add_field(name=member.display_name, value="<:oxmark:839069221207670804> "+f"Unsuccessful, owner is unkickable.")
return
else:
await member.kick(reason=f"{ctx.author} | User was in a chunk kick")
await ctx.reply(embed=embed, mention_author=False)
I also changed it to only send one embed, and not one embed per user.
Related
I'm trying to make a command that takes a channel name as input (or argument) and locks that channel but for only the students in the channel. Here's the code:
# bot.GUILD = bot.get_channel(guild_id) [In on_ready method in bot class]
#bot.command()
async def lock(ctx, channel_name):
user_dm = await bot.create_dm(ctx.author)
channels = await bot.GUILD.fetch_channels()
roles = await bot.GUILD.fetch_roles()
channels = list(filter(lambda c: c.name.lower() == channel_name.lower(), channels))
student_roles = list(filter(lambda r: r.name.endswith("students"), roles))
# print(channels, roles) [This works fine]
if channels:
for channel in channels:
for role in student_roles:
await channel.set_permissions(role, send_messages=False)
await user_dm.send(f"✅ {channel_name} has been locked!")
else:
await user_dm.send(f"❌ {channel_name} does not exist!")
I don't know why it's not sending any message to my dm. Because it's an if-else statement so at least I get a message from the bot whether positive or negative but that doesn't happen. And yes my bot has the necessary permissions. I really hope you can help me with this 😕🥺
I'm attempting checks if a username is in a valid username in the server. The check is done by the following code
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!logan',
intents=intents,
helpCommand=helpCommand)
Users = [# Need help getting users]
async def Fight(ctx, User):
if ctx.author.name != User:
if User in Users:
open_file = open(str(ctx.author.name), "w")
open_file.write(User + "\n300\nTurn")
open_file.close()
open_file = open(User, "w")
open_file.write(str(ctx.author.name) + "\n300\nNot")
open_file.close()
await ctx.author.send("You are now fighting " + User)
#await ctx.User.send("You are now fighting " + ctx.author.name)
else:
await ctx.send("User is not in this server")
else:
await ctx.send("You Cannot Fight Yourself")
I've tried googling, but I haven't found a valid answer
There are other ways to get your guild name, but here's a possible method to get it and get the member list from it.
In member (and user so), there is the ".bot" that is a boolean, 0 if not a bot.
listMembers = []
#bot.command(name="init")
async def FuncInit (ctx) :
global listMembers
guilde = ctx.message.guild
for member in guilde.members :
if not member.bot :
listMembers.append(member.name)
I'm trying to make an embed system that asks multiple questions and then put them together and send the embed with all the info given, but I can't figure out how to get multiple inputs in one command.
Based on what I understand from your question, you're only checking for one possible input with m.content == "hello". You can either remove it or add an in statement. Do view the revised code below.
#commands.command()
async def greet(ctx):
await ctx.send("Say hello!")
def check(m):
return m.channel == channel # only check the channel
# alternatively,
# return m.content.lower() in ["hello", "hey", "hi"] and m.channel == channel
msg = await bot.wait_for("message", check=check)
await ctx.send(f"Hello {msg.author}!")
In the case of the newly edited question, you can access the discord.Message class from the msg variable. For example, you can access the message.content. Do view the code snippet below.
#commands.command()
async def test(ctx):
def check(m):
return m.channel == ctx.channel and m.author == ctx.author
# return message if sent in current channel and author is command author
em = discord.Embed()
await ctx.send("Title:")
msg = await bot.wait_for("message",check=check)
em.title = msg.content
# in this case, you can continue to use the same check function
await ctx.send("Description:")
msg = await bot.wait_for("message",check=check)
em.description = msg.content
await ctx.send(embed=em)
I wanted to create a clear command where if example .clear #user#0000 100 it will clear the last 100 messages #user#0000 sent. Here is my code:
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount=1):
await ctx.channel.purge(limit=amount + 1)
#clear.error
async def clear_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('Sorry, you are missing the ``MANAGE_MESSAGES`` permission to use this command.')
This code i provided only deletes depeneding how many messages will be deleted in a channel. I want to make a code where the bot will delete messages from a specific user. If this is possible, please let me know. I will use the code as future reference. Much appreciated.
You can use check kwarg to purge messages from specific user:
from typing import Optional
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, member: Optional[discord.Member], amount: int = 1):
def _check(message):
if member is None:
return True
else:
if message.author != member:
return False
_check.count += 1
return _check.count <= amount
_check.count = 0
await ctx.channel.purge(limit=amount + 1 if member is None else 1000, check=_check)
Is there a way too do a callback or a background task to see when a user joins and leaves a voicechannel? Currently when I cmd the bot I only am able to see the users that are currently in the voicechannel only. Sorry if it might not make sense.
import asyncio
import config
client = discord.Client()
#client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#Voice channel
lobby_voicechannel = client.get_channel(708339994871463986)
#Text channel
txt_channel = client.get_channel(702908501533655203)
team_one = []
team_two = []
member_id = []
lobby_queue = lobby_voicechannel.members
for x in lobby_queue:
#change mention to name or nick for variations
member_id.append(x.mention)
player_num = len(member_id)
joined_user = str(member_id)
#check how many players in total for queue
if player_num == 5:
user_convert = tuple(member_id)
embed = discord.Embed(
title="**{}/10** players joined `{}`".format(player_num, lobby_voicechannel),
description="\n".join(user_convert),
color=0x00f2ff)
await txt_channel.send(delete_after=None, embed=embed)
else:
if player_num == 0:
embed = discord.Embed(
title="**{}/10** players joined `{}`".format(player_num, lobby_voicechannel),
description=f"***```No players in {lobby_voicechannel}```***",
color=0x00f2ff
)
await txt_channel.send(delete_after=None, embed=embed)
client.run(config.Token)```
You can use the on_voice_state_update event. This event gets triggered whenever a member joins/leaves or when a members state changes in a voice channel. For more info see link.
However you still need to check whether or not the member left/joined. This can be done through the before and after VoiceState objects received from the event: on_voice_state_update(member, before, after):.
Example:
#commands.Cog.listener()
async def on_voice_state_update(member, before, after):
if before.channel == None and after.channel != None:
state = 'joined'
else if before.channel != None and after.channel == None:
state = 'left'
else:
state = 'unchanged'
# Continue with some code