Forums

Running a Telegram Bot

Hi everyone, I am trying to run a telegram bot for personal use. Is there a way to simulate always on tasks on free plan? Or is there a way to trigger the bot to start/ stop with an API endpoint? Love to hear your thoughts. Novice here learning Python and more.

You could run the bot in a console, but then it wouldn't run 24/7 -- if the console server where you were running it was restarted for system maintenance (which would likely happen every day or two) then you'd have to manually restart it. But perhaps that would be enough for your use case?

If not, you could consider creating it using the webhooks interface for Telegram -- we have a (admittedly somewhat old) blog post about how to do that.

Thank you giles for the link! At least I have a direction.

I thought the same as you, but after considering it the best solution is to pay the hacker plan, it is just 5 usd a month.

@legolahs Glad to hear you're on the track!

@diegomedflo24 Sure, paid plan offers other useful features, too.

I put multiple different codes in my console and it doesn't respond to start or greet or anything and when I coded it on termux I had no issuez, what am I doing wrong I have the $5 havker account.

What happens in the console when you run your code?

It sayz modulenotfound , module name telegram not found.

Line 2 sayz import telegram import Update which iz the line that haz the error

You need to install the modules that your code uses: https://help.pythonanywhere.com/pages/InstallingNewModules/

Thank you, it started awaiting messagez after installing the proper modulez , the bot still isn't responding even tho I defined the variable BOT_TOKEN in the .env' file that is located in the path home/my username/.env

If there is a way to check the connection do so.

I would recommend digging in to Telegrams documentation for ping or relevant test events that would allow you to test your connection.

There might be an issue with having a Free account. So if your connection is blocked because of it, you might need to use the proxy instead. I'd recommend checking the documentation.

Ok also I have the $5 hacker account

Did you try any connection tests? What kind of errors do you see?

Yes and theze are the results

can_join_groups":true,"can_read_all_group_messages":false,"supports_inline_queries":false,"can_connect_to_business":false,"has_main_web_app":false}}

All my bot can do iz join groups, everything sayz false, idk if I have to add json commandz and I how I didn't have to pay for a ping service

Where are those results coming from? It does not look like something related to PythonAnywhere specifically.

Thoze rezults are found within the telegram documentz , in order to test connection/requests...

All queriez to the Telegram Bot API must be served over HTTPS and need to be presented in this form: https://api.telegram.org/bot<token>/METHOD_NAME

After placing my bot token next to bot in the address above it gave me the json rezults I posted.

My question now iz what print commandz should I add to my code so I can see what it iz doing?

Prints that will tell you the information you need. For instance, if you want to know that a particular piece of code ran, add a print before and after that tells you that. You can also print any variables that might affect which pieces of code run.

Ok im still technically a noob, where do i place the print statmentz?

I made sure to indent and for all of them it sayz syntax error...

I did print("BOT_TOKEN")

I already got print statements for startimg bot etc....

If you have a syntax error it should point to the place in your code where that error happens.

print("BOT_TOKEN") would print BOT_TOKEN, not the value of it, to print the value you need to print(BOT_TOKEN)

I'm redoing my entire code again doez it matter if I run the main.py file from my venv or the root?

Could you expand your question with example command? It's hard to guess what you mean exactly. What " run from venv" and "rooot" mean in that context.

I re did my entire code and now the only issue I have iz that it sayz that port 5000 iz already in use. What is the best solution? Should I go to port 5001 and kill port 5000?

That would not work that way as whatever port you use it would not be visible to the outside world. The only way to make something accessible from the outside is to deploy it as a web app.

Ok well how can I properly create a web app and deploy my bot uzing Pythonanywhere? I'm new to all of this but very motivated.

Take a look at https://blog.pythonanywhere.com/148/

I looked at the blog and followed along, now it sayz I have a attribute error with one line where it dealz with telegram.utils. I of course made the web app so I can get it set up with a web hook. I set it up with Python 3.13. how can I fix this?

The instructions were for a particular version of telepot. We'll have to update the docs at some point. In the meantime, you can check on PyPI what version was current at the time of the blog post and install that instead, or you can check the docs for telepot to see what happened to the attribute that is missing and modify the code to match.

I have Python 3.13 installed and I guess that might be the issue, I had to get rid of telepot for telebot

[formatted by admin]

from flask import Flask, request
import telegram
import urllib3
from telebot.credentials import bot_token
import secrets
webhook_secret = secrets.token_urlsafe(32)
import uuid
webhook_secret = str(uuid.uuid4())

# Initialize global variables
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)

# Proxy configuration (if needed)
proxy_url = "http://proxy.server:3128"
proxy_manager = urllib3.ProxyManager(proxy_url)
telegram.utils.request.Request(proxy_url=proxy_url)

# Flask app setup
app = Flask(__name__)
secret = "A_SECRET_NUMBER"  # This should be more secure in production

# Webhook setup - fix the URL format
WEBHOOK_URL = f"https://PhantomZ.pythonanywhere.com/{secret}"
bot.setWebhook(WEBHOOK_URL)

@app.route(f'/{secret}', methods=['POST'])
def telegram_webhook():
    update = request.get_json()

    if "message" in update:
        chat_id = update["message"]["chat"]["id"]

        if "text" in update["message"]:
            text = update["message"]["text"]
            # Echo the message back
            bot.send_message(chat_id=chat_id, text=f"You said: {text}")
        else:
            bot.send_message(chat_id=chat_id, text="I only understand text messages")

    return "OK"

What is the error you get?

AttributeError: module 'telegram' has no attribute 'utils'

The error comez from line 17

telegram.utils.request.Request(proxy_url=proxy_url)

You need to check against the package's documentation to see if the API of the version you use hasn't changed for example.

No it hasn't changed, it'z starting to seem as if it iz difficult to launch a telegram bot with Pythonanywhere.

Which version of telegram do you use?

I believe it'z version 20 as far az the library goes

Does the docs of that version match the interface you try to use?

I finally got it to respond!!!! Thank you for the attentive support, I hope to do many more projects with this service.