【问题标题】:bot executes next command without waiting for messagebot 执行下一个命令而不等待消息
【发布时间】:2021-02-19 09:24:25
【问题描述】:

您好,我一直在尝试为我的服务器创建一个应用程序机器人,该机器人向您发送一个问题,然后该人回答,然后记下等,但我的问题是,有时下一个问题会发送而无需等待前一个问题的答案问题。这只发生在大多数时候。试试我可能无法解决问题。我对 python 还很陌生,而且我也束手无策。 我的参考代码:

import os       
from discord.ext import commands    
from discord.utils import get 
BOT_PREFIX = ("!")
client = commands.Bot(command_prefix=BOT_PREFIX)    
a_list = []   
@client.event
async def on_ready():
    print ("------------------------------------")
    print ("Bot Name: " + client.user.name)
    print ("------------------------------------")        
submit_wait = False
a_list = []
b_list = []
c_list = []
d_list = []      
@client.command(aliases=['application'])
async def app(ctx):
    a_list = []
    b_list = []
    c_list = []
    d_list = []
    submit_wait = False    
    submit_channel = client.get_channel(806404345830047744)
    channel = await ctx.author.create_dm()
    await channel.send("starting applaction!")
    await ctx.send(ctx.author.mention + "check your dms!")
    time.sleep(2)    
    def check(m):
        return m.content is not None and m.channel == channel        
    await channel.send("Do you have any prior milli sim experiance?")
    msg = await client.wait_for('message', check=check)
    a_list.append(msg.content)        
    await channel.send("What time zone are you in?")        
    msg2 = await client.wait_for('message', check=check)
    b_list.append(msg2.content)        
    await channel.send("If a officer ordered you to break the genva convention would you do it?")        
    msg3 = await client.wait_for('message', check=check)
    c_list.append(msg3.content)        
    await channel.send("Is there any particular dvision you want to be in?")    
    msg4 = await client.wait_for('message', check=check)
    d_list.append(msg4.content)       
    await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
    msg = await client.wait_for('message', check=check)
    if "submit" in msg.content.lower():
      submit_wait = False
      answers = "\n".join(f'{a}. {b}' for a, b in enumerate(a_list, 1))
      answer = "\n".join(f'{a}. {b}' for a, b in enumerate(b_list, 2))
      answerr = "\n".join(f'{a}. {b}' for a, b in enumerate(c_list, 3))
      answerss = "\n".join(f'{a}. {b}' for a, b in enumerate(d_list, 4))                
      submit_msg = f'Application from {msg.author} \nThe answers are:\n{answers}'
      submit_msg2 = f'{answer}'
      submit_msg3 = f'{answerr}'
      submit_msg4 = f'{answerss}'
      await submit_channel.send(submit_msg)
      await submit_channel.send(submit_msg2)   
      await submit_channel.send(submit_msg3)
      await submit_channel.send(submit_msg4)   
client.run(os.getenv('TOKEN'))

【问题讨论】:

  • 可能首先使用print() 来查看执行了代码的哪一部分以及变量中有什么。也许您有错误的值,或者它执行的代码与您期望的不同。它被称为"print debuging"
  • 不要使用那么多空行。它使代码变得冗长且不可读 - 我们必须滚动它才能看到更多代码。
  • 我会尝试使用 print() 方法,我会删除空格
  • 如果内部函数app()你想将空列表分配给外部a_list,那么你必须使用global a_list。与外部submit_waitsubmit_wait = False 内部app() 相同 - 它需要global submit_wait 为外部变量赋值。如果你不使用它,那么它会创建局部变量submit_wait
  • answeranswerranswerss 是字符串,因此使用 submit_msg2 = f'{answer}' (等)是无用的,因为它将字符串转换为相同的字符串。您可以使用send(answer) 代替send(submit_msg2)

标签: python discord.py


【解决方案1】:

我使用print() 测试了代码,我认为问题在于check() 有时会收到机器人的问题并将其视为用户的答案。

您必须在check() 中检查m.author - 类似这样的内容

@client.command(aliases=['application'])
async def app(ctx):
    submit_channel = client.get_channel(806404345830047744)
    #print('submit_channel:', submit_channel)

    channel = await ctx.author.create_dm()
    author = ctx.author

    def check(m):
        #print('m.author:', m.author)
        #print('m.content:', m.content)
        #print('m.channel:', m.channel, m.channel == channel)
        return m.author == author and m.content and m.channel == channel

具有其他更改的最少工作代码

import os
import time
from discord.ext import commands

client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print ("------------------------------------")
    print ("Bot Name:", client.user.name)
    print ("------------------------------------")

@client.command(aliases=['application'])
async def app(ctx):
    submit_channel = client.get_channel(806404345830047744)
    print('submit_channel:', submit_channel)

    channel = await ctx.author.create_dm()
    author = ctx.author

    def check(m):
        print('m.author:', m.author)
        print('m.content:', m.content)
        print('m.channel:', m.channel, m.channel == channel)
        return m.author == author and m.content and m.channel == channel

    await channel.send("starting applaction!")
    await ctx.send(ctx.author.mention + " check your dms!")
    time.sleep(2)

    await channel.send("Do you have any prior milli sim experiance?")
    answer_a = await client.wait_for('message', check=check)
    answer_a = answer_a.content

    await channel.send("What time zone are you in?")
    answer_b = await client.wait_for('message', check=check)
    answer_b = answer_b.content

    await channel.send("If a officer ordered you to break the genva convention would you do it?")
    answer_c = await client.wait_for('message', check=check)
    answer_c = answer_c.content

    await channel.send("Is there any particular dvision you want to be in?")
    answer_d = await client.wait_for('message', check=check)
    answer_d = answer_d.content

    await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
    msg = await client.wait_for('message', check=check)

    if "submit" in msg.content.lower():
        submit_msg = f'''Application from {msg.author}
The answers are:
1. {answer_a}
2. {answer_b}
3. {answer_c}
4. {answer_d}'''
        await submit_channel.send(submit_msg)

client.run(os.getenv('TOKEN'))

【讨论】:

    【解决方案2】:

    好吧,乍一看我发现了一些错误

    首先,小问题,但使用time.sleep(2) 会暂停整个机器人,因此如果您想让其他人同时运行此命令,您可能需要更改此设置

    import asyncio # instead of import time
     
    await asyncio.sleep(2) # instead of time.sleep(2)
    

    另外你不需要重复那么多代码,这应该让它完全按照你想要的方式工作

    import os       
    from discord.ext import commands    
    from discord.utils import get
    import asyncio
    
    client = commands.Bot(command_prefix="!")    
    
    @client.event
    async def on_ready():
        print ("------------------------------------")
        print ("Bot Name: " + client.user.name)
        print ("------------------------------------")
    
    submit_wait = False
    questions = ["Do you have any prior milli sim experiance?",
                 "What time zone are you in?",
                 "If a officer ordered you to break the genva convention would you do it?",
                 "Is there any particular dvision you want to be in?"]
    
    @client.command(aliases=['application'])
    async def app(ctx):
        
        submit_channel = client.get_channel(810118639234973719)
        channel = await ctx.author.create_dm()
        
        await channel.send("starting applaction!")
        await ctx.send(ctx.author.mention + "check your dms!")
        await asyncio.sleep(2)
        
        def check(m):
            return m.content != "" and m.channel == channel
    
        answers = []
        for question in questions:
            await channel.send(question)
            msg = await client.wait_for("message", check=check)
            answers.append(msg.content)
        
        await channel.send('thank you for applying! a officer will do your application as soon as they can - respound with "submit" to submit your application')
        msg = await client.wait_for("message", check=check)
    
        if "submit" in msg.content.lower():
            submit_wait = False
            answers = [f"{no+1}. {ans}" for no, ans in enumerate(answers)]
            submit_msg = [f"Application from {msg.author}",
                          "The answers are:", *answers]
            await submit_channel.send("\n".join(submit_msg))
    
    client.run(os.getenv('TOKEN'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多