-1

I'm making a dice roller bot for Discord and basically I want to make possible to someone choose what they want to do. If they want to add 6 with the dice result, if they want to half the dice result and things like that. I made the code, and it can sum, but can't do other operations.

@client.command(aliases=['r', 'dado', 'dice'])
 async def roll(ctx, numero=20, conta='+', ficha=0):
     rolagem = random.randint(1,int(numero))
     total = (int(rolagem) + int(ficha))
     await ctx.send(f'{ctx.author.mention}  \n**Resultado**: D{numero} ({rolagem}) {conta} {ficha}\n**Total**: {total}')

Thats the code. In the total part, I want to use what they choose in the conta. Is there any way to do it? I already tried a lot, but nothing worked.

Ivonet
  • 2,492
  • 2
  • 15
  • 28

3 Answers3

0

If I correctly understand your code then you are using total to represent the users transformation. This could be achieved with a match case statement.

match conta:
    case '+':
        total = rolagem + int(ficha)
    case '*':
        total = rolagem * int(ficha)
    etc. for other operators
charlie scott
  • 136
  • 1
  • 9
  • `match`/`case` is new in python 3.10, which is not yet released. – Łukasz Kwieciński May 23 '21 at 16:58
  • Ty, helped me a lot! I'll use this in future updates. – 日本Jorge May 23 '21 at 17:01
  • For a current solution [this post](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) has some options. elifs are probably fine here but can become unwieldy and are harder to maintain if a variables name changes for some reason – charlie scott May 23 '21 at 17:09
0

This effect can be achived using eval() like this:

@client.command(aliases=["r", "dado", "dice"])
async def roll(ctx, numero=20, conta="+6"):
    rolagem = random.randint(1, int(numero))
    total = eval(f"{rolagem}{conta}")
    await ctx.send(
        f"{ctx.author.mention}  \n**Resultado**: D{numero} ({rolagem}) {conta}\n**Total**: {total}"
    )

by using this method you can even do some complicated math with your rolled number. If you are afraid of code injection you can make a list of allowed characters and check if the conta contains something out of this list.

loloToster
  • 1,395
  • 3
  • 5
  • 19
0

Instead of using eval(), you can use a if-elif-else conditional blocks.

@client.command(aliases=['r', 'dado', 'dice'])
 async def roll(ctx, numero=20, conta='+', ficha=0):
     rolagem = random.randint(1,int(numero))
     if conta == '+':
         total = (int(rolagem) + int(ficha))
     elif conta == '-':
         total = (int(rolagem) + int(ficha))
     # keep on adding as needed
     await ctx.send(f'{ctx.author.mention}  \n**Resultado**: D{numero} ({rolagem}) {conta} {ficha}\n**Total**: {total}')

12944qwerty
  • 2,001
  • 1
  • 10
  • 30