Web Push Is Not Being Executed In Job Scheduler - python

The job scheduler is being executed but for some reason the web push is not activated.I tried calling the web push function without the job scheduler and it does trigger a notification on browser. However, nothing gets triggered when I call it in the add_job scheduler function. The GET reminders should be called after the job scheduler if the web push were to be activated FYI. Please help.
#app.route("/notification", methods = ['POST', 'PUT'])
#token_required
def setNotifications(current_user, token):
if request.method == 'POST':
form = json.loads(request.data.decode('UTF-8'))
subscription = form["subscription"]
subscriptionId = form["subscriptionId"]
dailyReminder = True if form['daily'] is True else False
weeklyReminder = True if form['weekly'] is True else False
yearlyReminder = True if form['yearly'] is True else False
createNotif = db.session.query(User).filter(User.id == current_user.id).first()
reminder = db.session.query(Reminder).filter(Reminder.subscriptionId == subscriptionId).first()
message = json.dumps({"token": token, "subscriptionId": subscriptionId})
# print("Printing message" + message)
VAPID_CLAIMS = {
"sub": "my email"
}
if(createNotif.subscription == " "):
createNotif.subscription = json.dumps(subscription)
db.session.commit()
try:
# print("entering code")
sched.add_job(lambda:modules.send_web_push(json.loads(createNotif.subscription), message, VAPID_PRIVATE_KEY, VAPID_CLAIMS), 'date', run_date = datetime.date(2021, 5,8))
sched.start()
# modules.send_web_push(json.loads(createNotif.subscription), message, VAPID_PRIVATE_KEY, VAPID_CLAIMS)
# print("started here", flush= True)
return jsonify({'success':1})
except Exception as e:
print("error",e)
print("Could not send notification", flush=True)
return jsonify({'failed':str(e)})
if request.method == 'PUT':
removeSubscription = db.session.query(User).filter(User.id == current_user.id).first()
removeSubscription.subscription = " "
db.session.commit()
return jsonify({"success": "push notification has been updated"}), 200

Related

Add proxy to selenium python script

I'm really new to python and
I have a python selenium script
#Developed by github.com/useragents
#This script was made for educational purposes. I am not responsible for your actions using this script. This code is a few months old, hence why it may not appear as professional but still works to this day.
try:
from selenium import webdriver
import time, os, ctypes, requests
from colorama import Fore, init
import warnings, selenium, platform
except ImportError:
input("Error while importing modules. Please install the modules in requirements.txt")
init(convert = True, autoreset = True)
warnings.filterwarnings("ignore", category=DeprecationWarning)
clear = "clear"
if platform.system() == "Windows":
clear = "cls"
os.system(clear)
ascii_text = f"""{Fore.RED}
████████▀▀▀████
████████────▀██
████████──█▄──█
███▀▀▀██──█████
█▀──▄▄██──█████
█──█████──█████
█▄──▀▀▀──▄█████
███▄▄▄▄▄███████ github.com/useragents
"""
class automator:
def __init__(self):
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_experimental_option("excludeSwitches", ["enable-logging"])
self.xpaths = {
"followers": "/html/body/div[4]/div[1]/div[3]/div/div[1]/div/button",
"likes": "/html/body/div[4]/div[1]/div[3]/div/div[2]/div/button",
"views": "/html/body/div[4]/div[1]/div[3]/div/div[4]/div/button",
"shares": "/html/body/div[4]/div[1]/div[3]/div/div[5]/div/button"
}
try:
self.driver = webdriver.Chrome(options = options)
except Exception as e:
self.error(f"Error trying to load web driver: {e}")
self.status = {}
self.sent = 0
self.cooldowns = 0
self.ratelimits = 0
def check_status(self):
for xpath in self.xpaths:
value = self.xpaths[xpath]
element = self.driver.find_element_by_xpath(value)
if not element.is_enabled():
self.status.update({xpath: "[OFFLINE]"})
else:
self.status.update({xpath: ""})
def check_for_captcha(self):
while True:
try:
if "Enter the word" not in self.driver.page_source:
return
except:
return
os.system(clear)
print(ascii_text)
print(f"{self.console_msg('Error')} Complete the CAPTCHA in the driver.")
time.sleep(1)
def console_msg(self, status):
colour = Fore.RED
if status == "Success":
colour = Fore.GREEN
return f" {Fore.WHITE}[{colour}{status}{Fore.WHITE}]"
def update_ascii(self):
options = f"""
{self.console_msg("1")} Follower Bot {Fore.RED}{self.status["followers"]}
{self.console_msg("2")} Like Video Bot {Fore.RED}{self.status["likes"]}
{self.console_msg("3")} View Bot {Fore.RED}{self.status["views"]}
{self.console_msg("4")} Share Bot {Fore.RED}{self.status["shares"]}
"""
return ascii_text + options
def check_url(self, url):
redirect = True
if "vm.tiktok.com/" in url:
redirect = False
if redirect:
if "/video/" not in url:
return False
session = requests.Session()
r = session.get(url, allow_redirects=redirect)
if redirect:
if r.status_code == 200:
return True
return False
location = r.headers["Location"]
if "/video" in location:
return True
return False
def convert(self, min, sec):
seconds = 0
if min != 0:
answer = int(min) * 60
seconds += answer
seconds += int(sec) + 15
return seconds
def check_submit(self, div):
remaining = f"/html/body/div[4]/div[{div}]/div/div/h4"
try:
element = self.driver.find_element_by_xpath(remaining)
except:
return None, None
if "READY" in element.text:
return True, True
if "seconds for your next submit" in element.text:
output = element.text.split("Please wait ")[1].split(" for")[0]
minutes = element.text.split("Please wait ")[1].split(" ")[0]
seconds = element.text.split("(s) ")[1].split(" ")[0]
sleep_duration = self.convert(minutes, seconds)
return sleep_duration, output
return element.text, None
def update_cooldown(self, sleep_time, bot, rl = False):
cooldown = sleep_time
while True:
time.sleep(1)
try:
cooldown -= 1
except TypeError:
break
self.update_title(bot, cooldown, rl)
if cooldown == 0:
break
def wait_for_ratelimit(self, arg, div):
time.sleep(1)
duration, output = self.check_submit(div)
if duration == True:
return
if output == None:
time.sleep(0.7)
self.wait_for_ratelimit(arg, div)
self.cooldowns += 1
self.update_cooldown(duration, arg)
def send_bot(self, video_url, bot, div):
try:
self.driver.find_element_by_xpath(self.xpaths[bot]).click()
time.sleep(0.5)
except:
pass
enter_link_xpath = f"/html/body/div[4]/div[{div}]/div/form/div/input"
link = self.driver.find_element_by_xpath(enter_link_xpath)
link.clear()
link.send_keys(video_url)
self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
time.sleep(0.8)
send_button_xpath = f"/html/body/div[4]/div[{div}]/div/div/div[1]/div/form/button"
try:
self.driver.find_element_by_xpath(send_button_xpath).click()
except selenium.common.exceptions.NoSuchElementException:
self.wait_for_ratelimit(bot, div)
self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
time.sleep(0.8)
self.driver.find_element_by_xpath(send_button_xpath).click()
time.sleep(3)
try:
s = self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/div/span")
if "Too many requests" in s.text:
self.ratelimits += 1
self.update_cooldown(50, bot, True)
self.send_bot(video_url, bot, div)
elif "sent" in s.text:
sent = 100
if bot == "likes":
try:
sent = int(s.text.split(" Hearts")[0])
except IndexError:
sent = 30
if bot == "views":
sent = 2500
if bot == "shares":
sent = 500
self.sent += sent
else:
print(s.text)
except:
self.sent += sent
self.update_title(bot, "0")
self.wait_for_ratelimit(bot, div)
self.send_bot(video_url, bot, div)
def update_title(self, bot, remaining, rl = False):
if clear == "cls":
os.system(clear)
ctypes.windll.kernel32.SetConsoleTitleW(f"TikTok AIO | Sent: {self.sent} | Cooldown: {remaining}s | Developed by #useragents on Github")
print(ascii_text)
print(self.console_msg(self.sent) + f" Sent {bot}")
rl_cooldown = "0"
cooldown = "0"
if rl:
rl_cooldown = remaining
else:
cooldown = remaining
print(self.console_msg(self.cooldowns) + f" Cooldowns {Fore.WHITE}[{Fore.RED}{cooldown}s{Fore.WHITE}]")
print(self.console_msg(self.ratelimits) + f" Ratelimits {Fore.WHITE}[{Fore.RED}{rl_cooldown}s{Fore.WHITE}]")
def main(self):
if clear == "cls":
ctypes.windll.kernel32.SetConsoleTitleW("TikTok AIO | Developed by #useragents on Github")
self.driver.get("https://zefoy.com/")
time.sleep(2)
if "502 Bad Gateway" in self.driver.page_source:
os.system(clear)
print(ascii_text)
input(f"{self.console_msg('Error')} This website does not allow VPN or proxy services.")
os._exit(0)
self.check_for_captcha()
self.check_status()
self.start()
def error(self, error):
print(ascii_text)
print(f"{self.console_msg('Error')} {error}")
time.sleep(5)
os._exit(0)
def start(self):
os.system(clear)
print(self.update_ascii())
try:
option = int(input(f" {Fore.RED}> {Fore.WHITE}"))
except ValueError:
self.start()
if option == 1:
if self.status["followers"] != "":
return self.start()
div = 2
ver = "followers"
username = str(input(f"\n{self.console_msg('Console')} TikTok Username: #"))
print()
self.send_bot(username, ver, div)
return
elif option == 2:
if self.status["likes"] != "":
return self.start()
div = 3
ver = "likes"
elif option == 3:
if self.status["views"] != "":
return self.start()
div = 5
ver = "views"
elif option == 4:
if self.status["shares"] != "":
return self.start()
div = 6
ver = "shares"
else:
return self.start()
video_url = str(input(f"\n{self.console_msg('Console')} Video URL: "))
print()
check = self.check_url(video_url)
if not check:
return self.error("This URL does not exist.")
self.send_bot(video_url, ver, div)
obj = automator()
obj.main()
And tried to add https proxy with auth in this script
My proxy is 34.72.101.101:3127:user:BasAJSzAdAAWD
I tried to configure script to use proxy but it crashed one time and another time when I tried another way it worked but after some step proxy disappear

ONLY one client receive message in multiple client's server

My target is print the message from function result on the client's screen. But only ONE client can received the message...
The part of client.py is here
def PlayGame(clientSocket, msg):
invalid = "NO!"
if ("/guess " in msg):
msg1 = msg.split(" ")[1]
print("Hi1\n")
if msg1 == "true" or msg1 == "false":
print("Hi11")
clientSocket.send(msg1.encode())
print(clientSocket.recv(1024).decode())
print("!")
return '1'
else:
clientSocket.send(invalid.encode())
print(clientSocket.recv(1024).decode())
print("2")
return '2'
elif msg == "":
return '2'
else:
clientSocket.send(invalid.encode())
print(clientSocket.recv(1024).decode())
print("3")
return '2'
def main(argv):
msg=""
while (PlayGame(clientSocket, msg)!=1):
msg = input()
Any part of the server.py
guess_box = []
guess = bool(random.randint(0, 1))
def result(connectionSocket, guess_box, addr, addr_l):
a = 0
if(guess_box[0] == guess_box[1]):
msg = "Tie!!"
connectionSocket.send(msg.encode())
return '2'
elif(guess_box[0] == guess):
msg = "Player 1 Wins!"
a+=1
connectionSocket.send(msg.encode())
return '2'
elif(guess_box[1] == guess):
msg = "Player 2 Wins!"
a+=1
connectionSocket.send(msg.encode())
return '2'
def TF(connectionSocket, var, guess_box, addr, addr_l):
msg = connectionSocket.recv(1024).decode()
print("recv:",msg)
if(msg == 'true'):
msg = 'True'
var = str(var)
msg = bool(msg == var)
guess_box.append(msg)
return 'ok'
elif(msg == 'false'):
msg = 'False'
var = str(var)
msg = bool(msg == var)
guess_box.append(msg)
return 'ok'
else:
print(msg)
statement = "4002 Unrecognized message!!"
connectionSocket.send(statement.encode())
return 'again'
class ServerThread(threading.Thread):
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
def run(self):
...
print("guess is:", guess)
while (len(guess_box) != 2):
TF(connectionSocket, guess, guess_box, addr, addr_l)
print("start")
result(connectionSocket, guess_box, addr, addr_l)
...
Regarding only the one problem you address:
print the message from function result on the client's screen. But only ONE client can received the message
The problem comes from the use of a different thread for each client. The thread which receives a guess as first stays in its
while (len(guess_box) != 2):
print(guess_box)
TF(connectionSocket, guess, guess_box)
loop and waits for another message, which doesn't come. The thread which receives a guess as second sends the result to its own client only.
I don't think there's a sensible way to fix this while keeping this dthreaded approach.
Can I change the structure of my code by using those functions I implemented?
Here's a substitute for the while True loop in server_run that doesn't require changes in those functions other than server_run.
from select import select
connections = []
room_connection = {}
for reads in iter(lambda: select([serverSocket]+connections, [], [])[0], []):
for ready in reads: # for each socket which select reports is readable
if ready == serverSocket: # it's the server socket, accept new client
connectionSocket, addr = serverSocket.accept()
connections.append(connectionSocket)# store the connection socket
while RecvFromClient(connectionSocket) == "NO": pass
else: # message (or disconnect) from a client
try: var = GameHallMsg(ready, ready, connections)
except socket.error: var = 'bye'
if var == 'bye': # client finished, remove from list
connections.remove(ready)
ready.close()
elif var == 'wait': # store first player's connection
room_connection[current_rm_num.pop()] = ready
elif var == 'NO':
rtn_msg_4 = "4002 Unrecognized message"
ready.send(rtn_msg_4.encode())
elif var == 'jump':
readyroom = current_rm_num.pop()
# find and notify other player in the room
other = room_connection.pop(readyroom)
rtn_msg_2 = "3012 Game started. Please guess true or false"
other.send(rtn_msg_2.encode())
print("guess is:", guess)
# query and inform both players
guess_box = []
while TF(ready, True, guess_box) != 'ok': pass
while TF(other, True, guess_box) != 'ok': pass
result(ready, guess_box, ('', 0), [0])
result(other, guess_box, ('', 1), [0, 1])
room[readyroom] = 0

Global variable's value doesn't change in a thread

I'm making a flask application, and when the user presses a button I want for a thread to pause until the button is pressed again, and i'm planning to do this with a flag being set off. The thread can read the initial value of the flag, but when the user presses the button and the value is changed, the value remains false in the thread. It can read it successfully, but it just can't change it. I've tried making it global but it still has no effect. Here is the source -
web = False
#app.route("/")
def bg_func():
print('Thread test')
while True:
if web == False :
if Facial_Check.run() == True:
face_detected = True
t = Thread(target=bg_func)
t.start()
#app.route("/<changePin>/<action>")
def action(changePin, action):
changePin = int(changePin)
deviceName = pins[changePin]['name']
global web
if action == "on":
GPIO.output(changePin, GPIO.HIGH)
time.sleep(1)
GPIO.output(changePin, GPIO.LOW)
web = True
current_status = True
message = "Turned computer on."
if action == "off":
GPIO.output(changePin, GPIO.HIGH)
time.sleep(1)
GPIO.output(changePin, GPIO.LOW)
web = False
current_status = False
face_detected = False
message = "Turned computer off."
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
return render_template('index.html', Status=current_status)
You should use thread-specific features to be able share data between threads.
You may use current_thread for these purposes:
from flask import Flask
from time import sleep
from threading import Thread, current_thread
app = Flask(__name__)
web = current_thread()
def bg_func():
i = 0
while i < 100:
i += 1
sleep(2)
print('web is', getattr(web, 'web', None))
#app.route("/<my_web>")
def index(my_web = '0'):
before = getattr(web, 'web', None)
if my_web == '1':
setattr(web, 'web', True)
else:
setattr(web, 'web', False)
after = getattr(web, 'web', None)
return f"set {before} to {after}"
if __name__ == '__main__':
setattr(web, 'web', False)
t = Thread(target=bg_func)
t.start()
app.run(host='127.0.0.1', port=8080)
browser output will be:
set False to True
when access http://127.0.0.1:8080/1 first time
terminal output will be:
web is False
web is False
web is True
web is True
...
Update: adding example with socket client →
I added socket listeners as in your example:
Server side
from flask import Flask
from time import sleep
from threading import Thread, current_thread
from flask_socketio import SocketIO
def bg_func():
print('Thread test')
while True:
sleep(1)
print('web is ' + str(web.web))
app = Flask(__name__)
web = current_thread()
socketio = SocketIO(app)
setattr(web, 'web', None)
#app.route("/")
def action():
return 'web is ' + str(web.web)
#socketio.on('connect')
def connect():
setattr(web, 'web', True)
print('Client connected to server ')
#socketio.on('disconnect')
def disconnect():
setattr(web, 'web', False)
print('Client disconnected from server ')
if __name__ == "__main__":
t = Thread(target=bg_func)
t.start()
socketio.run(app, host='127.0.0.1', port=7878, debug=False)
Client side:
import socketio
sio = socketio.Client()
sio.connect('http://127.0.0.1:7878')
When I using client the output at server side is looking like:
...
web is None
web is None
...
Client connected to server
web is True
web is True
...
Client disconnected from server
web is False
web is False
...
BUT!
as you can see here is debug=False in my code. That is because of Flask run two app threads in DEBUG mode.
So first of web is controlled by you, second one is never changing and always will show None (if you change debug to True).

How can I receive messages from users in python-telegram-bot?

I'm using python-telegram-bot
def delete(update: Update, context: CallbackContext) -> None:
"""delete account from database"""
num = random.randrange(111111,999999)
update.message.reply_text("Something to write here\n\n****" + str(num) + "****")
time.sleep(10)
if int(update.message.text) == num: #here update.message.text == '/cancel' and not the message user
flag = delete_db(update.effective_user.id)
if flag:
update.message.reply_text('OK')
else:
update.message.reply_text('Something goes wrong or time is out')
How can i force the update of the message? I think is there the problem...
I resolved it, on the advice of the telegram community, with a Conversational Handler with two function, one to start the operation and the second to confirm.
In def main:
dispatcher.add_handler(
ConversationHandler(
entry_points = [MessageHandler(Filters.regex('^Cancel$'), delete)],
states = {
DELETE: [MessageHandler(Filters.text, random_number)],
},
fallbacks = [None], # here you can enter an /end function to break the process
conversation_timeout = 30,
),
)
Start function 'delete':
def delete(update: Update, context: CallbackContext):
update.message.reply_text('some message')
CallbackContext.chat_data = random.randrange(111111,999999)
update.message.reply_text("some other message\n*" + str(CallbackContext.chat_data) + "*")
return DELETE
The function to keep the string message and compare to random number generated:
def random_number(update: Update, context: CallbackContext):
try:
user_action = int(update.message.text)
if user_action == CallbackContext.chat_data:
#flag = delete_db(update.effective_user.id) # function to delete from database
if flag:
update.message.reply_text('Okay done')
else:
update.message.reply_text('Wrong number')
except:
update.message.reply_text('failed')
return ConversationHandler.END

Flask ldap3 issue with login

I am using Ldap3 with Flask python.
I am getting the error when I tried to login:
TypeError: Object of type 'Attribute' is not JSON serializable
Here is the code:
def ADlogin(username,password):
server = ldap3.Server(server_uri, get_info=ldap3.ALL)
connection = ldap3.Connection(server, user=username+base, password=password)
if not connection.bind():
return False
else:
connection.search(username+base, '(objectClass=*)', attributes=ldap3.ALL_ATTRIBUTES)
session['username'] = username
session['uid'] = connection.entries[0].uid
connection.search('dc=example,dc=com', '(objectclass=posixGroup)',
attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
for entry in connection.entries:
if entry.cn == 'service':
for user in entry.memberUid:
if user == session['uid']:
session['group_service'] = True
break
elif entry.cn == 'management':
for user in entry.memberUid:
if user == session['uid']:
session['group_management'] = True
break
return True
and the Login Page:
#app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == "POST" and request.form['submit'] == "Sign in":
username = request.form['username']
password = request.form['password']
if utils.isEmpty(username) or utils.isEmpty(password):
return render_template('login.html', status="Please Enter All Fields")
else:
status = ADConnect.ADlogin(username,password)
if status:
#return redirect(url_for('dashboard'))
return "Success"
else:
return render_template('login.html', status=status)
else:
return render_template('login.html')
The code is working fine in python console, but when I trying it with flask it is showing me that error, I am unable to find the solution for the problem.
Find the cause of error:
Here is the line or error : session['uid'] = connection.entries[0].uid
The connection.entries[0].uid is of type ATTRIBUTE and I am trying to set it on session causing the error.
I changes the attribute type to string and it works now!

Categories