Reputation: 193
I've made a python program that connects to an API using 2 different arguments, on which it asks for an input, and then exports the results to a text file.
I wanted to turn it into a discord bot that will do the exact same thing but will now send said file on the DM of the user who uses the command.
The part of the original contacting the API is:
# 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()
And when it came to exporting I was using:
with open("results.txt", "w") as f:
for dictionary in results:
f.write(dictionary['line'] + "\n")
On the first piece of code, you can see me asking for an input. It won't be needed because the bot will be getting it from the command, I tested if that was correct by making the bot send a message with the arguments and it's sending everything correctly. Here's the code of that message:
@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))
In case the full code of the bot is needed, this is what I have so far:
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)
The lines arg1 = "login" and arg2 = "teste" were just for testing, since I get the error "NameError: name 'arg1' is not defined", for some weird reason it also ain't pulling the argument correctly from the message.
Upvotes: 1
Views: 10246
Reputation:
If you want to write some text in file and send this file to user, you can use this example:
@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. Info about discord.File in docs
Upvotes: 7