首页 > 解决方案 > 如何实现 inp = input 并打印到 discord.py 代码?

问题描述

Python 3.6 张量流 1.15

我是 python 的初学者,我正在尝试将此聊天机器人“移植”到不和谐服务器中的聊天中,但我不知道该怎么做。我尝试了多种解决方案,例如将 inp = input("") 更改为 message.content == () 或 message.content.find == () 并尝试让机器人读取频道中的消息而不是直接读取信息。

这是我要更改的代码的原始部分,它在 CMD 中工作:

    print("(say quit to leave the bot)!")
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break

        results = model.predict([bag_of_words(inp, words)])
        results_index = numpy.argmax(results)
        tag = labels[results_index]

        for tg in data["intents"]:
            if tg['tag'] == tag:
                responses = tg['responses']

        print(random.choice(responses))

chat()

我的一些尝试只是让我尝试将我在不和谐文档中找到的一些代码直接放在我的代码中,我开始导入不和谐并弄乱我找到的代码

    print("(say quit to leave the bot)!")
    while True:
async def on_message(message):
    if message.content == "":
    if inp.lower() == "quit":
            break
    results = model.predict([bag_of_words(inp, words)])
        results_index = numpy.argmax(results)
        tag = labels[results_index]

        for tg in data["intents"]:
            if tg['tag'] == tag:
                responses = tg['responses']
await message.channel.send(random.choice(responses))

在我看来,这是有道理的,而且我走的是正确的道路,我尝试了很多以不同方式定位这些行并将 message.content 更改为 Client.wait_for() 但从未奏效。

这是完整的工作代码以获得更好的上下文>> https://gist.github.com/FlameinfirenBr/4db6fc5e736796233bb85b3422fac8a3

第一次在这里发帖,所以我真的不知道该提供什么信息,所以问我任何问题,我会尽量快速回答。

编辑:我已经在我的代码中完成了机器人实现,机器人上线并以简单的命令做出反应,例如

import discord


def read_token():
    with open("token.txt", "r") as f:
        lines = f.readlines()
        return lines[0].strip()


token = read_token()
client = discord.Client()

@client.event
async def on_message(message):
    if message.content == "!hi":
    await message.channel.send("hello")
client.run(token)

我阅读了 discord.py 重写文档的一些复杂部分,但没有看到任何对我的“问题”有用的东西,似乎这只是一个基本的“问题”,我无法弄清楚如何解决。

标签: pythondiscord.py-rewrite

解决方案


对于初学者来说,在 discord.com/developers/ 上制作一个机器人

导入 discord 和 from discord.ext 导入命令(相信我,它可以节省时间)。连接您的机器人后,您还可以连接一个存储用户“答案”的数据库,或者将其保存在 json 中,无论对您有用。正如其他人所说,如果您编写了代码,您可能应该知道在哪里放置查找上下文和发送消息命令。

顺便说一句,“..我尝试了多种解决方案,例如将 inp = input("") 更改为 message.content == () 或 message.content.find == ()..”尝试使用异步和机器人事件进行试验。这将是解决此问题的常用方法。

这是一个你应该开始使用更多的链接,它告诉你你需要知道的一切以及更多;) DiscordPy Docs

编辑:

尝试这个:

@client.event
async def on_message(message):
    if message.content.lower() == "quit": #this will only prevent the bot from going on if the message is 'quit', I say you make some kind of a command to talk to the bot or store data somewhere if the bot is inactive or not
            break
    else:
        results = model.predict([bag_of_words(inp, words)])
            results_index = numpy.argmax(results)
            tag = labels[results_index]
    
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']
await message.channel.send(random.choice(responses))

推荐阅读