Telebot not responding to requests with FLask server - flask

I am trying to deploy my telegram bot to Heroku using Flask. ALthough I followed the tutorials and set up everything the same I am not getting any result and my bot is not responding.
import requests
import pandas as pd
import telebot
from telebot import types
import random
import os
from flask import Flask, request
from requests.models import MissingSchema
URL_HEROKU = f"some_url"
TOKEN = os.environ['TOKEN']
bot = telebot.TeleBot(TOKEN, parse_mode=None)
app = Flask(__name__)
#bot.message_handler(commands=['start'])
def start(message):
#Init keyboard markup
msg = ''' Hello, how are you?'''
bot.reply_to(message, msg)
#bot.message_handler(commands=['random'])
#bot.message_handler(regexp=r'random')
def send_some(message):
bot.send_message(message.chat.id, text='Hello')
#app.route('/' + TOKEN, methods=['GET'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200
#app.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url= URL_HEROKU + TOKEN)
return "!", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
My Procfile is:
web: python telebreed.py
and my requirements.txt:
Flask==2.0.2
gunicorn==20.1.0
pandas==1.2.2
pyTelegramBotAPI==4.6.0
requests==2.26.0
do you see any mistake ? When I open my app in Heroku I only see "!" which is the character defined in getMessage() method.

Related

subprocess.Popen line in flask app not running on pythonanywhere while it work on local machine.. any idea why or how to catch error?

subprocess.Popen line (40) in flask app not running on pythonanywhere while it works on local machine.. tried different variation of the subprocess line but no luck. no error shown in error logs in pythonanywhere.
any idea why there is a difference to functionality on pythonanywhere vs local machine and how to fix or how to catch error of subprocess?
enter image description here
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
import yaml
from subprocess import Popen, PIPE
from threading import Thread
import time
import subprocess
app = Flask(__name__)
# config db
db = yaml.full_load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'xxx'
app.config["MYSQL_USER"] = "xxx"
app.config["MYSQL_PASSWORD"] = "xxx"
app.config["MYSQL_DB"] = "xxx"
mysql = MySQL(app)
#app.route("/", methods=["GET", "POST"])
def index():
if request.method =="POST":
#fetch form data
userDetails=request.form
title=userDetails["title"]
location=userDetails["location"]
radius=userDetails["radius"]
email=userDetails["email"]
cur = mysql.connection.cursor()
cur.execute("INSERT INTO requests(title, location, radius, email) VALUES(%s, %s, %s, %s)", (title, location, radius, email))
mysql.connection.commit()
cur.close()
subprocess.Popen(['python', 'file.py'])
return render_template('donenew.html')
return render_template("indexnew.html")
if __name__ == "__main__":
app.run(debug=True)

how to add app object in flask's main file

I want to add app object once in main.py which can be used everywhere, but route does not work in this way. What is the issue here?
main.py
from flask import Flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(debug=True)
routes.py
from main import app
#app.route("/", methods = ["GET"])
def home():
return "hi"
However, if declare app = Flask(name) in routes.py and import app in main.py it is working all fine. Working scenario.
main.py
from routes import app
if __name__ == "__main__":
app.run(debug=True)
routes.py
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route("/", methods = ["GET"])
def home():
return "hi"
my objective is to define app in main.py and import it in other files, but getting issues.
main.py is not even aware that routes.py exists. Import your routes.py file after initializing your app.
# main.py
from flask import Flask
app = Flask(__name__)
import routes # needed
if __name__ == "__main__":
app.run(debug=True)
# routes.py
from __main__ import app
#app.route("/")
def home():
return "hi"

Using sessions in flask

I want to add items in session and delete sessions in flask. Can anyone help with the code?
from flask import Flask, session
app = Flask(__name__)
#app.route('/home')
def hello world():
return "Hello world"
You can import session from flask and use it
from flask import Flask, session
app = Flask(__name__)
#app.route('/use_session')
def use_session():
if 'item' not in session:
session['items'] = {'item':'item2'}
return session.get('items')
#app.route('/delete_session'):
def delete_session():
session.pop('item', None)
return "removed item from session"

Simple Flask example with pytest and application factory does not work

I am new to flask and I have set up a simple flask example and two tests using pytest(see here). When I let run only one test it works, but if I run both tests it does not work.
Anyone knows why? I think I am missing here some basics of how flask works.
code structure:
app/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
with app.app_context():
from app import views
return app
app/views.py
from flask import current_app as app
#app.route('/')
def index():
return 'Index Page'
#app.route('/hello')
def hello():
return 'Hello World!'
tests/conftest.py
import pytest
from app import create_app
#pytest.fixture
def client():
app = create_app()
yield app.test_client()
tests/test_app.py
from app import create_app
def test_index(client):
response = client.get("/")
assert response.data == b"Index Page"
def test_hello(client):
response = client.get("/hello")
assert response.data == b"Hello World!"
The problem is with your registration of the routes in app/views.py when you register them with current_app as app. I'm not sure how you would apply the application factory pattern without using blueprints as the pattern description in the documentation implies they are mandatory for the pattern:
If you are already using packages and blueprints for your application [...]
So I adjusted your code to use a blueprint instead:
app/main/__init__.py:
from flask import Blueprint
bp = Blueprint('main', __name__)
from app.main import views
app/views.py -> app/main/views.py:
from app.main import bp
#bp.route('/')
def index():
return 'Index Page'
#bp.route('/hello')
def hello():
return 'Hello World!'
app/__init__.py:
from flask import Flask
def create_app():
app = Flask(__name__)
# register routes with app instead of current_app:
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
Then your tests work as intended:
$ python -m pytest tests
============================== test session starts ==============================
platform darwin -- Python 3.6.5, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /Users/oschlueter/github/simple-flask-example-with-pytest
collected 2 items
tests/test_app.py .. [100%]
=============================== 2 passed in 0.02s ===============================

How to run a Flask app on CherryPy WSGI server (Cheroot) using HTTPS?

I am running a Python 2.7 Flask app on CherryPy Cheroot WSGI server usinh HTTP now as below.
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from MyFlaskApp import app
d = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 80), d)
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()
What would I have to to move to HTTPS from here?
I found below instruction, but it does not seem to applicable to my application.
from cheroot.server import HTTPServer
from cheroot.ssl.builtin import BuiltinSSLAdapter
HTTPServer.ssl_adapter = BuiltinSSLAdapter(
certificate='cert/domain.crt',
private_key='cert/domain.key')
Can I apply above sample to my Flask app on Cheroot? If not, what would be a simple example for Flask app on Cheroot for HTTPS?
I figured out the necessary modification.
Not much information on Flask app on Cheroot with https, so I thought I'd share it.
from cheroot.wsgi import Server as WSGIServer
from cheroot.wsgi import PathInfoDispatcher as WSGIPathInfoDispatcher
from cheroot.ssl.builtin import BuiltinSSLAdapter
from MyFlaskApp import app
my_app = WSGIPathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 443), my_app)
ssl_cert = "[path]/myapp.crt"
ssl_key = "[path]/myapp.key"
server.ssl_adapter = BuiltinSSLAdapter(ssl_cert, ssl_key, None)
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()