Another How to start Python file at Windows Startup but - python

I fount a lot of How to start Python at Windows Startup but maybe I have something different here...
I made a Task Schedulation at Windows Startup (I want it before User loggin in) with a .vbs
The VBS run correctly, but the .py file doesn't run.
The VBS log to FILE.log correctly, but the Python script doesn't log anything (now I removed log).
It isn't called...
I tried to modify the VBS to have full path to python and to my script, but notting changed... the python script look like is not executed.
Why?
VBS file:
MyLog = "C:\Users\myUser\Desktop\FILE.log"
Set fso = CreateObject("Scripting.FileSystemObject")
if fso.FileExists(MyLog) = false then
Set MyOutputLog = FSO.CreateTextFile(MyLog)
else
Set MyOutputLog = FSO.OpenTextFile(MyLog, 8, True)
end if
MyOutputLog.writeline Cstr(now()) & " - VBS is ok"
MyOutputLog.close()
Set oShell = CreateObject ("WScript.Shell")
oShell.run "python.exe ./myScript.py"
alternative bat file:
cd C:\Users\myUser\Desktop\
C:\Users\myUser\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbxxxxxx8p0\python.exe "C:/Users/myUser/Desktop/myscript.py"
Python file:
import socket
import time
import json
import requests
TOKEN = "<my-bot-token>"
URL = "https://api.telegram.org/bot{}/".format(TOKEN)
CHAT = 111111111 # my chat ID
TEXT = "my message"
def get_IPpubl():
endpoint = 'https://ipinfo.io/json'
response = requests.get(endpoint, verify = True)
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
data = response.json()
return(data['ip'])
#check if DDNS is updated
def check_ddns():
IPddns = socket.gethostbyname('my.dynamic.dns')
IPpubl = get_IPpubl()
if IPddns == IPpubl:
return True
return False
#check if I'm online
def test_connection():
try:
socket.create_connection(('google.com', 80))
return True
except OSError:
return False
#functions for Telegram Bot
def get_url(url):
response = requests.get(url)
content = response.content.decode("utf8")
return content
def get_json_from_url(url):
content = get_url(url)
js = json.loads(content)
return js
def get_updates():
url = URL + "getUpdates"
js = get_json_from_url(url)
return js
def get_last_chat_id_and_text(updates):
num_updates = len(updates["result"])
last_update = num_updates - 1
text = updates["result"][last_update]["message"]["text"]
chat_id = updates["result"][last_update]["message"]["chat"]["id"]
return (text, chat_id)
def send_message(text, chat_id):
url = URL + "sendMessage?text={}&chat_id={}&parse_mode={}".format(text, chat_id, 'html')
get_url(url)
#try connection 300 times, after check DDNS and send message to Telegram
for _ in range(300):
if(test_connection()):
if(check_ddns()):
TEXT = TEXT + "DDNS OK"
else:
TEXT = TEXT + "DDNS need an update"
send_message(TEXT, CHAT)
break
time.sleep(5)
Task scheduler is enabled, because the VBS run...
However what I list what I select:
[General]
Account: myuser
Run whether user is logged on or not
Run with highest
privileges
[Triggers]
At Windows Startup
[Actions]
Start a program: myVBS.vbs (try also with /c start "C:\path_of_vbs_and_py"

Related

Telegram Bot not responding after 3rd function call

The issue is that the third function never seems to respond.
I haven't been able to find a reason why this happens in the telegram documentation.
Please let me know if you have this issue or seen it and know the solution.
Even a post that references an issue like this would work.
Thank you so much for the assistance.
from email import message
import os
import re
import html
import json
import telebot
import requests
import http.client
from pytube import *
from dotenv import load_dotenv
load_dotenv()
# Creating hiding, and using API Keys
API_KEY = os.getenv("API_KEY")
RAPID_KEY = os.getenv("RAPID_API")
bot = telebot.TeleBot(API_KEY)
#bot.message_handler(commands="start")
# Creating a help message for guidance on how to use bot.
def help(message):
# Trying to send help message, if unable to send, throw an error message for the user.
try:
bot.send_message(message.chat.id, "Use \"Youtube\" and the video name to search for a video.\n")
except:
bot.send_message(message.chat.id, "There was an error fetching help, the bot may be offline.\n")
# Checking data and seeing if the word "YouTube" was used in order to start the search
def data_validation(message):
query = message.text.split()
if("youtube" not in query[0].lower()): # Set flag false if regular text
return False
else:
return True
#bot.message_handler(func=data_validation)
# Searching for youtube videos
# using RAPID API
def search(message):
query = message.text.split()
# Check if data is valid, and change variable to be lowercase for easy use.
if(data_validation(message) == True and query[0].lower() == "youtube"):
try:
if(data_validation(message) == True and query[1].lower() != "-d"):
# Removing the word "YouTube" and sending the results to the YouTube search engine.
for item in query[:]:
if(item.lower() == "youtube"):
query.remove(item)
search_query = ' '.join(query)
else:
pass #If it's not term we're looking to convert, ignore it.
# RAPID API for Youtube
try:
url = "https://youtube-search-results.p.rapidapi.com/youtube-search/"
querystring = {"q":search_query}
headers = {
"X-RapidAPI-Key": RAPID_KEY,
"X-RapidAPI-Host": "youtube-search-results.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring) # Grabbing response information from URL
request = json.loads(response.text) # Parsing json string for python use
# Testing to see if the RAPID API service responds and is online.
if(response.status_code == 503):
# If the service is not online, let the user know.
bot.send_message(message.chat.id, f"The RAPID API service appears to be offline try back later.\n")
if(response.status_code == 429):
# If the service has reached max quota for the day, let the user know.
bot.send_message(message.chat.id, f"Max quota reached, try back in 24 hours.\n")
# Grabbing first link from json text and sending direct url and title.
first_link = str((request["items"][0]["url"]))
bot.send_message(message.chat.id, f"{first_link}\n") # Sending first link that was queried.
# If there are no results found for the requested video, sending an error message to alert the user.
except:
bot.send_message(message.chat.id, "Unable to load video.\n")
except:
pass #ignoring if not the phrase we're looking for.
def test(message):
string = message.text.split()
print(string)
if(string[0] == "test" and data_validation(message) == True):
print("This is a test and i should be printed")
bot.send_message(message.chat.id, "Test message")
# Stay alive function for bot pinging / communication
bot.infinity_polling(1440)
The first problem in your code is your first line
from email import message
You import the message from email and also pass a parameter to the data_validation function with the same name, then return False in the data_validation function. If you return false, the function never will be executed.
first give an alias to first line you imported
Try This
from email import message as msg
import os
import re
import html
import json
import telebot
import requests
import http.client
from pytube import *
from dotenv import load_dotenv
load_dotenv()
# Creating hiding, and using API Keys
API_KEY = os.getenv("API_KEY")
RAPID_KEY = os.getenv("RAPID_API")
bot = telebot.TeleBot(API_KEY)
# Creating a help message for guidance on how to use bot.
#bot.message_handler(commands=["start"])
def help(message):
# Trying to send help message, if unable to send, throw an error message for the user.
try:
bot.send_message(message.chat.id, "Use \"Youtube\" and the video name to search for a video.\n")
except:
bot.send_message(message.chat.id, "There was an error fetching help, the bot may be offline.\n")
# Checking data and seeing if the word "YouTube" was used in order to start the search
def data_validation(message):
query = message.text.split()
print(query)
if("youtube" not in query[0].lower()): # Set flag false if regular text
return False # if you return false, the function never will be executed
else:
return True
# Searching for youtube videos
# using RAPID API
#bot.message_handler(func=data_validation)
def search(message):
query = message.text.split()
print(query) # if function executed you see the query result
# Check if data is valid, and change variable to be lowercase for easy use.
if(data_validation(message) == True and query[0].lower() == "youtube"):
try:
if(data_validation(message) == True and query[1].lower() != "-d"):
# Removing the word "YouTube" and sending the results to the YouTube search engine.
for item in query[:]:
if(item.lower() == "youtube"):
query.remove(item)
search_query = ' '.join(query)
else:
pass #If it's not term we're looking to convert, ignore it.
# RAPID API for Youtube
try:
url = "https://youtube-search-results.p.rapidapi.com/youtube-search/"
querystring = {"q":search_query}
headers = {
"X-RapidAPI-Key": RAPID_KEY,
"X-RapidAPI-Host": "youtube-search-results.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring) # Grabbing response information from URL
request = json.loads(response.text) # Parsing json string for python use
# Testing to see if the RAPID API service responds and is online.
if(response.status_code == 503):
# If the service is not online, let the user know.
bot.send_message(message.chat.id, f"The RAPID API service appears to be offline try back later.\n")
if(response.status_code == 429):
# If the service has reached max quota for the day, let the user know.
bot.send_message(message.chat.id, f"Max quota reached, try back in 24 hours.\n")
# Grabbing first link from json text and sending direct url and title.
first_link = str((request["items"][0]["url"]))
bot.send_message(message.chat.id, f"{first_link}\n") # Sending first link that was queried.
# If there are no results found for the requested video, sending an error message to alert the user.
except:
bot.send_message(message.chat.id, "Unable to load video.\n")
except:
pass #ignoring if not the phrase we're looking for.
def test(message):
string = message.text.split()
print(string)
if(string[0] == "test" and data_validation(message) == True):
print("This is a test and i should be printed")
bot.send_message(message.chat.id, "Test message")
# Stay alive function for bot pinging / communication
bot.infinity_polling(1440)
I found that using "if name == 'main':" and keeping all the functions in "main():" as a function handler everything ran smoothly.
I'm still trying to figure out why this works.

Accessing an uploaded file's url

My application for sends and receives data from/to my phone - basically a 2-way communication through the pushbullet API.
I am trying to take a file from my phone and when it's uploaded do something with it, (play it for example if it's an audiofile).
But when I upload the file on my phone and then I list the pushes on my computer and get that exact push, the file-URLL is restricted.
I got following XML error-response showing "Access Denied" as message:
403: Forbidden
How would I approach this?
Here is the code for the application:
def play_sound(url):
#open the url and then write the contents into a local file
open("play.mp3", 'wb').write(urlopen(url))
#playsound through the playsound library
playsound("play.mp3", False)
pb = pushbullet.Pushbullet(API_KEY, ENCRYPTION_PASSWORD)
pushes = pb.get_pushes()
past_pushes = len(pushes)
while True:
time.sleep(3)
# checks for new pushes on the phone and then scans them for commands
pushes = pb.get_pushes()
number_pushes = len(pushes) - past_pushes
if number_pushes != 0:
past_pushes = (len(pushes) - number_pushes)
try:
for i in range(number_pushes):
push = pushes[i]
push_body = push.get("body")
if push_body is not None:
play = False
if push_body == "play":
play = True
elif play:
#only runs if the user has asked to play something
#beforehand
play = False
url = push.get('file_url')
#play sound from url
#this is where I get my 403: forbidden error
if url is not None and ".mp3" in url:
play_sound(url)
except Exception as e:
print(e)
From the docs...
To authenticate for the API, use your access token in a header like Access-Token: <your_access_token_here>.
You're using urlopen(url) without any header information, so the request is denied.
So, try something like the following
from urllib.request import Request, urlopen
req = Request('https://dl.pushbulletusercontent.com/...')
req.add_header('Access-Token', '<your token here>')
content = urlopen(req).read()
with open('sound.mp3', 'wb') as f:
f.write(content)
Reference: How do I set headers using python's urllib?

Python print with flush won't refresh firefox page (edge works)

I have a problem with a simple python script which triggers a jenkins job and returns intermediate results while the jenkins job is running. The script sleeps, checks jenkins again and prints some info to a web browser output.
This generally works fine, but on Firefox 90.0.2, I do not get anything but a blank page until the job is done (the job gets triggered though).
On edge browser (vers 91.0.864.70) everything works as expected.
Here are relevant parts of my python script:
#!path/python.exe
import requests
import time
import functools
print = functools.partial(print, flush=True)
jenkins_url = "https://xxxx"
auth = ("user", "password")
job_name = "job"
request_url = "{0:s}/job/{1:s}/build?token=tokenName".format(
jenkins_url,
job_name,
)
print("Content-Type: text/html\n")
print("Determining next build number<br>")
job = requests.get(
"{0:s}/job/{1:s}/api/json".format(
jenkins_url,
job_name,
),
auth=auth,
).json()
next_build_number = job['nextBuildNumber']
next_build_url = "{0:s}/job/{1:s}/{2:d}/api/json".format(
jenkins_url,
job_name,
next_build_number,
)
print("Triggering build: {0:s} #{1:d}<br>".format(job_name, next_build_number))
response = requests.post(request_url, auth=auth)
print("Job triggered successfully<br>")
while True:
print("Querying Job current status...<br>")
try:
build_data = requests.get(next_build_url, auth=auth).json()
except ValueError:
print("No data, build still in queue<br>")
print("Sleep for 20 sec<br>")
time.sleep(20)
continue
print("Building: {0}<br>".format(build_data['building']))
building = build_data['building']
if building is False:
break
else:
print("Sleep for 60 sec<br>")
time.sleep(60)
print("Job finished with status: {0:s}<br>".format(build_data['result']))
Any suggestions or hints are greatly appreciated!
Thanks

NameError: name 'startCommand' is not defined - PYTHON

from coinbase.wallet.client import Client
from telegram import ParseMode
from telegram.ext import CommandHandler, Defaults, Updater
COINBASE_KEY = 'xxxxxxxxxxxx'
COINBASE_SECRET = 'xxxxxxxxxxxx'
TELEGRAM_TOKEN = 'xxxxxxxxxxxx'
coinbase_client = Client(COINBASE_KEY, COINBASE_SECRET)
#if __name__ == '__main__':
updater = Updater(token=TELEGRAM_TOKEN, defaults=Defaults(parse_mode=ParseMode.HTML))
dispatcher = updater.dispatcher
dispatcher.add_handler('start', startCommand) # Accessed via /start
dispatcher.add_handler('alert', priceAlert) # Accessed via /alert
updater.start_polling() # Start the bot
updater.idle() # Wait for the script to be stopped, this will stop the bot
def startCommand(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text='Hello there!')
def priceAlert(update, context):
if len(context.args) > 2:
crypto = context.args[0].upper()
sign = context.args[1]
price = context.args[2]
context.job_queue.run_repeating(priceAlertCallback, interval=15, first=15, context=[crypto, sign, price, update.message.chat_id])
response = f"⏳ I will send you a message when the price of {crypto} reaches £{price}, \n"
response += f"the current price of {crypto} is £{coinbase_client.get_spot_price(currency_pair=crypto + '-GBP')['amount']}"
else:
response = '⚠️ Please provide a crypto code and a price value: \n<i>/price_alert {crypto code} {> / <} {price}</i>'
context.bot.send_message(chat_id=update.effective_chat.id, text=response)
def priceAlertCallback(context):
crypto = context.job.context[0]
sign = context.job.context[1]
price = context.job.context[2]
chat_id = context.job.context[3]
send = False
spot_price = coinbase_client.get_spot_price(currency_pair=crypto + '-GBP')['amount']
if sign == '<':
if float(price) >= float(spot_price):
send = True
else:
if float(price) <= float(spot_price):
send = True
if send:
response = f'👋 {crypto} has surpassed £{price} and has just reached <b>£{spot_price}</b>!'
context.job.schedule_removal()
context.bot.send_message(chat_id=chat_id, text=response)
enter image description here
I get this error of the code above, also I have already tried changing the position of the def but, it also shows error, How to solve this?
It is the code for telegram bot and also this keeps on showing me NameError, I have already added python3 and pip, but still not solved
Python reads files top to bottom. So when you call dispatcher.add_handler('start', startCommand), the function startCommand is not yet known. Move the part
updater = Updater(token=TELEGRAM_TOKEN, defaults=Defaults(parse_mode=ParseMode.HTML))
dispatcher = updater.dispatcher
dispatcher.add_handler('start', startCommand) # Accessed via /start
dispatcher.add_handler('alert', priceAlert) # Accessed via /alert
updater.start_polling() # Start the bot
updater.idle() # Wait for the script to be stopped, this will stop the bot
below the callback definitions.
Apart from that, add_handler needs a Handler as argument, in your case something like add_handler(CommandHanlder('start', startCommand). Please see PTB tutorial as well as the examples.
Disclaimer: I'm the current maintainer of the python-telegram-bot library.
Try
dispatcher.add_handler('start', startCommand()) # Accessed via /start
dispatcher.add_handler('alert', priceAlert()) # Accessed via /alert
You will also need to add the two arguments required by both functions.
dispatcher.add_handler('start', startCommand(update, context))
dispatcher.add_handler('alert', startCommand(update, context))
I'm not exactly sure what data the two functions take in but I'm going to guess that it is whatever the bot is returning.

Getting Access Denied after receiving valid session id

I have a working python/tk program that runs a cgi script based on user selection. I'm working to cut this down to a small script that just focuses on one particular cgi script. It appears to be getting the session id correctly but when I launch the browser I keep getting "access denied". As the other program works I not expecting any issues from the website. Any help will be appreciated.
UPDATE:
If I use a debugger and set a breakpoint on the line print url the url printed in the console, as seen below, does work. I now know the session id token is good.
Also if I step into the webbrowser function and then step over after that the script also works.
Here is my code.
import json
import tornado.web
import tornado.websocket
from tornado import gen
import tornado.ioloop
import webbrowser
from struct import *
request_id = 71
ip_address = "10.22.4.14"
# ************************************************
# Procedure to open websocket and get session id
# ***********************************************
#gen.coroutine
def open_ws(ip, username, password):
global client
global request_id
global session_id
ws_url = "ws://" + ip + ":7011/"
try:
client = yield tornado.websocket.websocket_connect(ws_url, None, None, 5, None, None)
# print("websocket %s open" % ws_url)
except error:
exit()
# Send Mercury login request
JSON = '{"requests":[{"request_id": %s, "login":{"username": "%s","password": "%s"}}]}' % (str(request_id), username, password)
client.write_message(JSON)
results = yield client.read_message()
# print("msg is %s" % results)
# Parse the response of login request to get the error code
parsed_json = json.loads(results)
err_code = parsed_json['responses'][0]['request_response']['result']['err_code']
if 0 == err_code:
# Parse the response of get_command_result to get the session id
session_id = parsed_json['responses'][0]['request_response']['login']['session_id']
# print("login succeeded - session id: %s" % session_id)
else:
print("login failed")
# error_exit(err_code)
def get_token():
tornado.ioloop.IOLoop.instance().run_sync(lambda: open_ws(ip_address, 'admin', 'admin'))
return session_id
session_id = get_token()
print "Token is " + session_id
url = "http://" + ip_address + "/scripts/dostuff.cgi?session=" + session_id
print url # add breakpoint here
# launch browser
webbrowser.open(url)
Console output:
Token is 7zNSZX9liaUDFFN0ijn-LWQ8
http://10.222.4.14/scripts/dostuff.cgi?session=7zNSZX9liaUDFFN0ijn-LWQ8
Resolved. The script was ending therefore closing the socket before the browser had a chance to respond to the request

Categories