Home > Enterprise >  making a discord bot function to print the sqrt of a number
making a discord bot function to print the sqrt of a number

Time:02-28

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.

CodePudding user response:

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.

CodePudding user response:

Try this:

    if msg.startswith("!sqrt"):
        number = int(msg.lstrip("!sqrt"))
        try:
            # return str(math.sqrt(number))
        except:
            # return "This is an error message"

  • Related