如何在 python discord bot 中获取用户输入?

Posted

技术标签:

【中文标题】如何在 python discord bot 中获取用户输入?【英文标题】:How can I get user input in a python discord bot? 【发布时间】:2020-10-04 06:06:51 【问题描述】:

我有一个 python discord bot,我需要它在命令后获取用户输入,我该怎么做?我是 python 和制作不和谐机器人的新手。这是我的代码:

import discord, datetime, time
from discord.ext import commands
from datetime import date, datetime

prefix = "!!"
client = commands.Bot(command_prefix=prefix, case_insensitive=True)

times_used = 0

@client.event
async def on_ready():
  print(f"I am ready to go - client.user.name")
  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"client.command_prefixpython_help. This bot is made by drakeerv."))

@client.command(name="ping")
async def _ping(ctx):
  global times_used
  await ctx.send(f"Ping: client.latency")
  times_used = times_used + 1

@client.command(name="time")
async def _time(ctx):
  global times_used
  from datetime import date, datetime

  now = datetime.now()

  if (now.strftime("%H") <= "12"):
    am_pm = "AM"
  else:
    am_pm = "PM"

  datetime = now.strftime("%m/%d/%Y, %I:%M")

  await ctx.send("Current Time:" + ' '  + datetime + ' ' + am_pm)
  times_used = times_used + 1

@client.command(name="times_used")
async def _used(ctx):
  global times_used
  await ctx.send(f"Times used since last reboot:" + ' ' + str(times_used))
  times_used = times_used + 1

@client.command(name="command") #THIS LINE
async def _command(ctx):
  global times_used
  await ctx.send(f"y or n")
  times_used = times_used + 1

@client.command(name="python_help")
async def _python_help(ctx):
  global times_used
  msg = '\r\n'.join(["!!help: returns all of the commands and what they do.",
                     "!!time: returns the current time.",
                     "!!ping: returns the ping to the server."])
  await ctx.send(msg)
  times_used = times_used + 1



client.run("token")

我正在使用 python 版本 3.8.3。我已经看过其他帖子,但他们没有回答我的问题或给我错误。任何帮助将不胜感激!

【问题讨论】:

【参考方案1】:

你会想要使用Client.wait_for()

@client.command(name="command")
async def _command(ctx):
    global times_used
    await ctx.send(f"y or n")

    # This will make sure that the response will only be registered if the following
    # conditions are met:
    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and \
        msg.content.lower() in ["y", "n"]

    msg = await client.wait_for("message", check=check)
    if msg.content.lower() == "y":
        await ctx.send("You said yes!")
    else:
        await ctx.send("You said no!")

    times_used = times_used + 1

还有超时:

import asyncio # To get the exception

@client.command(...)
async def _command(ctx):
    # code
    try:
        msg = await client.wait_for("message", check=check, timeout=30) # 30 seconds to reply
    except asyncio.TimeoutError:
        await ctx.send("Sorry, you didn't reply in time!")

参考资料:

Client.wait_for() - 更多示例在这里 Message.author Message.channel Message.content asyncio.TimeoutError

【讨论】:

msg = await client.wait_for(... 将他们的message 放入一个变量中。您可以通过msg.content查看内容。 ^ 我用一个例子编辑了答案 谢谢,帮了大忙! 祝你机器人的其余部分好运:^) 现在做一个机器人。试图添加一个刽子手游戏。这帮助很大。 我的刽子手游戏差不多完成了。如此成功......谢谢你的时代无限。 :)【参考方案2】:

我花了几天时间试图弄清楚这一点,对我来说唯一简单的事情就是将 message.content 存储到一个列表中并稍后使用它。

some_list = []
    user_message = message.content.split()
    some_list.append(user_message)

因为我使用的是命令,所以我想删除那个 '!'并获取原始消息

        for i  in some_list:
        del i[0]# delete's command tag

【讨论】:

【参考方案3】:

有了这个,你可以做出这样的事情

@client.command()
async def command(ctx):
    computer = random.randint(1, 10)
    await ctx.send('Guess my number')

    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel and int(msg.content) in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    msg = await client.wait_for("message", check=check)

    if int(msg.content) == computer:
        await ctx.send("Correct")
    else:
        await ctx.send(f"Nope it was computer")

【讨论】:

以上是关于如何在 python discord bot 中获取用户输入?的主要内容,如果未能解决你的问题,请参考以下文章

Python Discord Bot:如何与用户交互?

如何将多个参数插入discord bot命令python

如何添加超时,python discord bot

Python discord bot如何将消息与列表进行比较

Discord Bot Python 2.6(如何通过嵌入造句)

Discord Bot Python 让它创建嵌入