Python与大Python的分裂

2024-10-01 09:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个新的编码,我有了雄心壮志,开始写一个不和谐的机器人,这是通过信息内容触发的,我已经管理了一些简单的工作命令和随机答案,但当我和我的朋友交谈时,我想到了用用户发送的消息的一部分作为机器人返回的消息的一部分。。。好吧,说到python,我就是个累赘,很明显,我不知道我在下面的代码中做错了什么:

@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'不是一个可调用的对象,我环顾四周,发现了一些类似的问题(我试图根据答案来纠正我的错误),但我完全不知道我做错了什么(或者我想做的事情是否有可能)。任何帮助都将不胜感激,我很想知道这样的东西是否真的有用。在

^{pr2}$

加上这个:我的目标是尝试获取像“买我一台电视”这样的消息,用“买我的”这个词来触发机器人,删除“买我的”这个词,然后在机器人的信息末尾添加剩余的单词,这样就不是“买你的”而是“给你买台电视”

现在这个问题解决了:

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))

在原始代码中有多个错误,它现在可以工作了,它不是完美的,但是它可以工作。在


Tags: theyoumessagenew机器人buybecontent
2条回答

这里有几件事你需要了解:

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

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

第三,您不应该在on_message内部创建一个新的async def。如果你真的只想回复一个写着“买我的”的信息,这里有一个例子来回应那些以“买我”开头的人。因为我不能百分之百确定你的最终目标是什么,我只想给你举一个例子,你可以以此为基础:

@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)

附带说明:这看起来像是在使用的“异步”版本不和.py. 你应该考虑转移到“重写”库,这将改变很多API调用。另外,您应该使用commands.ext,但是考虑到您还没有很好地掌握Python,使用on_message()应该就足够了。在

关于代码的当前状态,还有很多要说的,但这应该足以将您推向正确的方向。在

message.content

根据文档https://github.com/Rapptz/discord.py/blob/async/discord/message.py显示为字符串。这意味着传递一个参数和两个圆括号是多余的,您可以删除它们。在

相关问题 更多 >