简体   繁体   English

如何从 discord 获取用户输入并将其存储为变量以在方程式中使用? Discord.py

[英]How do i take user input from discord and store it as a variable to use in an equation? Discord.py

Ok so im not intierly fluent in discord.py but heres the code im trying to use:好的,所以我对 discord.py 不是很流利,但这是我尝试使用的代码:

from discord import channel
from discord.embeds import Embed
import discord
from discord.ext import *
import os
import random
import string
from discord.ext import commands
from dotenv import load_dotenv
from discord.ext import commands
import requests
import sys
import threading
from discord.utils import get
import discord
import asyncio
from threading import Thread
from keep_alive import keep_alive

load_dotenv()
bot = commands.Bot(command_prefix = '.')

def init():
    loop = asyncio.get_event_loop()
    loop.create_task(bot.run(token))
    Thread(target=loop.run_forever).start()
    
@bot.event
async def on_ready():
  print('Bot is up and running')


@bot.command()
async def p(ctx):
  # MESSAGE 1, should have user input stored in variable "place"
  embed=discord.Embed()
  embed.add_field(name="Where did you place?", value="** **")
  sent = await ctx.send(embed=embed)

  # MESSAGE 2, should have user input stored in variable "kills"
  embed=discord.Embed()
  embed.add_field(name="How many kills did you get?", value="** **")
  sent = await ctx.send(embed=embed)

  # MESSAGE 3, should have combined input of place + kills AFTER running PLACEMENT CALC in variable "total""
  embed=discord.Embed()
  embed.add_field(name="Total Points:", value=total)
  sent = await ctx.send(embed=embed)

bot.run("OTA0MDc5MzY5NzU1MDU4MjA2.YX2Thg.S4A2e9SqZUvYZpyTzBW44W4Vumk")
keep_alive()
init()

I want to take the user response from the first and second msgs from discord.py and input them into the first 2 questions of this code so i can claculate the total:我想从 discord.py 的第一个和第二个消息中获取用户响应,并将它们输入到此代码的前两个问题中,以便我可以计算总数:

import sys

# Placement input, should be response to MESSAGE 1 In discord.py
print ("Where did you place? ")
place = int(input('| \n'))

#Checking if place is in range from 20-1, Should respond with the message in an embed in discord
if place >20 or place <1:
    place = 0

# Kill input, response to MESSAGE 2 In discord.py
print ("How many kills did you get?")
kills = int(input('| \n '))


# Assigning total / final variable
total = 0
tplace = 0

# ranges for placement variables
top20 = (18,19,20)      #Top 20
top17 = (16,17)         #Top 17
top15 = (13,14,15)      #Top 15
top12 = (11,12)         #Top 12
top10 = (6,7,8,9,10)    #Top 10

#Total kills calculations
kills = kills * 10
    
#Total placement calculations
if place in top20: #Top 20
    tplace = 10
    
if place in top17: #Top 17
    tplace = 20
    
if place in top15: #Top 15
    tplace = 35
    
if place in top12: #Top 12
    tplace = 50
    
if place in top10: #Top 10
    tplace = 60

if place == 5: #Top 5
    tplace = 80
    
if place == 4: #Top 4
    tplace = 90
    
if place == 3: #Top 3
    tplace = 100
    
if place == 2: #Top 2
    tplace = 125    
    
if place == 1: #Top 1 / vic roy
    tlace = 175

#Output, should be MESSAGE 3 In discord.py
total = kills + tplace
print ("Total Points: ")
print (total)

and after calculating the total I just send the variable "total" inside of an emebd, i just dont know hwo to store the response to 2 separate discord message inside of the variables i need.在计算总数之后,我只是在 emebd 中发送变量“total”,我只是不知道如何在我需要的变量中存储对 2 个单独的 discord 消息的响应。 It should run as它应该运行为

Bot: "Where did you place?" 
you: 10 (Stored in variable "place")

Bot:"How many kills did you get?" 
you: 1 (Stored in variable "kills")

---------calculating the total points (should be 70)-------

Bot: "Total points: 70"   

I know im probably being stupid but nothing i find online rlly helps我知道我可能很愚蠢,但我在网上找到的 rlly 没有任何帮助

You can use wait_for() function.您可以使用wait_for() function。 I have written a function below which allows you get some data from user.我在下面写了一个 function,它允许你从用户那里获取一些数据。

import asyncio

async def prompt(ctx, message: str, timeout: float) -> str:
    await ctx.send(message)
    message = await bot.wait_for('message', check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=timeout)
    return message.content

Let's use it for your command:让我们将它用于您的命令:

@bot.command()
async def calculate(ctx):
    try:
        place = await prompt(ctx, "Where did you place?", timeout=10)
        kills = await prompt(ctx, "How many kills did you get?", timeout=10)
    except asyncio.TimeoutError:
        await ctx.send("You are too slow.")  # if time limit exceeded
    else:
        await ctx.send(calculate_score(place, kills))  # now you can calculate total score and send the result using input data (`place`, `kills`)

I added some features for your embed to make it look better and used wait_for to wait for user input.我为您的嵌入添加了一些功能以使其看起来更好,并使用wait_for来等待用户输入。 You can copy and paste - I copied您可以复制和粘贴 - 我复制了

def calculate_points(place):
    place_pt = 0
    top20 = (18,19,20)  
    top17 = (16,17)     
    top15 = (13,14,15)  
    top12 = (11,12)     
    top10 = (6,7,8,9,10)

    if place in top20: #Top 20
        place_pt = 10
        
    elif place in top17: #Top 17
        place_pt = 20
        
    elif place in top15: #Top 15
        place_pt = 35
        
    elif place in top12: #Top 12
        place_pt = 50
        
    elif place in top10: #Top 10
        place_pt = 60

    elif place == 5: #Top 5
        place_pt = 80
        
    elif place == 4: #Top 4
        place_pt = 90
        
    elif place == 3: #Top 3
        place_pt = 100
        
    elif place == 2: #Top 2
        place_pt = 125    
        
    elif place == 1: #Top 1
        place_pt = 175

    return place_pt

@bot.command()
async def p(ctx):
    await ctx.send("Where did you place?")

    try:  
        def check1(m):
            return m.author == ctx.author and m.channel == ctx.channel
        place = await bot.wait_for("message", check=check1, timeout=60.0)
        place = int(place.content)


        await ctx.send("How many kills did you get?")
    
        def check2(m):
            return m.author == ctx.author and m.channel == ctx.channel
        kills = await bot.wait_for("message", check=check2, timeout=60.0) # you can change timeout here
        kills = int(kills.content)

    except Exception as e: # error handler
        if isinstance(e, asyncio.TimeoutError): # if timeout limit is exceeded
            await ctx.send("Too slow")
        elif isinstance(e, ValueError): # if use something else than number (when asked for kills and place)
            await ctx.send("Wrong value")
        return

    kills_pt = kills * 10
    place_pt = calculate_points(place) # invoking function that calculates place points

    total = kills_pt + place_pt

    embed=discord.Embed(title=f"{ctx.author}'s points")
    embed.set_thumbnail(url=ctx.author.avatar_url)
    embed.add_field(name="Place:", value=place, inline=True)
    embed.add_field(name="Kills:", value=kills, inline=True)
    embed.add_field(name="Total points:", value=total, inline=False)
    await ctx.send(embed=embed)

Results:结果:

结果

Also, you might want to remove unnecessary code and imports:此外,您可能希望删除不必要的代码和导入:

import discord, asyncio
from discord.ext import commands
from dotenv import load_dotenv
from keep_alive import keep_alive

load_dotenv()
bot = commands.Bot(command_prefix = '.')

@bot.event
async def on_ready():
    print('Bot is up and running')

# OTHER CODE HERE

keep_alive()
bot.run(Token)

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

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