generating a random number - python

I am trying to build up discord bot through pip discord.py. After command !random I want to ask user for any number and bot will then generate random number between 0 and entered number. It doesn't rly work for me and because i don't know much things about discord.py, I ask there :)
code:
import random
elif message.content.startswith("!random"):
await client.send_message(message.channel, "Enter a number: ")
num = await client.wait_for_message(int)
numm = int(num)
randomnum = random.randint(0, numm)
await client.send_message(message.channel, randomnum)

Try this:
import random
elif message.content.startswith("!random"):
await client.send_message(message.channel, "Enter a number: ")
def check(msg):
return msg.content
reaction.content = await client.wait_for_message(author=message.author, check=check)
numm = int(reaction)
randomnum = random.randint(0, numm)
await client.send_message(message.channel, randomnum)
You should also check if the reaction is a int
(added squaswin's reaction. note that the code is not tested)

Related

how to make client.wait_for look at one person

im making a guessing game and im trying to use the client.wait_for function for it but the problem is this function looks at all the messages being sent after you have run it but I want it to only look at one person's messages. I also tried this:
if guess.author != user: return
which did work, it would stop the code if someone else talked when you are using the bot but if someone speaks on another server when you are using the bot it will still be stopped.
if it could only read one person's messages it would be nice.
my full code:
user=message.author
number = random.randint(1, 100)
await message.channel.send('I have a number in mind between 1 and 100, you have 7 guesses, guess.')
for guesses in range(0, 7):
guess = await client.wait_for('message')
if guess.author !=user:
await message.channel.send("sorry game ended cus someone talked mid game.(this can happen if people talk even if not in this sever)")
return
if int(guess.content) < number:
if guesses == 6:
await message.channel.send("Too many guesses, try again.")
await message.channel.send("The number I was thinking of was " + str(number) + ".")
break
else:
await message.channel.send("Higher!")
elif int(guess.content) > number:
if guesses == 6:
await message.channel.send("Too many guesses, try again.")
await message.channel.send("The number I was thinking of was " + str(number) + ".")
break
else:
await message.channel.send("Lower!")
else:
await message.channel.send("You got it! You guessed " + str(guesses + 1) + " times.")
break
You can pass a check to your wait_for like this:
guess = await client.wait_for("message", check=lambda message: message.author.id == user_id)
Using a custom check allows you to actually use custom checks, you can use any method returning a bool, that way you can even use things unrelated to the bot itself, python is the limit.
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await self.client.wait_for("message", check=check)

discord.py adding mentioned users to list

I want to make disposable register system by using list which makes adding the discord user to list when you mentioned it but when i try to get user input from message it fails
#bot.command()
async def gameset(ctx,playernum:int):
if playernum <= 10:
await ctx.send('player 1 "<assign #player" mention yourself like this!')
else:
await ctx.send('maximum 10 player!')
num = 1
while num < playernum:
playerlist = []
#bot.command()
async def assign(user):
if user == discord.User.mentioned_in(message=user):
listadd = user
playerlist.append(listadd)
await user.send(f"player {num + 1} mention yourself!")
elif user != discord.User:
await user.send("not user")
else:
await user.send("go fix it dumb")
if playerlist[num - 1] == discord.User:
num = num + 1
else:
await gameset.send("problem with the listing")
also i think this is not the only problem i tried like this too but then my mention/user percaption logic failed i think
#bot.command()
async def ata(user : discord.User):
if not user:
await user.send("go fix it dumb")
else:
listadd = user
playerlist.append(listadd)
await user.send(f"player {num + 1} mention yourself!")
I've tried with #bot.event but i made more progress with #bot.command so if this is able to do with #bot.event i would be pleased if you guys help me understand how can i do with event but command is sufficient too.
Edit: I tried using wait_for() command like this:
num = 1
while num < playernum:
playerlist = []
def check(msg2 : discord.member):
return msg2 == discord.mentions
msg2 = await bot.wait_for("message", check=check)
# player = await bot.fetch_member(msg2.id)
if msg2 == discord.member:
player = str(msg2.id)
listadd = player
playerlist.append(listadd)
await ctx.send(f"player {num + 1} mention yourself!")
num = num + 1
else:
await msg2.send("go fix it dumb")
and i think it worked but now i have another problem which is
discord.ext.commands.errors.CommandNotFound: Command "#!id>" is not found
i get this when i try to mention someone

Making a guessing game in discord.py

I have been trying to make a discord bot which starts a game when !play message is sent. In the game there is a variable whose value is chosen randomly and if you predict the right number (between 1 and 10) then a "You win" message will be sent and if the it is greater or less then a message will be sent accordingly. I know I am messing it because I am using discord.py for the first time.
My code:
if message.content.startswith("!play"):
await message.channel.send("Choose a number between 1-10. Enter numerical values only.")
num = random.randint(1,10)
try:
if message.content.startswith(str(num)):
await message.channel.send("You won.")
elif int(message.content) > num:
await message.channel.send("Go a bit lower.")
elif int(message.content) < num:
await message.channel.send("Go a bit up.")
except Exception as e:
await message.channel.send("Check inputs.")
Please help
Here:
# imports the discord module and the random module.
import discord
from discord.ext import commands
import random
client = discord.Client()
client = commands.Bot(command_prefix = "!")
Token = "" #your token
#client.event
async def on_message(message):
if message.content.startswith("!play"): #the play command to start the guessing game.
channel = message.channel
await channel.send("Choose a number between 1-10. Enter numerical values only.") #message that tells about the start of the game
# generates a random number and turns it into a string
number1 = random.randint(1,10)
number2 = str(number1)
def check(m):
return m.content == number2 and m.channel == channel
"""
The check function, first it checks if the message is the correct number.
Then it checks if the channel is the same channel as the channel that the play command was sent in.
If both is true, then it returns true. Else it returns false.
"""
msg = await client.wait_for('message', check=check) #waits for the check function to return true
await channel.send("Correct answer {.author}" .format(msg)) #sends the correct answer message
client.run(Token)
This should work.
I have a working bot here: https://discord.com/api/oauth2/authorize?client_id=793152585346711573&permissions=8&scope=bot
Example: https://i.stack.imgur.com/ou60F.png

Is there a way to have a bot respond to a one of three messages, each with their own responses to a set of messages?

I have an excuse generator and decided to transfer it over to a bot. From what I have seen the command is a branching path. It asks, you respond, and then it asks again based on your previous answer.
The problem is the QuestionOneOne = int(input()), QuestionOneTwo = int(input()), and QuestionOneThree = int(input()). I understand what they do but not how to make it work on Discord where the questions are asked like how those 3 lines look for the response in the command prompt.
TL;DR: int(input()) makes the bot look for response in command prompt. I don't know how to make it look in chat.
Here's the code that is the issue. The bit after it would work ok if this part is fixed.
#client.command()
async def yote(ctx):
await ctx.send("Welcome to the EXCUSE GENERATOR")
await ctx.send("This is a generator that creates a random EXCUSE for you")
await ctx.send("What do you need an excuse for?")
await ctx.send("1: I forgot")
await ctx.send("2: I lost")
await ctx.send("3: I didn't do")
QuestionOne = int(input())
if QuestionOne == 1:
await ctx.send("What did you forget?")
await ctx.send("1: Homework")
await ctx.send("2: An object")
await ctx.send("3: A concept")
QuestionOneOne = int(input())
elif QuestionOne == 2:
await ctx.send("What did you lose?")
await ctx.send("1: Something expensive")
await ctx.send("2: Something cheap")
await ctx.send("3: Someone")
QuestionOneTwo = int(input())
elif QuestionOne == 3:
await ctx.send("What didn't you do?")
await ctx.send("1: Your homework")
await ctx.send("2: An errand")
await ctx.send("3: Something important")
QuestionOneThree = int(input())
Thing = str(input())
You should use the Client.wait_for / Bot.wait_for method and specify "message" for the event.
You'll want to add a check as well, e.g. for the channel or author, integer input, etc.

discord.py rewrite | How would I make this into an integer?

I am trying to make a command which activates a random number guesser game. Obviously, I am stuck in the first few lines. I have written what I THINK will work, however it may be blatantly wrong. I want it to change the message on the discord server to an int, so it will work in my if statement.
It's my first time making a bot in with discord.py, so I am running into many obstacles. I am not fully sure what the error is telling me, so I haven't been able to try any fixes. This is the code:
async def numgame(context):
number = random.randint(1,100)
for guess in range(0,5):
await context.send('Pick a number between 1 and 100')
Message = await client.wait_for('message')
Message = int(Message)
if Message.cleant_content > number:
await context.send(guess + ' guesses left...')
asyncio.sleep(1)
await context.send('Try going lower')
asyncio.sleep(1)
elif Message.clean_content < number:
await context.send(guess + ' guesses left...')
asyncio.sleep(1)
await context.send('Try going higher')
asyncio.sleep(1)
else:
await context.send('You guessed it! Good job!')
if number != Message:
await context.send('Tough luck!')
Whenever I do the command in my discord server, my shell gives me this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Message'
I am not too sure what it is telling me. As stated, I would like "Message" to be an integer, but I get the error. but help would be appreciated!
[still a beginner, don't be too harsh :(]
wait_for('message') returns a Message object, which int doesn't know how to handle yet. You need to convert Message.content to an int instead. Just below is your code with some other changes:
def check(message):
try:
int(message.content)
return True
except ValueError:
return False
#bot.command()
async def numgame(context):
number = random.randint(1,100)
for guess in range(0,5):
await context.send('Pick a number between 1 and 100')
msg = await client.wait_for('message', check=check)
attempt = int(msg.content)
if attempt > number:
await context.send(str(guess) + ' guesses left...')
await asyncio.sleep(1)
await context.send('Try going lower')
await asyncio.sleep(1)
elif attempt < number:
await context.send(str(guess) + ' guesses left...')
await asyncio.sleep(1)
await context.send('Try going higher')
await asyncio.sleep(1)
else:
await context.send('You guessed it! Good job!')
break
else:
await context.send("You didn't get it")

Categories

Resources