Creating a Telegram Bot with File-Based Responses

Hey everyone! I’m learning Python by creating a Telegram bot on Google App Engine. I found a cool project online, but I want to try something different. Instead of hardcoding responses, I aim to use a text file to supply the bot’s answers.

My file looks like this:

/fact1#I'm a robot
/fact2#I'm not human
/fact3#Stop talking to me

I modified the code to read the file:

d = {}
with open('data.txt') as f:
    for line in f:
        (key, val) = line.strip().split('#')
        d[key] = val

if text in d:
    reply(d[text])

However, my bot stopped replying. Could someone help me identify what I’m doing wrong and suggest a fix?

I’ve worked with Telegram bots before, and your approach is on the right track. One thing to consider is that Google App Engine can be tricky with file operations. Have you checked if the file is actually being read? You might want to add some logging to verify this.

Another potential issue could be with how you’re handling the incoming ‘text’ variable. Make sure it matches exactly with the keys in your dictionary, including the leading ‘/’. You might want to add a check to see if the text starts with ‘/’ and if not, add it before checking the dictionary.

Also, consider error handling. What happens if the file can’t be read or if the text doesn’t match any key? Adding some basic try-except blocks could help diagnose issues and prevent the bot from completely stopping.

Lastly, if you’re still having trouble, you might want to look into using a database instead of a text file. It’s generally more robust for this kind of application, especially on cloud platforms like GAE.

I encountered a similar issue when working on a file-based response system for my Telegram bot. The problem might be in how you’re handling the file path. Google App Engine has a specific file structure, and the standard file operations might not work as expected.

Try using the ‘os’ module to construct the correct file path:

import os

file_path = os.path.join(os.path.dirname(__file__), 'data.txt')
with open(file_path, 'r') as f:
    # Rest of your code here

Also, ensure your ‘data.txt’ file is included in your app.yaml file under the ‘includes’ section. If the issue persists, consider using Google Cloud Storage for file operations in App Engine. It’s more reliable for handling external files in this environment.