How do I get a list of all members in a discord server, preferably those who aren't bot - discord

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)

Related

get more input from one command (discord.py)

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)

Delete messages from specifc user using Discord py

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)

Problems with a discord.py bot

I have been trying to code a Discord bot for my own server.
However, it seems like, whenever I add more commands to the code, the ban, and kick functions no longer work correctly.
I've tried rewriting the code multiple times, but it did not work.
I've tried rearranging the codes, and that did not work as well.
client = commands.Bot(command_prefix = '!')
#client.command()
async def kick(ctx, member : discord.Member, *, reason = None):
await member.kick(reason = reason)
#client.command()
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
curseWord = ['die', 'kys', 'are you dumb', 'stfu', 'fuck you', 'nobody cares', 'do i care', 'bro shut up']
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
#ready
#client.event
async def on_ready():
print('LOGGED IN as mr MF {0.user}'.format(client))
#client.event
#detect self messages
async def on_message(message):
if message.author == client.user:
return
#greeting
if message.content.startswith('hello'):
await message.channel.send('ay whatup ma gamer')
#help
if message.content.startswith('!therapy'):
quote = get_quote()
await message.channel.send(quote)
#toxicity begone
msg_content = message.content.lower()
if any(word in msg_content for word in curseWord):
await message.delete()
#environment token
token = os.environ['token']
client.run(token)
You have overwritten the on_message event, which by default processes commands (those marked with the #client.command() decorator). You need to explicitly tell the library to process commands when you overwrite it. As noted in the discord.py documentation, you should add this line at the end of the on_message event:
await client.process_commands(message)

How to get how many messages has been sent by a user

How to get how many messages have been sent by a user, I tried doing it myself but it didn't work out for me can anyone help me.
This is what I came up with:
#client.command(aliases =["m"])
async def messages(ctx, Discord.user=User):
counter = 0
async for message in channel.history():
if message.author == client.user:
counter += 1
await ctx.send(f'{ctx.author.mention} sent {counter} messages.')
Your user parameter is not valid. = indicates default, what you want to use are type hints which are indicated with a :. This is the correct way to pass your user parameter: user: discord.Member.
#client.command(aliases=["m"])
async def messages(ctx, user: discord.Member):
channel = ctx.message.channel
counter = 0
async for message in channel.history():
if message.author == user:
counter += 1
await ctx.send(f'{ctx.author.mention} sent {counter} messages.')

How would i get live updates when a user joins and leaves a discord voice channel

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

Resources