Discord.py-在DM上发送文本文件

时间:2020-06-26 09:02:03

标签: python python-3.x discord discord.py discord.py-rewrite

我制作了一个python程序,该程序使用2个不同的参数连接到API,并在其上请求输入,然后将结果导出到文本文件中。

我想把它变成一个discord bot,它可以做完全相同的事情,但是现在会在使用该命令的用户的DM上发送该文件。

原始联系API的部分是:

# Setting the search type input
api.set_type(method)

# Getting the search query input
query = input("Please enter your search query ")

# Setting the search query input
api.set_query(query)

# Getting the results
results = api.lookup()

在导出时,我使用的是:

with open("results.txt", "w") as f:
        for dictionary in results:
            f.write(dictionary['line'] + "\n")

在第一段代码上,您可以看到我要求输入。不需要它是因为该机器人将从命令中获取它,我通过使该机器人发送带有参数的消息并正确发送了所有内容来测试了该命令是否正确。 这是该消息的代码:

@bot.command(name='search', help='Search for an e-mail, password or keyword')
async def args(ctx, arg1, arg2):
    await ctx.send('You sent {} and {}'.format(arg1, arg2))

万一需要机器人的完整代码,这就是我到目前为止的内容:

TOKEN = ""

bot = commands.Bot(command_prefix='!')

@bot.command(name='search', help='Search for an e-mail, password or keyword')
async def args(ctx, arg1, arg2):
    await ctx.send('You sent {} and {}'.format(arg1, arg2))



arg1 = "login"
arg2 = "teste"


# Now onto implementing and using the API

api = LeakCheckAPI()
api.set_key("")
ip = api.getIP() 
limits = api.getLimits() 
api.set_type(arg1) # setting the search method
api.set_query(arg2) # setting what we should search
results = api.lookup() # getting the results

bot.run(TOKEN)

arg1 =“ login” arg2 =“ teste” 这两个行仅用于测试,因为出现错误“ NameError:未定义名称'arg1' “,出于某些奇怪的原因,它也没有从消息中正确提取参数。

1 个答案:

答案 0 :(得分:1)

如果要在文件中写入一些文本并将其发送给用户,则可以使用以下示例:

@client.command(pass_context=True)
async def sendtext(ctx, arg1, arg2):
    # write to file
    with open("result.txt", "w") as file:
        file.write('arg1 = {0}, arg2 = {1}'.format(arg1, arg2))
    
    # send file to Discord in message
    with open("result.txt", "rb") as file:
        await ctx.send("Your file is:", file=discord.File(file, "result.txt"))

结果:

Result

P.S。文档中有关discord.File的信息