【问题标题】:Python, discord.py - search wikipedia with user inputPython, discord.py - 使用用户输入搜索维基百科
【发布时间】:2020-09-14 02:24:38
【问题描述】:

我正在尝试使用 Discordpy 和 WikipediaApi 制作 Discord 机器人。该机器人应该在输入适当的句子后打印维基百科摘要:“什么是......?”或“谁是……?”。到目前为止,它运行良好,但维基百科页面是在代码中定义的。我想将页面标题作为用户的关键字,例如,他可能会问“微软是什么?”或“埃隆·马斯克是谁?”并收到回复(当然,如果维基百科中存在页面)。我知道我应该使用 client.wait_for(),但我对此感到困惑,因为输入将是较长句子的一部分。

import discord
import wikipediaapi

@client.event
async def on_message(message):
    if not (message.author == client.user):
        if (message.mention_everyone == False):
            if (client.user.mentioned_in(message) or isinstance(message.channel, discord.abc.PrivateChannel)):
                async with message.channel.typing():

                    if message.content.startswith('What is') or message.content.startswith('Who is'):
                        wiki_wiki = wikipediaapi.Wikipedia('pl')
                        page_py = wiki_wiki.page('Elon Musk')  <----- HERE

                        await message.channel.send("Page - Summary: %s" % page_py.summary)

client.run('token')

【问题讨论】:

  • 您使用 wikipedia api 是否有特定原因? IMO 在许多方面使用requests api 来获取页面的源代码(如果存在)会更容易
  • 我注意到 Wikipedia api 是一种流行的解决方案,并且不难找到如何在我自己的代码中实现它。此外,Discord 上的结果看起来如我所愿。

标签: python discord bots discord.py


【解决方案1】:

当您尝试从每条消息中解析它时,您可以尝试仅拆分“命令”(What is/Who is)并将其余部分作为查询。

if message.content.startswith('What is') or message.content.startswith('Who is'):
    args = message.content.split(" ")  # Split the message based on spaces
    if len(args) > 2:  # Checks if a query was passed, avoids a potential IndexError
        query = " ".join(args[2:])  # Cut out the "What is" part, and join the rest back into a single string with spaces
        wiki_wiki = wikipediaapi.Wikipedia('pl')
        page_py = wiki_wiki.page(query)

我强烈建议使用内置的命令模块,并且只创建一个“Wiki”命令。这样,您的代码将如下所示:

@client.command()
async def wiki(ctx, *query):
    if query:  # I'm not sure what the wikipedia api does if you give it an empty string, so this if-statement makes sure something was passed
         query = " ".join(query)  # The rest of the args were passed as a list, so join them back into a string with spaces
         wiki_wiki = wikipediaapi.Wikipedia('pl')
         page_py = wiki_wiki.page(query)

您可以通过简单地在 Discord 中调用它[prefix]wiki elon musk。在您的情况下,您检查是否提到了该机器人来解析命令which can also be handled with prefixes,这样您就不会失去任何功能(如果您愿意,可以添加更多前缀)。

【讨论】:

  • 我决定不使用 cogs 和前缀命令,因为我的机器人是基于 AIML 文件的聊天机器人(因此它的主要作用是与用户进行对话)。对我来说重要的是它可以对某些句子做出自然反应。我会尝试你的建议!
猜你喜欢
  • 2015-02-12
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2013-12-26
  • 1970-01-01
相关资源
最近更新 更多