簡體   English   中英

如何在 discord.py 中制作骰子機器人

[英]How make a dice bot in discord.py

我正在嘗試為我的 discord 機器人創建一個擲骰子的命令,但我想不出一種方法讓這個命令讓我為擲骰添加一個值。 示例:3d20+8

@bot.command()
  async def d(ctx,number):
      variable=random.randint(1,int(number)) 
      await ctx.reply(f"` {variable} ` ⟵ [{variable}] 1d{numero}")

有誰知道我將如何做到這一點?

你可以這樣做。

為了便於閱讀,我制作了第一個dice function 解壓輸入(因為它的格式XdY+Z )。 然后它轉到第二個 function _dice進行所有處理。

@client.command()
async def dice(ctx, *, text: str):
    count, _, text = text.partition('d')  # eg "12d34+56" -> "12", "d", "34+56"
    size, _, offset = text.partition('+')  # eg "34+56" -> "34", "+", "56"
    try:
        count = int(count)
        size = int(size)
        offset = int(offset)
    except ValueError:
        raise commands.BadArgument('bad formatting of dice value')
    return await _dice(ctx, count, size, offset)

async def _dice(ctx, count, size, offset):
    rolls = [random.randint(offset+1, offset+size) for i in range(count)]  # eg for 20 with offset 3, generate values 4 to 23
    embed = discord.Embed(title=f'Dice for {count}d{size}+{offset}')
    embed.description = '\n'.join((f'#{i}: **{roll}**' for i, roll in enumerate(rolls)))
    embed.add_field(name='sum', value=f'total = {sum(rolls)}')
    await ctx.send(embed=embed)

Output:

在此處輸入圖像描述

在上面,您可以看到d10+10輸出范圍[11,20]中的值,與默認值[1,10]相差 10。

我特別不熟悉 discord.py,但這是我在普通文件中的做法

import random
user_input = input("Input dice size and how many (ex. 3d6)") #here you wouldn't be asking for input, just reading it off the server
dice_number = int(user_input.split("d")[0])
dice_add = int(user_input.split("+")[1])
print(dice_add)
dice_sides = int(user_input.strip(str(dice_number)).strip(str(dice_add)).strip("d").strip("+"))
total_number = 0
for i in range(dice_number):
  total_number += random.randint(1, dice_sides)
total_number += dice_add
print(total_number)

total_number = 0
for i in range(dice_number):
  total_number += random.randint(1, dice_sides)
total_number += int(dice[2])
print(total_number)

如果您還想減去,只需將輸入設為類似 4d12+-6 的 -6 修飾符

這是我的寫法:

import random
import re

from discord.ext import commands

# ...

@bot.command()
async def roll(ctx: commands.Context, cmd: str):
    num, sides, offset = map(lambda s: int(s), re.split(r"[d+]+", user_input))
    total = sum(random.randint(1, sides) for _ in range(num)) + offset
    # do what you want with the total

現在,這里發生了一些事情,所以我將嘗試對其進行分解。

  • re.split(r"[d+]+")獲取我們的user_input並將其拆分為一個或多個分隔符:'d' 和 '+'。
  • map采用這些拆分值並將它們全部轉換為int s。
  • sum部分是一種更 Pythonic 的方式,它執行相同的操作num次並將結果相加。 我們在最后添加offset

我真的不明白你想用這種格式實現什么,所以我將把它留給你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM