Deploying Python Telegram Bot on Heroku - heroku

I am trying to deploy my python telegram bot on heroku. Everything builds fine and heroku said its deployed successfully. However, when I tried the bot in telegram, it does not work. I have attached the deployment code below. Can someone help please? Thanks. My Procfile contains this: web: python3 encouragements.py
`import os
TOKEN = "Token"
PORT = int(os.environ.get('PORT', '5000'))
updater = Updater("Token")
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path="Token")
updater.bot.setWebhook("https://xxx.herokuapp.com/" + "Token")
updater.idle()`

I found this article helpful when deploying a Telegram bot on Heroku: Creating Telegram Bot and Deploying it to Heroku (make sure the code is up to date by comparing it to the docs guide to Version 12.0)
Based on the article provided above, I've tried to reproduce your case with the following setup:
encouragements.py:
from telegram.ext import Updater, CommandHandler, CallbackContext
from telegram import Update
import os
TOKEN = ""
HEROKU_APP_NAME=""
# def run(updater):
# updater.start_polling()
def run(updater):
PORT = int(os.environ.get("PORT", "8443"))
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN))
def start_handler(update: Update, context: CallbackContext):
update.message.reply_text("Hello from Python!\nPress /random to get random number")
if __name__ == '__main__':
updater = Updater(TOKEN, use_context=True)
updater.dispatcher.add_handler(CommandHandler("start", start_handler))
run(updater)
Pipfile:
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
python-telegram-bot = "*"
[requires]
python_version = "3.7"
Procfile:
web: python encouragements.py
And telegram bot is indeed responding to /start message. I followed this article when deploying to Heroku: https://devcenter.heroku.com/articles/getting-started-with-nodejs
I would also recommend to check what is happening on Heroku's side:
heroku logs -t --app <your-heroku-app-name>
Logs should tell you if your token is in fact correct, if your dependencies where properly loaded, and if your code does not produce any error during runtime.
Let me know if it worked :)

Related

Tweepy Code Works in Pycharm, but not when Uploaded to Heroku

To staart, I am pretty new to coding and this is somewhat of a big project for me. I am trying to make a twitter bot that would run automatically, however, I keep getting "Unicode objects are not escapbable" as a result when running it on a Heroku sever.
The code works fine in Pycharm, but for some reason will not work when running on Heroku. Here is what the beginning looks like:
import tweepy
import statsapi
import time
import os
#enviroment variables
from dotenv import load_dotenv
load_dotenv()
#Keys
CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TOKEN_SECRET')
#
while True:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

How can I periodically delete the contents of a folder ("uploads") related to my flask app on heroku

I need to periodically delete files of an uploads folder on heroku in python.
I've tried the heroku scheduler but I am constantly getting a fileNotFound error which I am unable to fix.
from flask_script import Manager
from app import app
manager = Manager(app)
#manager.command
def hello():
folder_path = '/uploads/'
for file_object in os.listdir(folder_path):
file_object_path = os.path.join(folder_path, file_object)
if os.path.isfile(file_object_path):
os.unlink(file_object_path)
else:
shutil.rmtree(file_object_path)

Why won't my flask command work on Heroku?

I have a simple CLI took in Flask that I use to create dummy data. It works fine on my local machine but not on Heroku. Here's a terminal session:
(venv) $ flask create-dummy-data
(venv) $ git push staging master
Everything up-to-date
(venv) $ heroku run bash --remote staging
Running bash on ⬢ app-name... up, run.8533 (Free)
~ $ flask create-dummy-data
Usage: flask [OPTIONS] COMMAND [ARGS]...
Try "flask --help" for help.
Error: No such command "create-dummy-data".
Here's my app/cli.py file:
import lorem
from app import db
from app.models import Survey, Question, Option, Answer, Response
def register(app):
#app.cli.command()
def create_dummy_data():
"""Create lorem ipsum questions and answers for testing."""
survey = Survey()
db.session.add(survey)
for _ in range(3):
question = Question(survey=survey, category='likert', question=lorem.sentence())
db.session.add(question)
for _ in range (2):
question = Question(survey=survey, category='word', question=lorem.sentence())
db.session.add(question)
db.session.commit()
And my run.py file:
from app import create_app, db, cli
from app.models import Survey, Question, Option, Answer, Response
app = create_app()
cli.register(app)
#app.shell_context_processor
def make_shell_context():
return {'db': db,
'Survey': Survey,
'Question': Question,
'Option': Option,
'Answer': Answer,
'Response': Response
}
Why would this work locally but not on the Heroku shell?
It was the simplest thing: Heroku didn't have $FLASK_APP set in the staging environment's variables. Adding that allowed the command line tool to run.

How can we create a project on google cloud using python api client

I'm working on a project to automate google cloud setup, is there any way to create a google cloud platform project using Google-Api-Client for python?
Help me, please!
Thanks in advance!
Here's what I have tried:
From views.py
from google.cloud import resource_manager
...
client = resource_manager.Client()
# List down all gcp projects
for project in client.list_projects():
print(project)
new_project = client.new_project('project11-372', name='My new project')
new_project.create()
It list down all of my gcp projects but doesn't create new project.
Here's the error I have received:
File "/Users/abdul/Documents/IGui/rest/views.py", line 60, in post
new_project.create()
File "/Users/abdul/IstioVirEnv/lib/python3.6/site-packages/google/cloud/resource_manager/project.py", line 138, in create
data=data)
File "/Users/abdul/IstioVirEnv/lib/python3.6/site-packages/google/cloud/_http.py", line 293, in api_request
raise exceptions.from_http_response(response)
google.cloud.exceptions.Forbidden: 403 POST https://cloudresourcemanager.googleapis.com/v1beta1/projects: The caller does not have permission.
[20/Aug/2017 05:55:02] "POST /user/deployment/create/new HTTP/1.1" 500 14960
I have successfully created google cloud project by using Google cloud API python client.
Steps
run gcloud beta auth application-default login command to get application default credentials by login onto the browser
Enable Resource Manager API on my gcp console
Here's the working python code:
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
...
credentials = GoogleCredentials.get_application_default()
service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
project_body = {
'name': 'Api Project',
'projectId': 'api-9837'
}
request = service.projects().create(body=project_body)
request.execute()
pprint(request)

Flask with MongoDB using MongoKit to MongoLabs

I am a beginner and I have a simple application I have developed locally which uses mongodb with mongoKit as follows:
app = Flask(__name__)
app.config.from_object(__name__)
customerDB = MongoKit(app)
customerDB.register([CustomerModel])
then in views I just use the CustomerDB
I have put everything on heroku cloud but my database connection doesn't work.
I got the link I need to connect by:
heroku config | grep MONGOLAB_URI
but I am not sure how to pull this. I looked at the following post, but I am more confused
How can I use the mongolab add-on to Heroku from python?
Any help would be appreciated.
Thanks!
According to the documentation, Flask-MongoKit supports a set of configuration settings.
MONGODB_DATABASE
MONGODB_HOST
MONGODB_PORT
MONGODB_USERNAME
MONGODB_PASSWORD
The MONGOLAB_URI environment setting needs to be parsed to get each of these. We can use this answer to the question you linked to as a starting point.
import os
from urlparse import urlsplit
from flask import Flask
from flask_mongokit import MongoKit
app = Flask(__name__)
# Get the URL from the Heroku setting.
url = os.environ.get('MONGOLAB_URI', 'mongodb://localhost:27017/some_db_name')
# Parse it.
parsed - urlsplit(url)
# The database name comes from the path, minus the leading /.
app.config['MONGODB_DATABASE'] = parsed.path[1:]
if '#' in parsed.netloc:
# If there are authentication details, split the network locality.
auth, server = parsed.netloc.split('#')
# The username and password are in the first part, separated by a :.
app.config['MONGODB_USERNAME'], app.config['MONGODB_PASSWORD'] = auth.split(':')
else:
# Otherwise the whole thing is the host and port.
server = parsed.netloc
# Split whatever version of netloc we have left to get the host and port.
app.config['MONGODB_HOST'], app.config['MONGODB_PORT'] = server.split(':')
customerDB = MongoKit(app)

Resources