While Loop No Longer Updating Data when added "Press Enter to Exit" - python

I am a beginner to Python and recently was making a **Discord Rich Prescense** application. The problem is that I was using a While Loop and added a "*Press Enter to Exit*" feature. This made the Rich Prescense stuck on One Quote. I have attached a screenshot of the problem.
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if not i:
break
Screenshot of what its supposed to do:

Using the keyboard module (https://pypi.org/project/keyboard/)
you can do it all.
I modified your code to fit your requirements:
import keyboard # using module keyboard
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if keyboard.is_pressed('enter'): # if key 'enter' is pressed
break

Related

Why my app keep opening when I use shortcut in Python?

I tried to create a program to open a app with a specific shortcut but when I press my keys it keep opening and didn't stop until I stopped the program
import keyboard
import time
import subprocess
while True:
if keyboard.is_pressed('ctrl+space+b'):
subprocess.Popen([r"C:\\Program Files\\Everything\\Everything.exe"])
time.sleep(1.5)
How about try this code
import keyboard
import subprocess
import threading
def run_my_program():
subprocess.run([r"C:\Program Files\Everything\Everything.exe"])
while True:
if keyboard.is_pressed('ctrl+space+b'):
threading.Thread(target=run_my_program).start() # launch up the subprocess in parallel so input is not delayed
while keyboard.is_pressed('ctrl+space+b'):
pass # Wait until user lifts his hands off the keyboard

Unique import * only allowed at module level [duplicate]

This question already has answers here:
Python: Why should 'from <module> import *' be prohibited?
(6 answers)
Closed 5 months ago.
I am making a utility program which has multiple programs built into it but I made some changes to my program for it re-run when the user has prompted which then for some reason, I am facing the error
import * only allowed at module level
Here's my code
def main():
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
print("*"*30)
print("Utility Build v1: Starting")
print("*"*30)
time.sleep(3)
print("NOTE: Before using this program for repairing corrupted disk, please locate this utility .py file into the corrupted storage. Thanks")
time.sleep(3)
print("*"*30)
print("*"*30)
print("Commands: Choose by inputting allocated number")
print("Utility 1: Speed Test")
print("Utility 2: Whatsapp Message Automation")
time.sleep(2)
print("Please Wait...Loading")
time.sleep(4)
print("Utility 3: Disk/Removable Storage Repair(a.k.a Dr Corrupt)")
print("Utility 4: Python .py status monitor")
print("*"*30)
print("*"*30)
print("q = Quit Utility Program")
input_ = input(": ")
if input_ == "q":
exit()
if input_ == "1":
time.sleep(2)
print("*"*30)
print("Speed Test: Starting")
print("*"*30)
st = Speedtest()
Download_ = print("Your connection download speed is:", st.download())
Upload_ = print("Your connection upload speed is:", st.upload())
Download1_ = st.download()
Upload1_ = st.upload()
print("*"*30)
print("Speed Test: Finishing Up!")
print("*"*30)
answer = input("Would you like results? ")
if answer == "yes":
print("NOTE: The first 2 digits frm the left is your internet speed")
time.sleep(2)
top = Tk()
top.geometry("100x100")
messagebox.showinfo("Speed Test: Download", Download1_)
top.mainloop()
reply = input("Would like to leave Utility Build(yes) or go to home page?(no) ")
else:
reply1 = print("Would like to leave Utility Build(yes) or go to home page?(no) ")
if reply1 == "yes":
main()
else:
exit()
if input_ == "2":
whatsapp.sendwhatmsg("+61450776320", "Hi, this is a test", 0, 0)
if input_ == "3":
for filename in listdir('./'):
if filename.endswith('.png'):
try:
img = Image.open('./'+filename) # open the image file
img.verify() # verify that it is, in fact an image
except (IOError, SyntaxError) as e:
print('Bad file:', filename) # print out the names of corrupt files
"Module level" just means in a part of the script that's not in a class or function. Any names you define there go directly into the module namespace.
The error message is therefore just saying to move
def main():
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
to
import os
import sys
import time
import pywhatkit as whatsapp
from speedtest import Speedtest
from tkinter import *
from tkinter import messagebox
from os import listdir
from PIL import Image
def main():
Actually, the interpreter only really cares about the line from tkinter import *. The others are a matter of convention and readability.
CPython does optimizations on the local namespace inside a function that requires the interpreter to know the names of all local variables up-front. A star import prevents that from happening since you don't know what names will be in the imported module until you run it. The global namespace doesn't have this restriction, so you can do star imports there.
Python is a language for consenting adults. Just because something is "bad practice" or not maintainable does not make it a syntax error.

Audio does not complete when called from another function

I have the following code quasi-working
from gtts import gTTS
import speech_recognition as rs
import pyaudio
import audioop
import os
import math
from os import system
import threading
from datetime import datetime
def say(text):
filename = 'speak.mp3'
language = 'en'
myobj = gTTS(text=text, lang=language, slow=False)
myobj.save(filename)
player = vlc.MediaPlayer(filename)
player.play()
def listen(x):
r=rs.Recognizer()
with rs.Microphone() as source:
audio=r.listen(source)
try:
text = r.recognize_google(audio)
process(text.lower())
except:
system('say I did not get that. Please say again.')
listen(0)
def process(text):
print(text)
# Do things here based on text
if 'what time is it' in text:
say(datetime.now().strftime("%H%M"))
return
#process("what time is it") "Seventeen oh six"
# Listen for me to say something, if I say 'what time is it' return the time
#listen(0) "Se"
If I run process(text) manually such as:
process("what time is it")
Python will speak back to me something like "1706" (Seventeen oh six)
However, if I call it from the listen() function python will start to play the file but it gets cut off and is more like "Se" and then nothing.
I've tried multiple things including using time.sleep(n) but no changes seem to make the entire file play when called through the listen(n) function.

WhatsApp texting using webbrowser module of python

import webbrowser
import time
import datetime
name = input('Enter the contact number of a person you want to send message in WhatsApp: ')
message = input('Enter the message: ')
time1 = input('Enter time in {hh:mm:ss} format: ')
print(f'Time entered by user: {time1}')
while True:
current_time = time.ctime()
time_format = current_time[11:19]
time.sleep(1)
print(f'Current time: {time_format}')
if time1 == time_format:
webbrowser.open_new_tab(f'https://web.whatsapp.com/send?phone=+91{name}&text={message}')
break
elif time1 < time_format:
print('Enter correct time')
break
else:
print('waiting..')
I am taking message, contact number and time as a input from the user. whenever, if condition satisfies, WhatsApp is open with the contact number and message you type in before.
Only problem is, I have to manually hit the send button to send message. Everything else is working fine.
Is there any way to do that? It would be great, if you provide solution without using Selenium
Thanks in advance!
This doesn't seem really efficient and not really good to constantly check to see if the time the user gave is the same as the current one. The schedule module can be really helpful with this and it does help to make your code look cleaner. I'll provide 2 answers, one with the schedule library and one without it.
Remember that if the user inputs a time that has passed, that doesn't matter to the program and it will only send the message at the next time that the time the user provided is the current device time. For example if the user inputs 13:10:00 and the current device time is 14:00:00 then the message will be sent the next time the current time is 13:10:00 which is the next day.
import os
import time
import webbrowser
from datetime import datetime
from string import ascii_letters
name = input('Enter the contact number of a person you want to send message in WhatsApp: ')
message = input('Enter the message:\n')
time1 = input('Enter time in {hh:mm:ss} format: ')
# Check if there aren't any ':' in the input time
if ":" not in time1:
print("Please input a correct time format")
os._exit(0)
# Check if there are any letters in the input time
elif ascii_letters in time1:
print("Please input a correct time format")
os._exit(0)
print(f'Time entered by user: {time1}')
# Check every .9 seconds if the current time is the same as the user input time
while True:
current_time = datetime.now().strftime("%H:%M:%S")
print(f'Current time: {current_time}')
if time1 == current_time:
webbrowser.open_new_tab(f'https://web.whatsapp.com/send?phone=+91{name}&text={message}')
break
else:
time.sleep(0.9)
And with the schedule library this is how it would probably look like:
(this is how you would probably do it)
import os
import time
import schedule
import webbrowser
from string import ascii_letters
def send_whatsapp_msg(name, message):
webbrowser.open_new_tab(f'https://web.whatsapp.com/send?phone=+91{name}&text={message}')
return schedule.CancelJob # do this if you want to send this message only once
# or just exit the program entirely if you don't want to run any more tasks
# os._exit(0)
name = input('Enter the contact number of a person you want to send message in WhatsApp: ')
message = input('Enter the message:\n') # Message to be sent
time1 = input('Enter time in {hh:mm:ss} format: ') # Time to sent the message
# Check if there aren't any ':' in the input time
if ":" not in time1:
print("Please input a correct time format")
os._exit(0)
# Check if there are any letters in the input time
elif ascii_letters in time1:
print("Please input a correct time format")
os._exit(0)
print(f'Time entered by user: {time1}')
# Schedule the message to be sent
schedule.every().day.at(time1).do(send_whatsapp_msg, name, message)
# Wait for the tasks to run and check the time every .9 seconds
while True:
schedule.run_pending()
time.sleep(0.9)
To fix the button clicking problem I think I found a "hacky" solution, using selenium and pyautogui. On Windows, you can install the WhatsApp application and scan the QR Code only once and then this solution will probably work for you.
You will also have to install the selenium chrome webdriver and take a screenshot of the "arrow" button to send the message to on the WhatsApp app. Here is the janky solution:
import os
import time
import schedule
import pyautogui
from string import ascii_letters
from selenium import webdriver
from selenium.webdriver.commn.keys import Keys
def send_whatsapp_msg(name, message):
driver = webdriver.Chrome() # you can user different drivers like 'Firefox()' but you will have to install them first
# look at https://selenium-python.readthedocs.io/installation.html for more info
driver.get("https://api.whatsapp.com/send?phone=+91{name}&text={message}")
time.sleep(10) # Wait for everything to set up, can be assigned lower values
# Click on the 'Open WhatsApp' Prompt Button
# Much easier to do it with pyautogui since I couldn't make it work with Selenium
# Look at https://pyautogui.readthedocs.io/en/latest/quickstart.html#screenshot-functions for the '.locateCenterOnScreen' function
coords = pyautogui.locateCenterOnScreen("open_whatsapp.png")
pyautogui.click(coords[0], coords[1]) # read the docs on what '.locateCenterOnScreen' returns
time.sleep(15) # Wait for the WhatsApp dektop app to load up
coords = pyautogui.locateCenterOnScreen("click_send.png") # coordinates for the 'send' button
pyautogui.click(coords[0], coords[1])
# Your message has been sent!
return schedule.CancelJob # do this if you want to send this message only once
# or just exit the program entirely if you don't want to run any more tasks
# os._exit(0)
name = input('Enter the contact number of a person you want to send message in WhatsApp: ')
message = input('Enter the message:\n') # Message to be sent
time1 = input('Enter time in {hh:mm:ss} format: ') # Time to sent the message
# Check if there aren't any ':' in the input time
if ":" not in time1:
print("Please input a correct time format")
os._exit(0)
# Check if there are any letters in the input time
elif ascii_letters in time1:
print("Please input a correct time format")
os._exit(0)
print(f'Time entered by user: {time1}')
# Schedule the message to be sent
schedule.every().day.at(time1).do(send_whatsapp_msg, name, message)
# Wait for the tasks to run and check the time every .9 seconds
while True:
schedule.run_pending()
time.sleep(0.9)
click_send.png looks like this:
and open_whatsapp.png looks like this:
open_whatsapp.png is a screenshot of the "Open WhatsApp" button that the website prompts you, but it was different in my language so I had to edit it out.
Also I don't know how reliable pyautogui will be but it worked every time I tried to run this, so I guess it kinda works.

how do i make this duplicate the tab and type into the input bar?

I haven't started on the web typing part but I need help with the starting part.
Here is my code
import webbot
import os
import time
import random
os.system('pip3 install pyautogui')
driver = webbot.Browser()
print("")
driver.go_to('https://kahoot.it/')
code = input("The game id: ")
input_elements = driver.find_elements(xpath='//input')
driver.type(driver.Key.TAB,into=input_elements[0].text)
driver.type(code)
driver.type(driver.Key.ENTER,into=input_elements[0].text)
time.sleep(1.5)
username = "test"
input_elements = driver.find_elements(xpath='//input')
driver.type(driver.Key.TAB,into=input_elements[0].text)
driver.type(username)
driver.type(driver.Key.ENTER,into=input_elements[0].text)
time.sleep(2)
driver.execute_script("window.open(' ');")
time.sleep(2)
driver.go_to('https://kahoot.it/')
# keeps the loop running
while True:
time.sleep(1)
I use repl.it's pygame for this
Edit: nvm I fixed the new tab now I need to type and hit enter into the boxes

Categories