【问题标题】:Wikipedia search discord bot command维基百科搜索不和谐机器人命令
【发布时间】:2021-03-16 05:07:50
【问题描述】:

这是我第一次编写机器人程序,我需要帮助我在 Discord 上使用我的 Wikipedia 机器人程序。它是用wikipedia api编写的。

wikipedia = wikipedia.summary('', sentences=1, chars=100, 
auto_suggest=True, redirect=True)

@client.event
async def on_message(message):
    if message.content.startswith('!define'):
       await client.send_message(message.channel, wikipedia)

如何让机器人识别第一行中的搜索?我希望该命令搜索放置在 !define 之后的单词。

谢谢!

【问题讨论】:

    标签: python bots wikipedia discord


    【解决方案1】:

    据我所知,这是代码有多个问题。首先,你的wikipedia 变量需要是一个函数,看起来你可能没有掌握python 的一些基础知识,如果是这样,我建议你阅读函数herehere。一个函数可以接受一个或多个参数并返回一个值。在您的情况下,您希望传递一个带有您要定义的术语的参数,并且返回的值将是定义。其语法类似于:

    def wiki_summary(arg):
    
        definition = wikipedia.summary(arg, sentences=1, chars=100, 
        auto_suggest=True, redirect=True)
        return definition
    

    在您的 client.send_message 函数中,您想要调用新创建的函数,您可以使用 client.send_message(message.channel, wiki_summary(arg) 执行此操作,其中 arg 替换为您希望维基百科定义的术语。 在您的情况下,这将是“!定义”之后消息中的所有单词。最简单的方法是使用.split() (Docs),它将字符串分隔为子字符串,默认分隔符是空格,并创建一个包含所有子字符串的列表。要获取第一个单词 ("!define") 之后的所有单词,您可以使用 list indices ([start:end]),选择除您使用 list[1:] 的列表中的第一个对象以外的所有内容,这将启动在 list1 处选择并在列表末尾结束。在代码中,这看起来像这样:

    words = message.content.split()
    important_words = words[1:]
    

    然后你想在你的wikipedia 函数中将这些重要的词作为 arg 传递,如下所示:

    @client.event
    async def on_message(message):
        if message.content.startswith('!define'):
           words = message.content.split()
           important_words = words[1:]
           await client.send_message(message.channel, wiki_summary(important_words)
    

    正如 Aaron 所建议的,一项改进是让“!define”不区分大小写,这意味着无论用户键入“!Define”还是“!DeFInE”,两者都将被机器人。为此,我们可以使用.lower()(或任何其他统一大写函数)。这使得字符串中的所有字符都小写。要使用它,我们将检查用户消息的小写字母的第一个单词是否与“!define”(小写字母)相同。像这样:

    if message.content.split()[0].lower() == "!define"
    

    这里同时发生了一些事情,首先我们.split()消息获取单词列表,然后访问列表索引为0的第一个单词,然后将其变为小写,最后我们将其与你的“!定义”关键字。

    由于这会检查消息中的第一个单词是否是“!define”,我们可以用它替换我们的.startswith() 函数。因此:

    @client.event
    async def on_message(message):
    words = message.content.split()
        if words[0].lower() == "!define":
           important_words = words[1:]
           await client.send_message(message.channel, wiki_summary(important_words))
    

    【讨论】:

    • 为了清楚起见,我会将 wikipedia 函数重命名为其他名称。 wiki_summary(search_term) 不太可能与模块 wikipedia 混淆。否则,您会在我输入的答案中找到所有要点。另一个建议是调用if message.content.lower().startswith('!define') 以确保用户在调用命令时无需过多担心大小写问题(为了幽默和捕捉机器人容易纠正的打字错误)。不妨在顶部声明words,然后是if words[0].lower() == 'define!'
    • 你说得对,我会相应地编辑我的答案,谢谢。很抱歉偷了你的答案。
    • 哈哈,不用担心。我们都在这里互相帮助,与经得起时间考验的答案相比,代表并不重要。
    【解决方案2】:

    您还应该将“@client.event”更改为“@client.listen()”,这样您的其他机器人命令才能正常工作。

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 2012-04-22
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2018-07-21
      • 2018-11-10
      • 1970-01-01
      • 2017-05-31
      相关资源
      最近更新 更多