【问题标题】:How to exit discord.py on_message function?如何退出 discord.py on_message 功能?
【发布时间】:2021-01-30 20:27:04
【问题描述】:

我想在 python 命令中创建一个不和谐机器人,它可以启动一个游戏,你必须在其中写一个给定的单词,一旦用户正确拼写就停止,但 return 在我的情况下不起作用

async def joc(ctx):

     a=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
     '0','1','2','3','4','5','6','7','8','9']

     cuv=random.sample(a,10)
     cuvant=''
     for x in cuv:
         cuvant+=x

     await ctx.send('The game begins in: ')
     await ctx.send('3')
     time.sleep(1)
     await ctx.send('2')
     time.sleep(1)
     await ctx.send('1')
     time.sleep(1)
     await ctx.send('Start!')
     await ctx.send(cuvant)



     @bot.event
     async def on_message(message):
         if message.content==cuvant:
             await message.channel.send(message.author)
             await message.channel.send("Nice")
             return 
     return

我可以通过访问历史来做到这一点,但我想知道如何做到这一点

【问题讨论】:

  • 如果你想停止程序,然后使用exit()退出,如果你想让它再次重复,那么你可以在while True:循环中编写所有工作代码。跨度>
  • 我只想退出这个函数,如果他们再次调用它再次执行它
  • 然后在末尾使用break

标签: python python-3.x discord bots discord.py


【解决方案1】:

您不应该将事件放在命令中,它不会那样工作。您正在寻找的是wait_for,链接中包含如何使用它的示例。基本上,您创建一个check 来查看消息是否采用某种格式或满足您的要求,在您的情况下检查消息是否是正确的词。

【讨论】:

  • 你能写出来吗,因为我无法想象我应该如何使用它
【解决方案2】:

哦,我也遇到了同样的问题

通过将其添加到 on_message() 的最后一行来修复

await client.process_commands(message)
# Replace the client with own bot or something that you have started with

【讨论】:

    【解决方案3】:

    这是修改后的代码,wait_for stijndcl 告诉

    import asyncio
    async def joc(ctx):
    
         a=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
         '0','1','2','3','4','5','6','7','8','9']
    
         cuv=random.sample(a,10)
         cuvant=''
         for x in cuv:
             cuvant+=x
    
         await ctx.send('The game begins in: ')
         await ctx.send('3')
         await asyncio.sleep(1)
         await ctx.send('2')
         await asyncio.sleep(1)
         await ctx.send('1')
         await asyncio.sleep(1)
         await ctx.send('Start!')
         await ctx.send(cuvant)
         content = ""
         while content != cuvant:
              msg = await bot.wait_for("message", check=lambda m: m.author == ctx.author and m.channel.id == ctx.channel.id)
              content = msg.content
         await ctx.send(message.author)
         await ctx.send(cuvant)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2020-12-18
      • 2020-12-18
      相关资源
      最近更新 更多