Hello. My name is Arthur. I am new to coding. I just started using Python and am addicted to it. I wrote a code that sends a message every 10 minutes to a Telegram group. I want to change the code so that it gets the messages from a Google Sheets document instead of a list in the code itself. This is the code that I have now:
resp = requests.get(base_url, data = parameters)
print(resp.text)
How would I change this code so that I can send the messages from a Google Sheets document instead of writing a list in the code because the list of messages is well over a hundred messages and I’d rather use a Google Sheets document instead of typing it all into the code. Thank you.
Hi Arthur, That’s great you’re learning Python. I hope you discover many worthwhile applications of it, as well as building Telegram bots.
Anyway, the simplest thing to do is download the Google Sheets document as a local plain text file with each message on a new line. Then for message in messages can be replaced with
with open(file,'rt') as f:
for message in f:
And indent everything in the for loop in another level.
If the document is live (frequently updated), then it’s necessary to find a library (or a method to do it with requests) that lets you read Google Sheets documents from Python.
I’d just download the file and store all the messages locally at the first opportunity. But no doubt there are more sophisticated ways.
If the goal of the Google Sheets is just to separate data from code, you can just have those messages live in a text file next to the code. The file would look like:in your code:
message 1
message 2
message 3
and to access it in your code:
with open('messages.txt') as f:
messages = f.read().splitlines()
That would give you a list of the messages. If you need it to be updatable from afar or by multiple people, then Google Docs is a possibility (there are others I’m sure) and, as @JamesParrott said, you should look for a library that gives you API access.
I hope this helps!
NB - To format your code (which will help make sure that the indents are preserved, among other things,) you should use markdown and put the code in a block with ``` on the line above and below the block. It will make it easier for people to see any potential issues in the code.
Thank you all very much. I really appreciate your help. I was able to write a complete working code. It’s a code of fifty messages that sends a message every fifteen minutes and loops continuously.
Interesting concept! Does the Google API also check to see if the user is signed in and also has read access for the online Google Sheet? That would explain why there was no sign in info in the sample program itself here.