Getting message contiously on telegram - python

from flask import Flask
from flask import request,jsonify
import requests
import json
app = Flask(__name__)
url = ''
token = ''
def send_message(chat_id,text):
URL = url+token+'sendMessage'
answer = {'chat_id': chat_id, 'text': text}
r = requests.post(URL,json = answer)
return ''
#app.route('/', methods = ['GET','POST'])
def index():
if request.method == 'POST':
r = request.get_json()
chat_id = r['message']['chat']['id']
text = "how are you?"
send_message(chat_id,text)
else:
return "hello world"
if __name__ == '__main__':
app.run()
when I run this after setting the webhook I keep getting the text 'how are you?' continuously. How do i fix this? I saw 2 answers telling to return 200 Ok. Could anyone please help ?

Related

Python Multiprocessing running process twice?

Running the following Python 3 script and for some reason that I cannot fathom the startWebview function executes twice resulting in two PyWebView windows being opened.
# Import Modules Here
import os
import time
import webview
import os.path
import multiprocessing
from dotenv import load_dotenv
from flask_wtf import FlaskForm
from flask_mde import Mde, MdeField
from wtforms import SubmitField, StringField
from wtforms.validators import InputRequired, DataRequired, Length
from flask import Flask, request, render_template, flash, session, url_for
app = Flask(__name__)
load_dotenv()
mde = Mde(app)
app.config['SECRET_KEY'] = os.environ.get("FLASK_SECRET_KEY")
windowTitle = os.environ.get("WINDOW_TITLE")
fileDirPath = os.environ.get("FILE_DIRECTORY")
def error_flasher(form):
for field, message_list in form.errors.items():
for message in message_list:
flash(form[field].label.text + ': ' + message, 'error')
print(message, message_list)
def fileHandler(form):
savePath = os.path.join(fileDirPath, form.title.data)
f = open(savePath, "w+")
f.write(form.editor.data)
f.close()
def contentLoader(form):
savePath = os.path.join(fileDirPath, form.title.data)
fileName = savePath
f = open(fileName, "r")
return f.read()
class MdeForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
editor = MdeField(
validators=[
#InputRequired("Input required"),
Length(min=0, max=30000)
]
)
submit = SubmitField()
#app.route('/', methods=['GET', 'POST'])
def index():
form = MdeForm()
if form.validate_on_submit() and form.editor.data == "":
form.editor.data = contentLoader(form)
elif form.validate_on_submit() and form.editor.data != "":
session['editor'] = request.form['editor']
fileHandler(form)
form.title.data = ""
form.editor.data = ""
return render_template("index.html", form=form, windowTitle=windowTitle)
def startFlaskServer():
app.run(debug=True)
def startWebview():
webview.create_window(windowTitle, 'http://localhost:5000')
webview.start(debug=True)
if __name__ == "__main__":
p1 = multiprocessing.Process(target=startFlaskServer)
p2 = multiprocessing.Process(target=startWebview)
p1.start()
time.sleep(2)
p2.start()
p2.join()
p1.terminate()
As seen in the above image it would appear that the cause is two GET requests as the second Webview only loads after the second GET request.
Thanks in advance!
It would appear that this issue is caused by Multiprocessing re-evaluating the file as suggested by #Carcigenicate.
Problem solved by moving from Multithreading to threading.

404 Not Found when using Flask and Ngrok for http://127.0.0.1:5000

Complete beginner in flask, ngrok and twilio. I ran this piece of python code to create a flask app for twilio :
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
"""Send a dynamic reply to an incoming text message"""
# Get the message the user sent our Twilio number
body = request.values.get('Body', None)
# Start our TwiML response
resp = MessagingResponse()
# Determine the right reply for this message
if body == 'hello':
resp.message("Hi!")
elif body == 'bye':
resp.message("Goodbye")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
It was hosted on http://127.0.0.1:5000
I then ran "ngrok http http://127.0.0.1:5000" which create an ngrok link, but when I used it I get 404 not found. What is causing this issue and how can I fix it ?
UPDATE: http://127.0.0.1:5000/sms does not work, shows blank page
1. Run ngrok 5000
2. Here is the flask code for generating, sending and validating OTP:
#app.route('/getOTP', methods=['GET', 'POST'])
def getOTP():
mobNum = request.get_json().get("mobNum")
length = len(mobNum)
val = 0
if length == 13 :
val = getOTPApi(mobNum)
elif length == '' or length < 12:
message = "Failure"
print(message)
return message
{'ContentType':'application/json'}
if val:
message = "Success"
print(message)
return message
else:
message = "NaN"
print(message)
return message
#app.route('/validateOTP', methods=['POST'])
def validateOTP():
otp = request.get_json().get("otp")
length = len(otp)
if 'response' in session:
s = session['response']
if s == otp:
message = "Success"
print(message)
return message
elif length == 0 or length < 6:
message = "NaN"
print(message)
return message
else:
message = "Failure"
print(message)
return message
session.pop('response', None)
def generateOTP():
return random.randrange(100000, 999999)
def getOTPApi(mobNum):
account_sid = 'XXXxxXXXXXX'
auth_token = 'XXXxxXXXXXX'
client = Client(account_sid, auth_token)
otp = generateOTP()
session['response'] = str(otp)
body = 'Your OTP is ' + str(otp)
message = client.messages.create(
from_='+1123456789',
body=body,
to=mobNum
)
if message.sid:
return True
else:
return False

youtube-dl front-end Video Download - using python and flask?

How to download youtube and other website video and audio file through youtube-dl (Front-End download - WEB UI)
Search and download the video through frontend.
i have write a script is python and flask -
from flask import (
Flask, Response,
render_template,
request,
redirect,
flash,
url_for,
send_file,
session,
)
import subprocess
from ydl import get_media, verify, fetch_name
from zipper import zipping
import os
app = Flask(__name__)
app.secret_key = "supposed to be a secret"
#app.route("/return-file/")
def return_file():
import pdb
#pdb.set_trace()
num_choice = session.get("choice")
filename = session.get("filename")
url = session.get("url")
if num_choice == 1:
filename_formatted = filename + ".mp3"
location = "media/Audio downloads/{}.mp3".format(session.get("id"))
if num_choice == 2:
#filename_formatted = filename + ".mp4"
#cc = get_media(url, num_choice)
print(url)
print('==============================================================================')
#"youtube-dl", "--get-url", url
#subprocess.run(["youtube-dl", "--no-check-certificate", "--get-url", url])
#subprocess.run(["youtube-dl", "--no-check-certificate", url])
test = subprocess.run(["youtube-dl", "--no-check-certificate", "--get-filename", url])
print(test)
csv = '1,2,3\n4,5,6\n'
return Response(
csv,
mimetype="text/csv",
headers={"Content-disposition":
"attachment; filename=test"})
#return send_file('', attachment_filename="myplot.csv")
print('==============================================================================')
#subprocess.run(["youtube-dl", "--no-check-certificate", url])
#location = "media/{}.mp4".format(session.get("id"))
#if os.path.isdir(location):
#print('True')
if num_choice == 3 or num_choice == 4:
filename_formatted = filename + ".zip"
location = "media/{}.zip".format(session.get("id"))
#return send_file(
#location, attachment_filename=filename_formatted, as_attachment=True
#)
#app.route("/", methods=["GET", "POST"])
def home_page():
"""
Displaying homepage
"""
title = "YDL | YouTube Downloader"
if request.method == "POST":
attempted_url = request.form["url"]
attempted_choice = int(request.form["submit"])
title = [attempted_url, attempted_choice]
if attempted_url != "":
if verify(attempted_url):
result_id = get_media(attempted_url, attempted_choice)
session["url"] = attempted_url
session["id"] = result_id
session["choice"] = attempted_choice
filename = fetch_name(attempted_url)
session["filename"] = filename
# return render_template('material-life.html', title = "Success {}".format(title))
# return render_template('material-life.html', title = result_id)
return redirect(url_for("return_file"))
else:
return render_template(
"material-life.html", title="YDL | Doesn't belong to YouTube"
)
else:
return render_template(
"material-life.html", title="YDL | URL shouldn't be empty"
)
return render_template("material-life.html", title=title)
#app.errorhandler(404)
def page_not_found(error):
"""
for anyone trying different links or searching for images within the server
"""
return (
render_template(
"error_template.html",
title="404 bud",
message="Time to make the chimi-fuckin'-changas. ",
subline="404, not there",
image_location=url_for("static", filename="images/deadpool-funny.jpg"),
),
404,
)
#app.errorhandler(400)
def bad_request(error):
"""
For handling situations where the server doesn't know what to do with the browser's request
"""
return (
render_template(
"error_template.html",
title="Aaaah ...",
message="나는 이해하지 못한다.",
subline="Yeah, the server couldn't understand what you asked for, Sorry",
image_location=url_for("static", filename="images/simpson-gangam.jpg"),
),
400,
)
if __name__ == "__main__":
app.run(debug=True)
its working on console base download... but i want to download through front end... without save - direct download
You can use pytube module, which depends on youtube-dl.
You seem to be building an app, but with the video's url, you can use the below one-liner to download the video:
from pytube import YouTube
YouTube(video_url).streams.first().download(filename='file_name')

My python webhook isn't giving me results

I've been working on trying to edit a webhook that was originally meant to be used for a weather API to get to be used with a postcode/zipcode API. The original file is here: https://github.com/dialogflow/fulfillment-webhook-weather-python/blob/master/app.py
I can't understand where mine is different, I thought I had solved it when I replaced urlencode with quote but alas, it wasn't enough.
The problem is very unlikely to do with the source json request that collects the postcode in postcodeValue(). The api url comes out correct when you enter it into a browser and is presented quite simply.
https://api.getaddress.io/find/SW11%201th?api-key=I98umgPiu02GEMmHdmfg3w12959
Is it in the correct format? Maybe I need to convert it to become even more JSON then it already is. This question is essentially an end of day brain dump that I I'm hoping that someone can save me with.
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode, quote
from urllib.request import urlopen, Request
from urllib.error import HTTPError
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
#this line is just naming conventions I reckon with a reference to expect to receive data as POST
#app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
#who knows where this is getting printed
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
res = json.dumps(res, indent=4)
# print(res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
if req.get("result").get("action") != "yahooWeatherForecast":
return {}
baseurl = "https://api.getaddress.io/find/"
apikey = "?api-key=I98umgPiu02GEMmHdmfg3w12959"
yql_query = postcodeValue(req)
if yql_query is None:
return {}
#this line is the actual api request
yql_url = baseurl + quote(yql_query) + apikey
result = urlopen(yql_url).read()
data = json.loads(result)
res = makeWebhookResult(data)
return res
#this function extracts an individual parameter and turns it into a string
def postcodeValue(req):
result = req.get("result")
parameters = result.get("parameters")
postcode = parameters.get("postcode")
if postcode is None:
return None
return postcode
#def housenoValue(req):
# result = req.get("result")
#parameters = result.get("parameters")
#houseno = parameters.get("houseno")
#if houseno is None:
# return None
#return houseno
def makeWebhookResult(data):
longitude = data.get("longitude")
if longitude is None:
return {}
#def makeWebhookResult(data):
# query = data.get('query')
# if query is None:
# return {}
# result = query.get('results')
# if result is None:
# return {}
# channel = result.get('channel')
# if channel is None:
# return {}
# item = channel.get('item')
# location = channel.get('location')
# units = channel.get('units')
# if (location is None) or (item is None) or (units is None):
# return {}
# condition = item.get('condition')
# if condition is None:
# return {}
# print(json.dumps(item, indent=4))
speech = "Sausage face " + longitude
print("Response:")
print(speech)
return {
"speech": speech,
"displayText": speech,
# "data": data,
# "contextOut": [],
"source": "apiai-weather-webhook-sample"
}
#More flask specific stuff
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print("Starting app on port %d" % port)
app.run(debug=False, port=port, host='0.0.0.0')
Here is a bit cleaner version of your code:
from urllib.request import urlopen
import os
from flask import Flask
app = Flask(__name__)
#app.route('/webhook', methods=['GET'])
def webhook():
res = processRequest()
return res
def processRequest():
try:
result = urlopen("https://api.getaddress.io/find/SW11%201th?api-key=I98umgPiu02GEMmHdmfg3w12959").read()
return result
except:
return "Error fetching data"
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print("Starting app on port %d" % port)
app.run(debug=False, port=port, host='0.0.0.0')
Open your browser and go to http://localhost:5000/webhook and you should see a response.

Flask AttributeError: 'NoneType' object has no attribute 'split'

from flask import Flask, render_template, request
from sys import argv
import requests
import json
app = Flask(__name__)
def decrementList(words):
for w in [words] + [words[:-x] for x in range(1,len(words))]:
url = 'http://ws.spotify.com/search/1/track.json?q='
request = requests.get(url + "%20".join(w))
json_dict = json.loads(request.content)
track_title = ' '.join(w)
for track in json_dict["tracks"]:
if track["name"].lower() == track_title.lower() and track['href']:
return "http://open.spotify.com/track/" + track["href"][14:], words[len(w):]
return "Sorry, no more track matches found!"
#app.route('/')
def home():
message = request.args.get('q').split()
first_arg = ' '.join(message)
results = []
while message:
href, new_list = decrementList(message)
message = new_list
results.append(href)
return render_template('home.html', first_arg=first_arg, results=results)
if __name__ == '__main__':
app.run(debug=True)
In the code above, when I run this Flask app I get an error AttributeError: 'NoneType' object has no attribute 'split from the home function. When I remove this, I also get an error on the ' '.join(message). Now when both of these are removed I refresh the page and the code runs, but not with the correct outputs. Next, I added the split and joins back in and refreshed the page and the code works perfectly, just as it should with no errors. How can I get this to run properly with out having to remove, refresh and add the join and split?
When there is no "q" in query string, you will get None.None has no methods named split, but string has.
message = request.args.get('q').split()
should be:
message = request.args.get('q', '').split()

Categories