Python discord bot has problems writing to textfiles - python

I'm currently working on a little discord bot. To host it for free, I'm using an application on heroku.com which is connected to my github. Everytime I restart the bot it gets some previously stored information from a textfile (works perfectly).
f = open("example_textfile.txt", "r")
example_list = dict(json.loads(f.read()))
f.close()
Everytime a list gets updated it should overwrite the textfile with the updated list like this (does NOT work):
f = open("example_textfile.txt", "w")
f.write(json.dumps(example_list))
f.close()
If I host the bot locally on my PC everything works perfectly (then I need the path, not just the name of the file). But when I host it with Heroku it can only read the files but not overwrite them. Does anyone know why this doesn't work? Or is there any alternative? Would be great if you could help me :D (And sorry for my bad english xD. I'm not native)

This should work
json.dump(example_list, open("example_file.txt", "w"))
The reason the write method may not be working for you is because
json.dumps() automatically writes to the file; That is the purpose of the method.
You're writing to the program is indicating that whatever json.dumps returns is what will get written to the file...
You should use json.dump | Is writes to the file intaking a dictionary instead!

Related

Copy discord messages into minecraft chat

I want to make a bot that copies messages from a discord server and then pastes them into the Minecraft chat. I'm not talking about rcon.
I copied some code that takes the last message and puts it in a text file:
async def copy(ctx):
with open("file.txt", "w") as f:
async for message in ctx.history(limit=1000):
f.write(message.content + "\n")
But I can't find this text file. I've tried putting it in the same folder with main.py and replacing "file.txt" with a full path to the file but it still won't work.
If I manage to get this whole "copy message into txt/variable" thing I should be able to finish the "paste stuff into chat" thing.
Please help me I'm stupid.
Not Python-specific, although you can try AutoHotkey for this (assuming you are dealing with 2 different apps consuming 2 different windows). AutoIt is also a solid alternative for this. Both are Windows specific and if you are using some other operating system, then good luck finding a proper macro recorder.
If you only need to output the text to a file, Selenium might be a better solution, given the plethora of options, as Discord can be opened in a browser too.
For a pure Python solution, you might look into PyWinAuto (again, Windows-specific).

How can I update data in a JSON file while using UptimeRobot?

I am creating an Economy Discord Bot using Python and I am hosting it on Replit and keeping it online using UptimeRobot. Sometimes, when people use my bot's economy commands, the data is not updated in the JSON file. I have observed that this only happens when my UptimeRobot monitor brings my bot online and not when I manually run the code. Does anyone know how to work around this?
Here is the code I am using to update the JSON file:
with open("data.json", "w") as file:
file.write(json.dumps(data))
The issue here might be with replit. Replit reboots your repl every once in a while, even if you have hacker plan or are using uptime robot. And sometimes the JSON file might not be saved. In this case the file reverts to its last saved state. As far as I'm aware, there is no way to work around this. The only way is using an external database like MongoDB.
I would dump your json a little differently.. PS. I have never seen this kind of thing happen so it might just be the way your json dump code is.
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
So we just open the json file data.json or whatever your json file is called. We define it as f and we dump your data or whatever you called it into f... the indent=4 just makes it more clean but you can get rid of it if you want.

Can't open a .txt file

So I was trying to learn the function open which is apparently easy to use. I copied a really simple code from a website to just open and read a file called "test.txt" with some text on it. I tried it both ways, not specifying the path (since it's in the same folder) and calling the whole path. None worked (FileNotFoundError). It's all in a server so that might be the problem but I'd still like a short explanation if that is the problem.
Go easy on the vocabulary please, I'm just taking the first steps.
On the image I tried to stack as much info as posible: link.
handle = open("test.txt")
data = handle.read()
print(data)
handle.close()
SOLUTION: I actually just removed the .txt from the text file. Now it's name is test and it is a text file and the code works. I previously moved the python file and text file from the server to the computer since a comment said it could be the problem, but after finding my solution i put it all back in the server and the program runs as well.
You are trying to open a file that is located on a network share (\\Servidor\profiles$\...) and you are accessing it by using the \\<server>\<sharename> syntax and not mounted as a Windows drive letter.
Some things you could try:
Copy the data from the network share to some local directory on your machine and run your script again.
Try mounting the network share under a "drive letter" and run again using this drive letter.
Try this answer: https://stackoverflow.com/a/7170008/8745384 if you really need to access it on the network share.

linux server hosting .py files that are reading .txt files but cant store in variable

I have a linux server.
It is reading files in a directory and doing things with the full text of the file.
I've got some code. it retrieves the file path.
And then I'm doing this:
for file in files:
with open(file,'r') as f:
raw_data = f.read()
Its reading the file just fine. And Ive used this exact code outside of the server and it worked as expected.
In this case, when run on the server, the above code is spitting out all the text to the terminal. But then raw_data == None.
Not the behavior I'm used to. I imagine its something very simple as I am new to linux in general.
But I'm wanting the text in the file to be stored in the 'raw_data' variable as a string.
is there a special way I am to do this on linux? Googling so far as not helped much and I feel this is likely a VERY simple problem.
User error.
I thought, due to my noob status in linux, that perhaps the enviroment was causing weird behavior. But buried deep in the functions that use the data from the files was a print statement i had used a while back for testing. That was causing the output to screen.
As for the None type being returned. It was being returned by another subfunction that had a try/except block in it and was failing. The variable being referenced had the same name (raw_data). So i thought it came from the file read. But it was actually from elsewhere.
thanks all who stopped by. User error for this one.

Downloading CSV file from website/server with Python 3.X

Programming beginner here. So for my very first project I was able to make a quick python script that downloaded files from this website:
http://www.wesm.ph/inner.php/downloads/market_prices_&_schedules
I noticed that the link address of the to-be-downloaded file
followed a pattern.
(http://wesm.ph/admin/downloads/download.php?download=../csv/mpas/XXXXX/XXXX.csv)
With some string concatenation and using the datetime module, I was able to create the HTML string of the csv file. After which, I just would use the:
urllib.request.urlopen(HTMLlink).read()
and save it with something like:
with open('output.csv', "w", newline='') as f:
writer = csv.writer(f)
writer.writerows(fullList)
It used to work - now it doesn't. I noticed however whenever I clicked the 'Generate Report' button and THEN run the script, the script would generate the output file. I'm not sure why this works. Is there a way to send a request to their server to generate the actual file? Which module, or commands should I use?
Most likely those files are only temporarily stored on that webserver after you click 'Generate Report'.
In order to grenerate new ones, there might even be a check (in JavaScript or using Cookies, Session-ID), to see if the generation of the new link/file is asked from a human, or a bot.
You might also want to check the HTTP return code (or even the full returned headers to see what exactly the server is answering).

Categories