How to convert user object to name - discord

Currently the output of the user is Team_<#378014902620520451>. How do i convert this to a username of the player?
team_one_capatain = []
team_two_capatain = []
team_one_capatain.append(random.choice(queue))
team_two_capatain.append(random.choice(queue))
for captain_one in team_one_capatain:
for captain_two in team_two_capatain:
""" queue.remove(team_one_capatain)
queue.remove(team_two_capatain) """
embed = discord.Embed(color=discord.Color.teal())
embed.add_field(name=f'Team_{captain_one}', value=None, inline=True)
embed.add_field(name='PLAYERS', value=',\n'.join(queue), inline=True)
embed.add_field(name=f'Team_{captain_two}', value=None, inline=True)
embed_message = await ready_channel.send(embed=embed)
for i in range(0, len(queue)):
await embed_message.add_reaction(emoji_numbers[i])

If captain_one is of type discord.User or discord.Member, you can use captain_one.display_name. The documentation explains the display_name attribute:
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
(source)
Other attributes you might be interested in:
discord.User.name (same for discord.Member)
discord.User.discriminator (same for discord.Member)
discord.Member.nick

Related

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

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)

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)

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 can I change the order of correct answers or accept more than just one global answer?

I am still working on my question bot and now I want you to be able to give multiple correct_answers. Here is what I had in mind: Each user can execute a command 3x to give an answer. But to each question I want a different solution to be considered correct, so not always just A, as an example. How can I make the bot consider the following answers as correct in the order: A, B, A or A, B, C etc.
At the moment I have the following code:
correct_answers = "A" #Only possibility
#commands.command()
async def answer(self, ctx, answer):
self.answer.enabled = False
global correct_answers
if correct_answers != answer:
await ctx.author.send(f "You guessed {answer} which is **wrong**. Good luck next time!")
await ctx.message.delete()
return
[shortened]
await ctx.message.delete()
await ctx.author.send(f'The right answer was **{correct_answers}**, you guessed **correctly**!')
await asyncio.sleep(10)
self.answer.enabled = True
My embed code where I want to decide after which edit which answer is correct:
#commands.command()
async def trivia_c(self, ctx):
e = discord.Embed(color=discord.Color.gold())
e.title = "New question, new luck."
e.description = "**When was Steve Jobs born?**"
e.add_field(name="1️⃣", value="02/24/1955", inline=False)
e.add_field(name="2️⃣", value="03/24/1955", inline=False)
e.add_field(name="3️⃣", value="02/24/1965", inline=False)
e.set_footer(text="You have x-x to answer this question.", icon_url=self.bot.user.avatar_url)
e.timestamp = datetime.datetime.utcnow()
question = await ctx.send(embed=e)
await asyncio.sleep(10)
e2 = discord.Embed(color=discord.Color.gold())
e2.title = "New question, new luck."
e2.description = "Test1"
e2.add_field(name="1️⃣", value="02/24/1955")
e2.add_field(name="2️⃣", value="03/24/1955")
e2.add_field(name="3️⃣", value="02/24/1965")
e2.set_footer(text="You have x-x to answer this question.")
e2.timestamp = datetime.datetime.utcnow()
await question.edit(embed=e2)
await asyncio.sleep(10)
e3 = discord.Embed(color=discord.Color.gold())
e3.title = "Test2"
e3.description = "When was Steve Jobs born?"
e3.add_field(name="1️⃣", value="02/24/1955")
e3.add_field(name="2️⃣", value="03/24/1955")
e3.add_field(name="3️⃣", value="02/24/1965")
e3.set_footer(text="You have x-x to answer this question.")
e3.timestamp = datetime.datetime.utcnow()
await question.edit(embed=e3)
await asyncio.sleep(10)
My approach would have been to do it via an enumeration, i.e.
first, second, third = "A", "B", "A" or correct_answers = ["A", "B", "B"] but in both cases it doesn't work. Would I have to go through a list and how exactly do I do that? I also read that you can get the results via an index, but then it fails for me.
In summary:
The first execution of the command should recognize A as correct, then the second time for example B, and the third time for example C.
Using the embed code provided I have used wait_for like my previous example. Still reduces the need for a second command. If you wanted you would have to implement a storage system. I have done the first command as an example. If you wanted to set a limit you can use timeout=seconds in the wait_or
#commands.command()
async def trivia_c(self, ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel
e = discord.Embed(color=discord.Color.gold())
e.title = "New question, new luck."
e.description = "**When was Steve Jobs born?**"
e.add_field(name="1️⃣", value="02/24/1955", inline=False)
e.add_field(name="2️⃣", value="03/24/1955", inline=False)
e.add_field(name="3️⃣", value="02/24/1965", inline=False)
e.set_footer(text="You have x-x to answer this question.", icon_url=self.bot.user.avatar_url)
e.timestamp = datetime.datetime.utcnow()
question = await ctx.send(embed=e)
try:
reply = await client.wait_for('message', check=check)
if reply.content == "a":
print("Good")
else:
print("bad")
await reply.delete()
except:
return await question.edit(content="You took too long, so the question is gone.")
await asyncio.sleep(10)
# Next
import random
#commands.command()
async def question(self, ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel
question_one = "How many lives do cat's have?"
answers_one = {"9":"a","1":"b","10":"c"}
questions = {question_one:{"9":answers_one}, "Pineapple on pizza?":{"yes":{"yes":"a",
"no":"b"}}}
# get a question
question = random.choice(list(questions.keys()))
data = questions.get(question)
correct_answer = list(data.keys())[0]
answers = list(list(data.values())[0].items())
question_msg = ""
answers_msg = ""
numbers_list = []
answers_list = []
for answer, number in answers:
numbers_list.append(number)
answers_list.append(answer)
while numbers_list != []:
num = random.choice(numbers_list)
ans = random.choice(answers_list)
answers_msg += f"{num}. {ans}\n"
answers_list.remove(ans)
numbers_list.remove(num)
question_msg = f"{question}\nPlease pick one of the following:\n{answers_msg}"
question_sent = await ctx.send(question_msg)
try:
reply = await client.wait_for('message', check=check)
except:
return await question_sent.edit(content="You took too long, so the question is gone.")
await reply.delete()
if reply.content == correct_answer:
await ctx.send("Well done!")
else:
await ctx.send("Nope. How can you get confused!")
This uses wait_for which means you can share the data and not need multiple commands.
This supports the use of multiple questions.
During testing I got:
How many lives do cat's have?
Please pick one of the following:
c. 1
b. 10
a. 9
How many lives do cat's have?
Please pick one of the following:
a. 10
b. 9
c. 1

Bot saying only one word in string

As in title. I'm trying to get my bot to send an announcement, without having to use "" to capture the whole sentence. What the hell do you mean?
Here's my code:
#bot.command(pass_context=True)
#discord.ext.commands.has_permissions(administrator=True)
async def announce(ctx, message : str):
if message == None:
return
else:
embed = discord.Embed(title='yBot | ANNOUNCEMENT', description='', color= 0xFF0000)
embed.add_field(name="ANNOUNCEMENT: ", value="{}".format(message))
embed.set_footer(text="© 2020 - Powered by yanuu ;k#2137")
await ctx.send("||#everyone||")
await ctx.send(embed=embed)
Your issue is in the way you defined the command it self. It should be with a * so that it will take everything after
async def announce(ctx,*, message : str):
Have a look at this doc

Resources