[Python] How to solve this error (POST / HTTP/1.1" 405) in a telegram bot using python flask...

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a python telegram bot that manage my team group, adding tasks and reminders. I deployed the code on render.com, and this error: (POST / HTTP/1.1" 405) appears in it's logs. notice: "method not allowed" is not mentioned in the logs..

    [​IMG]

    Here is the code:

    #modules

    import os
    import json
    import requests
    from flask import Flask, request
    from pymongo import MongoClient
    from apscheduler.schedulers.background import BackgroundScheduler
    from apscheduler.triggers.date import DateTrigger
    from dotenv import load_dotenv
    from datetime import datetime

    #imp.data
    load_dotenv()
    BOT_TOKEN = os.getenv("BOT_TOKEN")
    MONGO_URI = os.getenv("MONGO_URI")
    WEBHOOK_URL = os.getenv("WEBHOOK_URL")
    AUTHORIZED_USERS = list(map(int, os.getenv("AUTHORIZED_USERS", "").split(",")))

    # setting flask

    app = Flask(__name__)
    # إعداد قاعدة البيانات MongoDB
    client = MongoClient(MONGO_URI)
    db = client["task_manager"]
    tasks_collection = db["tasks"]
    reminders_collection = db["reminders"]

    # Task Scheduler
    scheduler = BackgroundScheduler()
    scheduler.start()

    #setting webhook
    @app.route("/", methods=["GET", "POST"])
    def home():
    if request.method == "POST":
    return "This endpoint is not for webhooks!", 405
    return "Bot is running!"

    @app.route("/webhook", methods=["POST"])
    def webhook():
    update = request.get_json()
    if update:
    handle_message(update.get("message", {}))
    return "", 200 # Always return a successful response
    def handle_message(message):
    chat_id = message["chat"]["id"]
    user_id = message["from"]["id"]
    text = message.get("text", "")

    if text.startswith("/addtask") and user_id in AUTHORIZED_USERS:
    add_task(chat_id, user_id, text)
    elif text.startswith("/viewtasks"):
    view_tasks(chat_id)
    elif text.startswith("/setreminder") and user_id in AUTHORIZED_USERS:
    set_reminder(chat_id, user_id, text)
    else:
    send_message(chat_id, "❌ أمر غير معروف أو ليس لديك الصلاحية!") #translation = Unknown command or you do not have permission

    def add_task(chat_id, user_id, text):
    try:
    _, title, desc, due_date, priority = text.split("|")
    task = {
    "title": title.strip(),
    "description": desc.strip(),
    "due_date": due_date.strip(),
    "priority": priority.strip(),
    "created_by": user_id,
    "created_at": datetime.utcnow()
    }
    tasks_collection.insert_one(task)
    send_message(chat_id, "✅ تم إضافة المهمة بنجاح!")# Tasks added
    except:
    send_message(chat_id, "❌ صيغة غير صحيحة! استخدم:\n`/addtask | العنوان | الوصف | YYYY-MM-DD | الأولوية (Low, Medium, High)`") #Not the best way I'll fix it later.

    def view_tasks(chat_id):
    tasks = list(tasks_collection.find())
    if not tasks:
    send_message(chat_id, " لا توجد مهام حاليًا.")#not tasks certainly
    return

    message = " **قائمة المهام:**\n" #tasks list
    for task in tasks:
    message += f"\n **{task['title']}**\n {task['description']}\n {task['due_date']}\n⚠️ {task['priority']}\n---"

    send_message(chat_id, message)

    def set_reminder(chat_id, user_id, text):
    try:
    _, task_title, remind_time = text.split("|")
    remind_time = datetime.strptime(remind_time.strip(), "%Y-%m-%d %H:%M")

    reminder = {
    "task_title": task_title.strip(),
    "remind_time": remind_time,
    "chat_id": chat_id
    }
    reminders_collection.insert_one(reminder)

    scheduler.add_job(
    send_reminder,
    trigger=DateTrigger(run_date=remind_time),
    args=[chat_id, task_title]
    )

    send_message(chat_id, "⏰ تم تعيين التذكير بنجاح!")#reminder set
    except:
    send_message(chat_id, "❌ صيغة غير صحيحة! استخدم:\n`/setreminder | عنوان المهمة | YYYY-MM-DD HH:MM`")

    def send_reminder(chat_id, task_title):
    send_message(chat_id, f" تذكير بالمهمة: **{task_title}**")

    def send_message(chat_id, text):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
    requests.post(url, json=payload)

    if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
    requests.get(f"https://api.telegram.org/bot{TOKEN}setWebhook?url=https://testbot-zppg.onrender.com")


    I have tried to ask gpt but all solutions didn't worked, setting webhook was in the beginning but didn't work also.

    Can you help Guys,the bot is not responding, I have tried for 3 days and more than 40 commits and tries.

    Continue reading...

Compartilhe esta Página