How to get user input in discord.py - python

#client.command()
async def blackjack(ctx):
y= random.choice(deck)
x=random.choice(deck)
z=random.choice(deck)
a=random.choice(deck)
await ctx.send(f'{x, y}')
await ctx.send(f'{a, z}')
m = await client.wait_for("message", check=None)
if m == "Stand":
B = x+y
S = a+z
if S < B:
while S < B or S < 21:
await ctx.send(S= a+z+random.choice(deck))
if S > 21:
ctx.send("You win")
else:
ctx.send("You Lose")
else:
ctx.send("You Lose")
This is a snippet of my code where I'm trying to get user input on whether he wants to stand or draw another card. I have not yet implemented a draw feature as the stand feature does not seem to work. My deck is properly defined as numbers and.
I think the problem is in the user input as I'm not very familiar with input in discord.py
if the program would work it would wait for the user's response if they want to stand and draw cards until it has over 21 or has more than the player and print out whether the player has lost or won.
Any help would be appreciated

I think you didn't add the check you kept it NONE.
so you should do it like this:
#client.command()
async def blackjack(ctx):
y= random.choice(deck)
x=random.choice(deck)
z=random.choice(deck)
a=random.choice(deck)
await ctx.send(f'{x, y}')
await ctx.send(f'{a, z}')
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower().startswith()
msg = await client.wait_for("message", check=check)
if msg.content.lower().startswith("Stand"):
B = x+y
S = a+z
if S < B:
while S < B or S < 21:
await ctx.send(S= a+z+random.choice(deck))
if S > 21:
ctx.send("You win")
else:
ctx.send("You Lose")
else:
ctx.send("You Lose")
The startswith() is purely optional but I recommend you to add it!
You can add event time out like this:
msg = await bot.wait_for("message", check=check, timeout=<anything you want in {int}>)

Related

client.await_for unresponsive In a Loop Under Cogs Folder | Discord.py

I made a number-guessing command in Discord.py. The command works perfectly fine outside of any cogs folder (main.py). Because my main.py was getting cluttered, I relocated the guess command into one of the cog's folders where I organized my other commands. When I ran the bot and try to use the guess command, I get an error saying:
loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hooktype
Below is the code I used for the guess command inside the cog:
#commands.command()
async def guess(self, ctx):
try:
await ctx.send(f"Pick a range of numbers you want and the number of attempts you want."
f"Ex: '__**1-10**, **4**__' or '__**600-10**, **200**__'")
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await client.wait_for('message', check=check)
user_range = msg.content
num = re.findall(r'\d+', user_range) # get the values from the msg.content or user input
range_1 = int(num[0])
range_2 = int(num[1])
attempt = int(num[2])
if range_1 > range_2:
range_1 = int(num[1])
range_2 = int(num[0])
await ctx.send(
f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
Entry = 0
ran_picker = random.randrange(range_1, range_2)
while Entry <= attempt:
msg = await client.await_for('message', check=check)
Entry = Entry + 1
if msg.content == "stop" or msg.content == "Stop":
await ctx.send(f"You gave up 😢")
await ctx.send(f"The number was **{ran_picker}**")
break
elif int(msg.content) == ran_picker:
await ctx.send(f"**Good job, it was {ran_picker}!**")
break
elif int(msg.content) > range_2 or int(msg.content) < range_1:
await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
Entry = Entry - 1
print(Entry)
elif Entry == attempt:
await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
break
else:
await ctx.send(f"Nope, keep guessing", delete_after=2)
else:
await ctx.send(
f"Now guess a number between **{range_1}-{range_2}**, you have **{attempt}** attempts. Type 'stop' to give up.")
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
Entry = 0
ran_picker = random.randrange(range_1, range_2)
while Entry <= attempt:
msg = await client.await_for('message', check=check)
Entry = Entry + 1
if msg.content == "stop" or msg.content == "Stop":
await ctx.send(f"You gave up 😢")
await ctx.send(f"The number was **{ran_picker}**")
break
elif int(msg.content) == ran_picker:
await ctx.send(f"**Good job, it was {ran_picker}!**")
break
elif int(msg.content) > range_2 or int(msg.content) < range_1:
await ctx.send(f"Pick a number between **{range_1}-{range_2}**!")
Entry = Entry - 1
print(Entry)
elif Entry == attempt:
await ctx.send(f"You ran out of inputs, it was **{ran_picker}**!")
break
else:
await ctx.send(f"Nope, keep guessing", delete_after=2)
except Exception as error:
print(f"{error}")
await ctx.send(f"Problem: **[{error}]**")re
In fact, other commands that's inside a cog folder involving the function/line
msg = await client.await_for('message', check=check)
# specifically' client.await_for'
I get a similar error.
I am fairly new to Python's language and Discord.py. I tried to read some of the documents for discord.py revolving around "setup_hooktype" and try to see how I can implement it into my code. Every time I change something I get a new error saying: "unexpected keyward argument," "no attributes" and so on. I believe this function has to do with the subclass (which I have for the cog) but I'm not sure how to create an addon for "setup_hook." I could just leave this command in my main.py, but soon or later I'm going to encounter this problem again in the future.
Any help is appreciated, thanks!

How to fix "TypeError: 'Member' object is not subscriptable" discord.py

So I am creating a gambling bot and I created a slots command. This command was previously working but then for some reason stopped, here is the code:
#client.command()
async def slots(ctx, amount=None):
if amount == None:
return await ctx.send("Please enter an amount you would like to bet!")
await open_account(ctx.author)
bal = await update_bank(ctx.author)
amount = int(amount)
if amount <50:
return await ctx.send("You must bet at least $50")
else:
if amount>bal[0]:
return await ctx.send("You don't have that much money")
if amount <0:
return await ctx.send("Amount must be larger than 0")
final = []
for i in range(3):
a = random.choice(["🥞", "🍖", "🌀", "💧", "🎈", "🎄", "🎱", "🧠", "🐥"])
final.append(a)
slotsEmbed = discord.Embed(title=f"{ctx.author.name}'s slots game")
slotsEmbed.add_field(name="Your slots game", value=str(final))
await ctx.send(embed=slotsEmbed)
if final[0] == final[1] == final[2]:
await update_bank(ctx.author, 3*amount)
await ctx.send("You won all 3 slots!")
elif final[0] == final[1] or final[0] == final[2] or final[1] == final[2]:
await update_bank(ctx.author, 2*amount)
await ctx.send("You won 2 slots!")
else:
await update_bank(ctx.author, -1*amount)
await ctx.send("You didn't win any slots.")
The error occurs on line if amount>bal[0]:
This is just very odd to me because like I said this command was once working with this same exact code but for some reason it just stopped.
Here is the update_bank function:
async def update_bank(user,change = 0,mode = "Wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("mainbank.json", "w") as f:
json.dump(users, f, indent=4)
bal = [users[str(user.id)]["Wallet"],users[str(user.id)]["Bank"]]
return user
I fixed it, in the update bank function for whatever reason I had return users which doesn't make sense since I want to change the balance of the user. I ended up changing it from "return users" to "return bal" and that fixed my problem!

discord.py - Guessing game no response (updated)

The following code is supposed to run when I type $play on my discord server but nothing happens when I run it..
client = commands.Bot(command_prefix='$')
#client.command(name="play")
async def play(ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel and m.content.isdigit()
number = random.randint(1,100)
await ctx.send('I have a number in mind between 1 and 100, guess it')
for i in range(0,5):
guess = await client.wait_for("message", check=check)
if int(guess.content) > number:
await ctx.send("The number is greater")
elif int(guess.content) < number:
await ctx.send("The number is smaller")
elif int(guess.content) == number:
await ctx.send("You guessed the number!!.")
else:
return ("It has to be a positive integer between 1 to 100")
else:
await ctx.send("You lost, type $play to play again.")
It looks like your on_message event is blocking commands from working.
Add the following to your on_message event:
#client.event
async def on_message(message):
if message.author == client.user:
return
# Your next events
await client.process_commands(message) # Process commands
We added this because you have overwritten the normal on_message event.
process_commands makes sure that commands are recognized.
See the docs for more information.

How do i check if a user wrote the command?

I have this
await ctx.send("Which inventory do you want to access?")
await ctx.send("Mining, Collecting, Farming, Fishing or Fighting?")
def check(user):
if user == ctx.author:
# Idk what to do here
pass
type_check = await self.bot.wait_for('message', check=check)
if type_check.content.lower() == "mining":
await ctx.send("You chose Mining!")
if type_check.content.lower() == "collecting":
await ctx.send("You chose Collecting!")
if type_check.content.lower() == "farming":
await ctx.send("You chose Farming!")
if type_check.content.lower() == "fishing":
await ctx.send("You chose Fishing!")
if type_check.content.lower() == "fighting":
await ctx.send("You chose Fighting!")
And I need to check if a user wrote the message and if they did it would await ctx send the thing
The check func must return a boolean, also the argument passed is a discord.Message object not a user
def check(message):
if message.author == ctx.author:
return True
or
# This is a better way
def check(message):
return message.author == ctx.author
btw a better solution for those if statements is checking if they're in a list:
inv_type = type_check.content.lower()
if inv_type in ['mining', 'collecting', 'farming', 'fishing', 'fighting']:
await ctx.send(f"You chose {inv_type}!")

Bot isn't responding to my command | discord.py

So I was making a work command, and I needed some help. The bot was not responding unless I put my id into the json file instead of the bot doing it automatically. I don't get any error either. Again, it only works unless I manually put the id into the json file.
Here's the code:
youtuber = {}
def youtube():
global youtuber
try:
with open ('youtuber.json', "a") as f:
youtuber = json.load(f)
except FileNotFoundError:
print("File not found")
developer = {}
def developing():
global developer
try:
with open('developer.json', "a") as f:
developer = json.load(f)
except FileNotFoundError:
print("Error")
scientist = {}
def science():
global scientist
try:
with open('scientist.json', "a") as f:
scientist = json.load(f)
except FileNotFoundError:
print("Error")
#commands.command()
async def work(self, ctx):
await open_account(ctx.author)
#Variables
salary = 2000
id = str(ctx.author.id)
#If user is unemployed :laughard:
if id not in developer and scientist and youtuber:
await ctx.send("Your unemployed, You can work as a `developer` or a `scientist` or a `youtuber` or a `doctor`. Pick one.\n\nNote: All jobs have the same amount of salary")
message = await self.bot.wait_for('message', check = lambda: message.author == ctx.author)
#Developer
if message.content == "developer":
developer[id] = 1
with open('developer.json', 'a') as f:
json.dump(developer, f)
await ctx.send("Congratualations! You now work as a developer!")
return
#youtuber
elif message.content == "youtuber":
youtuber[id] = 1
with open('scientist.json', 'a') as f:
json.dump(scientist, f)
await ctx.send("Congratualations! You now work as a youtuber!")
return
#scientist
elif message.content == "scientist":
scientist[id] = 1
with open('youtuber.json', 'a') as f:
json.dump(youtuber, f)
await ctx.send("Congratualations! You now work as a scientist!")
return
#Dev work
elif id in developer:
dev_work = ["Type the following: `Python is the best. Everything else is trash.`", "Type the following: `Time to steal some code.`", "Answer the following question: `Which is the best bot in the world?`"]
rand_dev = random.choice(dev_work)
await ctx.send(rand_dev)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_dev == dev_work[0]:
if message.content == "Python is the best. Everything else is trash.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? You get 0 coins")
return
elif rand_dev == dev_work[1]:
if message.content == "Time to steal some code.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_dev == dev_work[2]:
if message.content == "LeBot":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("It's LeBot......")
return
#Youtube work
elif id in youtuber:
youtuber_work = ["Type the following: `I wish I had 100mil sub's like pewdiepie.`", "Type the following: `The Hair Trilogy is the best trilogy to ever exist.`", "Type the following: `Papa Franku please come back.`"]
rand_youtube = random.choice(youtuber_work)
await ctx.send(rand_dev)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_youtube == youtuber_work[0]:
if message.content == "I wish I had 100mil sub's like pewdiepie.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_youtube == youtuber_work[1]:
if message.content == "The Hair Trilogy is the best trilogy to ever exist.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_youtube == youtuber_work[2]:
if message.content == "Papa Franku please come back.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly?")
return
#scientist work
elif id in scientist:
science_work = ["Type the following: `I wonder if waterproof spray can make me walk on water.`", "Type the following: `Don't trust atoms! They make everything up!`", "Type the following: `No I'm not Elon Musk, I can't make a rocket land by itself.`"]
rand_science = random.choice(science_work)
await ctx.send(rand_science)
message = await self.bot.wait_for('message', check=lambda : message.author == ctx.author)
if rand_science == science_work[0]:
if message.content == "I wonder if waterproof spray can make me walk on water.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_science == science_work[1]:
if message.content == "Don't trust atoms! They make everything up!":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly? Dumb")
return
elif rand_science == science_work[2]:
if message.content == "No I'm not Elon Musk, I can't make a rocket land by itself.":
await ctx.send("You have earned 2000 coins!")
else:
await ctx.send("You can't even type a sentence properly?")
return
Any help will be appreciated!

Categories

Resources