Discord Python Bot: Clear Command If statements - python

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)

Related

How to Check if Required Argument is Missing in discord.py

I am adding a coinflip feature to my discord bot. This command has 3 arguments which is !coinflip, the side you want on the coin and the amount of money you want to gamble. This feature works fine. However, if the user writes those arguments wrong, or there are missing arguments, nothing will happen, and I will get an error in my console. How can I make the bot send a message that explains how to write the command, when a user writes the command wrong?
Here are the necessary parts of the code:
#bot.command()
async def coinflip(ctx, outcome, amount:int):
coin = random.choice(["heads", "tails"])
if outcome == coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
await ctx.send(embed=coinflipEmbed)
elif outcome != coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
await ctx.send(embed=coinflipEmbed)
You might want to create an error command below your coin_flip() command.
The following code will only accept a MissingRequiredArgument error btw.
Though you can easily change this by, removing the code block. Running the code again, typing something incorrect and find the main error. Then replace this commands.MissingRequiredArgument with commands.your_error.
#coinflip.error
async def flip_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Inccorrect arguments entered | **!command_name - outcome:str - amount:int'**)
You could:
Capture all args in *args
Validate its length
Then validate each argument individually
It would look like so:
#bot.command()
async def coinflip(ctx, *args):
# All args are here?
if len(args) != 2:
await ctx.send("Error message saying you want coin and amount")
return
# Are they valid?
outcome = args[0]
amount = args[1]
if not outcome_is_valid(outcome):
await ctx.send("Tell him its invalid and why")
return
if not amount_is_valid(outcome):
await ctx.send("Tell him its invalid and why")
return
# All good, proceed
coin = random.choice(["heads", "tails"])
if outcome == coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
await ctx.send(embed=coinflipEmbed)
elif outcome != coin:
coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
await ctx.send(embed=coinflipEmbed)

How do I choose a number out of a predefined matrix in discord.py?

I have been attempting to code a bot for a client, but as I am self-taught, sometimes the easiest aspects escape me. I know that I have known how to do this before, but I need to fix the following code:
#client.command()
async def rroulette(ctx):
await ctx.send(f"Aye, {ctx.author.mention}! Choose a number beween **1** and **6**! We all know what happens if your number is chosen, though, Comrade! ;)")
rroulette1 = await client.wait_for("Message")
await ctx.send("Alright, Comrade! Here goes nothing!")
await asyncio.sleep(2)
rroulette2 = (random.randint(1, 6))
if rroulette2 == rroulette1.content:
await ctx.send("Oops! The number was " + rroulette1.content + "! You know what that means!")
else:
await ctx.send("Ah, you are safe, Comrade! The number was not yours.")
The bot always responds with the else function, that being that your number is never chosen. I do not know how to fix this.
The overall purpose of the code is, as you probably guessed, to play Russian roulette. If your number is chosen, you get muted for 5 minutes. Any help would be greatly appreciated.
rroulette2 = (random.randint(1, 6))
if rroulette2 == int(rroulette1.content):
await ctx.send("Oops! The number was " + rroulette1.content + "! You know what that means!")
else:
await ctx.send("Ah, you are safe, Comrade! The number was not yours.")
As #Oli said, the content of rroulette1 is always a string, you need to convert it to int and this should work

How can I set a minimum amount of messages tha can be purged? discord.py

right now I am struggling to find a way to set a minimum amount of messages that can be purged. Basically I want it so whenever someone uses the command it will send an error for typing 0 or nothing for amount. I tried some things but they did not seem to work so I guess someone in here will know how to help me.
The code is this:
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, *, limit=None):
await ctx.message.delete()
channel = ctx.channel
messages = await channel.history(limit=123).flatten()
if limit != 0 or None:
if not messages:
await ctx.channel.send("I am really sorry but I can not purge an empty channel!")
return
else:
try:
await channel.purge(limit = limit)
return
except discord.Forbidden:
return await ctx.channel.send('I do not have perms')
else:
ctx.channel.send('Minimum amount of purge is 1!')
return
In the beginning I had the limit=None to limit=100 and the None in the if limit != 0 or None was not working. Now I changed it but whenever I put any number that has nothing to do with 0 or None it does not work. Any ideas why and how to fix it?
This line if limit != 0 or None: has to be if limit != 0 or limit == None:. For each comparison you need to declare what it's comparing to.
Additionally, to check if it's over a certain limit, you can just use a less-than symbol comparison. E.g. if limit < 5: return

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

discord python (bot.command with int check)

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.

Categories

Resources