import discord
from discord.ext import commands
from discord.utils import get
from discord.ext.commands import bot
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.event
async def on_ready():
print("The 'Superbot' is now online.")
#bot.command()
async def clear(ctx, amount):
amount = int(amount)
if amount == int:
await ctx.channel.purge(limit=amount)
elif amount != int:
return await ctx.send("!Clear [Integer]")
bot.run('removed')`
EnyoS:
!clear dfk
Superbot:
The Command raised an exception: ValueError: invalid literal for int() with base 10: 'dfk'
EnyoS:
!clear 10
Superbot:
!Clear [Integer]
I want to make it return !Clear [Integer] and when I write a number it just works, thanks ahead!
Try and Except ValueError. The format for this is: Try: amount = int(amount) Except ValueError: await ctx.send("!Clear [Integer]") This removes the need for the if statement too. The indentation doesn't quite come across well, but this will help: https://www.w3schools.com/python/python_try_except.asp
You're gonna want to check if the argument passed can be cast to an int.
#bot.command()
async def clear(ctx, amount):
try:
amount = int(amount)
return await ctx.channel.purge(limit=amount)
except ValueError:
return await ctx.send("!Clear [Integer]")
but that's not what I am aking, I am trying to make the (amount) as an int so u can't cuz even when u write an number it still counts that as a sting
I'm not 100% sure what you mean with this, but I think my answer does what you need. This way, when you pass in a number, which will indeed be a string, it will try to cast it to an int to see if it's an actual number (and not some random text). Going off of your error message, which sends the command usage, this is what you want.
Related
I want to make it that when someone does /AFK and writes letters instead of numbers, it should show something like "input numbers not letters". Here is my code:
async def afk(ctx, mins : int):
current_nick = ctx.author.nick
await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.", delete_after=5)
await ctx.author.edit(nick=f"[AFK]{ctx.author.name}")
counter = 0
while counter <= int(mins):
counter += 1
await asyncio.sleep(60)
if counter == int(mins):
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
break```
You need to remove the typehint and then use try/except
async def afk(ctx, mins):
try:
mins = int(mins)
except ValueError:
return await ctx.send("input numbers not letters")
# your other code
Try this:
async def afk(ctx, mins : int):
try:
mins = int(mins)
except ValueError:
# ...
# <send the message here.>
# ...
return
current_nick = ctx.author.nick
await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.", delete_after=5)
await ctx.author.edit(nick=f"[AFK]{ctx.author.name}")
asyncio.sleep(60 * mins)
await ctx.author.edit(nick=current_nick)
await ctx.send(f"{ctx.author.mention} is no longer AFK", delete_after=5)
Here, we try to convert mins to an int, and if it fails, send the message. Otherwise, continue as usual. I think you can also remove the while loop and if statement like I did here.
Generally I agree with #Poojan's answer, but there's a much simpler way than try/except:
async def afk(ctx, mins):
if not mins.isdigit():
return await ctx.send("input numbers not letters")
mins = int(mins)
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
Here is the code
import discord
from discord.ext import commands
class roll(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def roll(self, ctx, output):
count, size = output.split("d")
size = int(size)
count = int(count)
counter = 0
rolltotal = 0
while counter < count:
result = randint(1, size)
rolltotal += result
counter += 1
eject = "You rolled {} on a {}!".format(rolltotal, output)
await ctx.send(eject)
#roll.error
async def roll_error(self, ctx, error):
if isinstance (error, commands.MissingRequiredArgument):
await ctx.send(f'{ctx.author.mention}, please specify the size of the dice and ho many dice you\'re rolling EX: 1d20')
await ctx.message.delete()
print(f'{ctx.author.name} tried to roll dnd dice but didn\'t specify an argument in {ctx.guild.name}')
elif isinstance (error, commands.BadArgument):
await ctx.send(f'{ctx.author.mention}, please specify the size of the dice and ho many dice you\'re rolling EX: 1d20')
await ctx.message.delete()
print(f'{ctx.author.name} tried to roll dnd dice but gave a bad argument in {ctx.guild.name}')
def setup(bot):
bot.add_cog(roll(bot))
I cant figure out what is wrong with this cog I have other cogs that send messages fine but this one dosent for some reason
In the command decorator, set the name of the command: #commands.command(name="roll")
I did not import random and my ide was jut not showing that there was an error so time for a new ide
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")
I am currently tying to make a discord bot in python. It has been about 1 week since I started learning and I thought I would give this a go. I am trying to make a clear function to have it clear the chat. I want to make the bot say "please enter a valid number". If you type anything else other than an int ex. some char.
For example when I put ".clear t" it wont do anything and it gets angry in the terminal. When I put a valid argument such as ".clear 3" it will throw up the "please enter a valid number." after clearing all of it.
I tried different variations of the if statement including placement. Can't figure it out. I have a feeling it be something about where to place the if statement. Thank you for taking the time to read.
#client.command(pass_context = True)
async def clear(ctx, number = 5):
number = int(number)
counter = 0
channel = ctx.message.channel
async for x in client.logs_from(ctx.message.channel, limit = number):
if counter < number:
await client.delete_message(x)
counter += 1
await asyncio.sleep(0.5)
if number != int():
await client.send_message(channel, "Please enter a valid number.")
You need to learn how to properly check an object's type. In your case, if number = 5, and you do if number != int():, since int() returns 0, you're basically saying if 5 != 0:, which is always.
To overcome the aforementioned, useisinstance(obj, type). However, it doesn't matter since number will always be a string (unless the default value is used).
Having the following line will raise an error if number cannot be converted into an integer.
number = int(number)
Which raises a ValueError, you need to catch that in order to send your error message.
#client.command(pass_context=True)
async def clear(ctx, number=5):
channel = ctx.message.channel
try:
number = int(number)
except ValueError:
return await client.send_message(channel, "Please enter a valid number.")
async for x in client.logs_from(channel, limit=number):
await client.delete_message(x)
await asyncio.sleep(0.5)
With discord.py however, there's an easier way to do type conversations, by using the type annotation syntax:
#client.command(pass_context=True)
async def clear(ctx, number: int=5):
channel = ctx.message.channel
async for x in client.logs_from(channel, limit=number):
await client.delete_message(x)
await asyncio.sleep(0.5)
If you desperately need to send that error message to the channel, you can do it from the on_command_error event. (Search their documentation)
You might've noticed that I removed the counter part, since limit does exactly the same thing. (Removed redundancy)