【问题标题】:How to use loop in discord.py?如何在 discord.py 中使用循环?
【发布时间】:2020-08-23 18:40:44
【问题描述】:

您好,我正在制作一个机器人来创建排行榜,这是代码

@bot.command(pass_context=True)
async def on(ctx):
    await ctx.send("How many total teams are there?")
    t = await get_input_of_type(int, ctx)
    totalteam = 0
    while totalteam <= t:
        await ctx.send("Enter team name :")
        teamname1 = await get_input_of_type(str, ctx)
        await ctx.send("How many kills did they get?")
        firstnum1 = await get_input_of_type(int, ctx)
        await ctx.send("How much Position points did they score?")
        secondnum1 = await get_input_of_type(int, ctx)
        totalteam -=1
    await ctx.channel.send("**__Today's Result:__**")
    await ctx.channel.send("Format: Team Name/Kills/Position Points/Total Points")
    await ctx.send(f"{teamname1} | {firstnum1} | {secondnum1} = {firstnum1+secondnum1}")

此命令使用户可以选择要创建多少个团队来创建排行榜。 整个团队的循环有效,但我也想要一些能在循环中显示结果的东西。 我希望它应该发送用户输入的每个团队的总分。现在它只发送第一个入口点。

【问题讨论】:

  • 你希望它输出什么?输入预期结果?
  • get_input_of_type的功能是什么?
  • sum = 0 以上 while 循环比 sum=sum+secondnum1+kills 可以工作,而不是输出 sum。

标签: python discord discord.py


【解决方案1】:

创建一个具有特定属性(例如团队名称、击杀数、位置点等)的团队 Class 可能是一个很酷的想法。然后您可以将所有团队添加到数组或列表中,然后遍历它们以创建排行榜和其他有用的功能。

我推荐这个 YouTube 视频,它完美地详细介绍了 Python 中的面向对象编程 (OOP) 的工作原理:https://www.youtube.com/watch?v=MikphENIrOo

您的团队课程可能如下所示:

Class Team:
 def __init__(name, kills, points):
  self.name = name
  self.kills = kills
  self.points = points 

那么你可能有一个列表

teams = []

您可以将用户想要的每个团队数量附加到该列表中

teams.append(Team(BestTeam, 10, 50))

【讨论】:

    【解决方案2】:

    您可以使用嵌入来使其看起来不错。我添加了你应该使用的两个函数。

    def check(ctx):
        return lambda m: m.author == ctx.author and m.channel == ctx.channel
    
    
    async def get_input_of_type(func, ctx):
        while True:
            try:
                msg = await bot.wait_for('message', check=check(ctx))
                return func(msg.content)
            except ValueError:
                continue
    
    
    @bot.command()
    async def on(ctx):
        await ctx.send("How many total teams are there?")
        t = await get_input_of_type(int, ctx)
        embed = discord.Embed(title="**__Today's Result:__**")
        
        for i in range(t):
            await ctx.send(f"Enter team {i+1} name :")
            teamname = await get_input_of_type(str, ctx)
            await ctx.send("How many kills did they get?")
            firstnum = await get_input_of_type(int, ctx)
            await ctx.send("How much Position points did they score?")
            secondnum = await get_input_of_type(int, ctx)
    
            embed.add_field(name=teamname, value=f'Kills: {firstnum}\n Position: {secondnum}')
    
        await ctx.send(embed=embed)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 2023-01-26
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2023-03-22
      相关资源
      最近更新 更多