【问题标题】:discord.py - Guessing game no responsediscord.py - 猜谜游戏没有反应
【发布时间】:2021-08-01 13:05:59
【问题描述】:

$play 被输入到我的 Discord 服务器上的频道但机器人没有响应或以任何方式做出反应时,应该执行以下代码。

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

@bot.command(name="play")
async def play(ctx):
  def check(m):
    return m.author == ctx.author and m.channel == ctx.message.channel

  number = random.randint(1,100)
  await ctx.send('I have a number in mind between 1 and 100, guess it')

  for i in range(0,5):
    guess = await bot.wait_for("message", check=check)
    
    if guess.content > number:
      await ctx.send("The number is greater")
    elif guess.content < number:
      await ctx.send("The number is smaller")
    elif guess.content == number:
      await ctx.send("You guessed the number!!")
    else:
      return ("It has to be a positive integer between 1 to 100")
  else:
    await ctx.send("You lost, type $play to play again.")

【问题讨论】:

  • 您的代码中有on_message 事件吗?
  • @Chuaat 我应该在哪里(什么位置)添加on_message 事件?
  • 你不应该,on_message事件与你的问题根本没有关系,你的代码有一个简单的逻辑错误。
  • 这能回答你的问题吗? Guessing game, discord.py bot

标签: python discord discord.py


【解决方案1】:

因为您的代码中存在逻辑错误,所以在您检查 guess.content(字符串)是否小于/大于/等于整数的所有 if/elif 语句中,这绝不是真的,然后在您的 else 语句中你根本没有发送任何东西(你正在返回,退出函数而不是发送实际消息)。

@client.command(name="play")
async def play(ctx):
  def check(m):
    return m.author == ctx.author and m.channel == ctx.message.channel

  number = random.randint(1,100)
  await ctx.send('I have a number in mind between 1 and 100, guess it')

  for i in range(0,5):
    guess = await client.wait_for("message", check=check)
    
    if int(guess.content) > number:
      await ctx.send("The number is greater")
    elif int(guess.content) < number:
      await ctx.send("The number is smaller")
    elif int(guess.content) == number:
      await ctx.send("You guessed the number!!")
    else:
      await ctx.send("It has to be a positive integer between 1 to 100")
  else:
    await ctx.send("You lost, type $play to play again.")

如果消息不包含数字,这将引发错误,您应该在检查中添加另一个语句

def check(m):
    return m.author == ctx.author and m.channel == ctx.message.channel and m.content.isdigit()

【讨论】:

  • 我已经进行了您提到的更改,但机器人仍然没有响应键入 $play.. 这是程序的回复 link
  • 代码中的其他命令起作用;我正在为他们使用@client.event。如果您在我之前的编辑中错过了链接,请再次点击此处:replit.com/@fs0c13ty/Mr-Robot#main.py
  • 那你为什么决定使用bot.command 这个?您还应该将其从 bot.wait_for 更改为 client.wait_for
  • @Elmo 如果您想使用commands,您必须更改代码中的一些内容。不久前我为此做了一个answer。你也不能使用botclient,选择一个并定义它。
猜你喜欢
  • 2021-08-02
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多