'making a discord bot function to print the sqrt of a number
I'm trying to make a discord bot command that replies with the square root of a number if the message is "!sqrt (number)" but I can't figure out how to do that. My code looks like this
import discord
import math
client = discord.Client()
async def on_message(message:discord.message.Message):
if message.author == client.user:
return
msg = str(message.content).lower()
I know I have to write if msg.startswith('!sqrt') and use math.sqrt(number) but I can't figure out how to extract that number from the message or how to pass that in the if condition.
Solution 1:[1]
You're better off using the commands extension in discord.py.
Your code will then look something like this:
from discord.ext.commands import Bot
import math
bot = Bot(command_prefix='!')
@bot.command()
async def sqrt(ctx, number: int):
try:
result = str(math.sqrt(number))
except:
result = "An error occurred"
await ctx.send(result)
bot.run(TOKEN)
All the message.startswith fuss is dealt with for you, as is converting the argument to the required type.
Solution 2:[2]
Try this:
if msg.startswith("!sqrt"):
number = int(msg.lstrip("!sqrt"))
try:
# return str(math.sqrt(number))
except:
# return "This is an error message"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RoadieRich |
| Solution 2 | Froggo |
