【问题标题】:Discord Python Bot - User inputDiscord Python Bot - 用户输入
【发布时间】:2022-03-12 22:05:08
【问题描述】:

所以我想制作一个接受用户输入的不和谐 python 机器人。 我想做的是计算某事的百分比。

这是我想做的:

我在开始使用 discord 机器人之前编写了这段代码。但我不知道如何接受用户输入。

userInputOriginalPrice = float(input("Enter the original price: "))

userInputPercentage = float(input("Enter how much percantage: "))

discount = ( userInputPercentage / 100) * userInputOriginalPrice

finalCost = userInputOriginalPrice - discount

print("You saved", discount, ". Your total is", finalCost)

【问题讨论】:

  • 您是否尝试过使用 discord api 模块(例如 discord.py)?通常,人们会将用户的消息内容视为输入。该站点上已经有关于如何接收用户消息和获取其内容的资源。您在尝试此操作时遇到过任何问题吗?

标签: python discord percentage


【解决方案1】:

你可以使用 client.wait_for() 方法来接受事件和检查,所以

import discord
from discord.ext import commands

client = commands.Bot(commands_prefix='!')

@commands.command()
async def calculate_percentage(ctx):

    await ctx.send('Enter the original price: ')
    message_response = client.wait_for('message', check=lambda m: m.user == ctx.user)
    original_price = float(message_response.content)

    await ctx.send('Enter how much percantage: ')
    message_response = client.wait_for('message', check=lambda m: m.user == ctx.user)
    input_percantage = float(message_response.content)

    # Your calculations
    discount = ( input_percantage / 100) * original_price 
    finalCost = original_price - input_percantage

    await ctx.send(f"You saved {discount}. Your total is, {finalCost}")

client.run('Bot Token')

【讨论】:

  • 您在不和谐对象中将 author 与 user 混淆了。我还建议在频道中添加支票。防止在其他渠道发送的消息被接受为回复。 check=lambda m: m.author == ctx.author and m.channel==ctx.channel
【解决方案2】:

更简单的方法是使用 python 内置的.split() 方法。

例如当用户输入!percentage 300 60时

## this will split your message where there is a space
_, orig_price, discount = message.split(" ")

这将节省时间并创造一个更加用户友好的环境,并且代码更具可读性

【讨论】:

    【解决方案3】:

    我看到其他人发布的答案甚至不起作用!这是正确的,但有点复杂,因为 discord.py 结束了。

    @bot.command(aliases=['discount'])
    async def percentage(ctx, *nums):
    operation = " / ".join(nums)
    operation = " * ".join(nums)
    await ctx.send(f'Tip: (discount) / 100 * (real price) \n\n{operation} = {eval(operation)}')
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2021-04-22
      • 2020-12-22
      • 2020-10-29
      相关资源
      最近更新 更多