简体   繁体   English

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

[英]How do I store input in my python discord bot?

I want to make a discord bot where you can get a random number with the max being what you type.我想制作一个不和谐的机器人,您可以在其中获得一个随机数,最大值是您键入的内容。 Like this:像这样:

number = input("")

number = int(number)

print(random.randint(1, number))

But my problem is storing the input the user typed.但我的问题是存储用户输入的输入。 All I've done this far is making it only certain max numbers like 2 and 100.到目前为止,我所做的只是使它只有某些最大数字,例如 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))

You can use max_random= int(message.content[1:]) to get the number after the "r" :您可以使用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))

The simplest way to do this is with a commands.Bot Command最简单的方法是使用commands.Bot Command

you can set different parameters to a command, and can convert them super easy您可以为命令设置不同的参数,并且可以非常轻松地转换它们

from discord.ext import commands  # import commands

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

remove the on_message event, or add client.process_commands to it删除 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)}")

to use the command you can type !random 50 or !random2 20 50要使用该命令,您可以键入!random 50!random2 20 50

The code Chuaat posted helped me but with that you could type (for example) 101 and it would say 1. I got to a solution to put it like this instead: Chuaat 发布的代码帮助了我,但是你可以输入(例如)101,它会说 1。我找到了一个解决方案,把它改成这样:

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

The mistake I made when trying to do exactly this was putting == after startswith.我在尝试这样做时犯的错误是将 == 放在startswith 之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM