如何在我的 python discord bot 中存储输入?

时间:2021-07-19 13:04:10

标签: python discord discord.py

我想制作一个不和谐的机器人,您可以在其中获得一个随机数,最大值是您键入的内容。像这样:

number = input("")

number = int(number)

print(random.randint(1, number))

但我的问题是存储用户输入的输入。到目前为止,我所做的只是使它只有某些最大数字,例如 2 和 100。

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content == ("r100"):
    await message.channel.send(random.randint(1, 100))

  if message.content == ("r2"):
    await message.channel.send(random.randint(1, 2))

3 个答案:

答案 0 :(得分:2)

您可以使用 max_random= int(message.content[1:]) 获取 "r" 后的数字:

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  max_random = int(message.content[1:])
  await message.channel.send(random.randint(1, max_random))

答案 1 :(得分:0)

最简单的方法是使用 commands.Bot Command

你可以为一个命令设置不同的参数,并且可以非常容易地转换它们

from discord.ext import commands  # import commands

# instead of client = discord.Client()
client = discord.Client()
# use this
client = commands.Bot(command_prefix="!")

移除 on_message 事件,或者添加 client.process_commands

@client.event
async def on_message(message):
    await client.process_commands(message) # add this line
    # you can also add other stuff here
# add a command
@client.command()
async def random(ctx, max_number: int): 
    await ctx.send(f"Your number is: {random.randint(1, max_number)}")


# you can also add a second arg
@client.command()
async def random2(ctx, min_number: int, max_number: int): 
    await ctx.send(f"Your number is: {random.randint(min_number, max_number)}")

要使用命令,您可以输入 !random 50!random2 20 50

答案 2 :(得分:0)

Chuaat 发布的代码帮助了我,但是你可以输入(例如)101,它会说 1。我找到了一个解决方案,把它改成这样:

if message.content.startswith("r"):
    maxnum = int(message.content[1:])
    await message.channel.send(random.randint(1, maxnum))

我在尝试执行此操作时犯的错误是将 == 放在startswith 之后。