Python discord bot - 关于消息拆分和更改

时间:2018-01-10 22:50:50

标签: python string bots discord

我是编码的新手,我雄心勃勃,开始编写一个通过邮件内容触发的不和谐机器人,我已经用随机答案管理了一些简单的工作命令,但是当时与我的朋友交谈我得到了使用用户发送的部分消息作为机器人发回的消息的一部分的想法......好吧,我在火车上遇到的问题很明显,因为我可以&# 39;弄清楚我在下面的代码中做错了什么:

@client.event
async def on_message(message):
     if "buy me" in message.content(pass_context=True):
        async def quote(ctx):
           split_parts = quote.split(' ') # splits the content by the space, making a list
           # split_parts[0] would be "buy"
           # split_parts[0] would be "me"
           # etc
          split_parts.pop(0)
          split_parts.pop(0)
          new_quote = " ".join(split_parts)
          buyquotes = ["Buying you", "No, I will not buy you"] #etc
          var = int(random.random() * len(buyquotes))
          await client.send_message(message.channel, "{0} {1}".format(buyquotes[var], new_quote))

一切都很好,但是当我试图触发机器人它告诉我TypeError:' str'我不是一个可调用的对象,我环顾四周并发现了一些类似的问题(我已根据答案尝试修复我的错误)但我完全不知道我做错了什么(或者是什么我试图做甚至可能)。任何帮助都会非常感激,我很想知道这样的事情是否真的有效。

Ignoring exception in on_message
Traceback (most recent call last):
 File "/usr/local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "nyola.py", line 11, in on_message
    if "buy me" in message.content(pass_context=True):
TypeError: 'str' object is not callable

添加此内容:我的目标是尝试接收一条消息,例如"给我买一台电视"用"买我"触发机器人单词,删除单词"买我"然后将剩余的单词添加到机器人消息的末尾,而不是"购买你"这将是"给你买电视"

现在已经解决了这个问题:

if "buy me" in message.content:
       quote = message.content
       split_parts = quote.split(' ') # splits the content by the space, making a list
       # split_parts[0] would be "buy"
       # split_parts[0] would be "me"
       # etc
       split_parts.pop(0)
       split_parts.pop(0)
       new = " ".join(split_parts)
       buyquotes = ["Buying you", "Contacting Amazon looking to buy you", "No, I will not buy you", "You can't have", "There is no need for", "I am not buying you","I can't believe you would ask me for"]
       var = int(random.random() * len(buyquotes))
       await client.send_message(message.channel, "{0} {1}".format(buyquotes[var], new))

原始代码中存在多个错误,现在可以使用,但并不完美,但它确实有效。

2 个答案:

答案 0 :(得分:2)

您需要了解一些事项:

on_message()是一个简单地传递整个Message对象的事件。

其次,对于消息的字符串,它是message.content。不要使用函数调用()

第三,您不应该在async def内创建新的on_message。如果你真的只是想回复一条说“买我”的消息,这里有一个回复那些以“买我”开始他们的消息的人的例子。由于我不能100%确定你的最终目标究竟是什么,所以我只想给你一个你可以建立起来的例子:

@client.event
async def on_message(msg):
    if msg.content.startswith("buy me"):
        responses = ['meh', 'no thanks brudda']
        choice = random.choice(responses)
        await client.send_message(msg.channel, choice)

旁注:这似乎是你在使用discord.py的“异步”版本。您应该考虑转移到“重写”库,这将改变许多这些API调用。此外,您应该使用commands.ext,但考虑到您还没有很好地掌握Python,使用on_message()应该足够好了。

在当前状态下,您的代码还有很多话要说,但这足以让您朝着正确的方向前进。

答案 1 :(得分:1)

message.content

根据此处的文档https://github.com/Rapptz/discord.py/blob/async/discord/message.py显示为字符串。这意味着传递一个参数,两个括号是超级的,你可以放弃它们。