首页 > 解决方案 > Python:有没有办法使用一定数量的输入?

问题描述

我有一个用于不和谐的简单 python webhook 发送器,带有 3 个 URL 输入。我想弄清楚如何选择使用 1、2 或所有 3 个输入。那可能吗?我不是最有经验的人,所以请详细回答。

from discord_webhook import DiscordWebhook

print('paste webhook 1')
url1 = input()

print('paste webhook 2')
url2 = input()

print('paste webhook 3')
url3 = input()

print('what do you want them to say?')
content = input()
print('sending...')

while True:
    webhook_urls = [url1, url2, url3]
    webhook = DiscordWebhook(url=webhook_urls, content=content)
    response = webhook.execute()

标签: python-3.x

解决方案


我假设您最初会问他们要输入多少个 webhook

from discord_webhook import DiscordWebhook


def ask_for_count():
    webhooks_num = input('How many webhooks would you like to use? (1, 2 or 3) \n')
    # Firstly, you don't need a seperate print statement to ask for input
    # it can be in the input function and if you need the answer in a new line,
    # use the escape character /n which creates a new line after execution.
    return webhooks_num


def get_webhooks():
    if count == '1':
        url1 = input('paste webhook 1 \n')
        webhook_urls.append(url1)
        return # The return ends function as soon as the urls are added to the list.

    elif count == '2':
        url1 = input('paste webhook 1 \n')
        url2 = input('paste webhook 2 \n')
        webhook_urls.append(url1)
        webhook_urls.append(url2)
        return

    elif count == '3':
        url1 = input('paste webhook 1 \n')
        url2 = input('paste webhook 2 \n')
        url3 = input('paste webhook 3 \n')
        webhook_urls.append(url1)
        webhook_urls.append(url2)
        webhook_urls.append(url3)
        return

    else:
        print('Please enter a valid choice.')


def get_content():
    answer = input('what do you want them to say? \n')
    print('sending...')
    return answer


webhook_urls = []
# List is intentionally outside of the function,
# so that you don't create an empty list everytime the function is called.

# Now you call the functions defined above to execute in order.
count = ask_for_count()
get_webhooks()
content = get_content()


while True:
    webhook = DiscordWebhook(url=webhook_urls, content=content)
    response = webhook.execute()

因此,基本上,一旦程序运行,用户就会被询问所需的 webhook 数量,然后根据输入(共 3 个),他们会被询问 webhook,然后将其添加到之前启动的 webhook_urls 列表中。

之后,向用户询问内容并启动 while 循环,正常执行代码,使用函数输出和之前启动的列表;webhook_urls。

希望我有所帮助。


推荐阅读