Reddit bot that changes windows background with downloaded images - python

As of right now I have a majority of the code done for browsing a subreddit, and downloading the top images at the time of the request. I was able to do this using PRAW and urllib to download the images once i get their link. The final part that i am stuck on is putting the images files in an array and actually setting them as my background. Here is what i have
import praw
import time
import os
import urllib as ul
import os
def backGroundChanger(sub):
USER_AGENT='wall paper changer for linux/windows by /u/**********' #specifies what my bot does and by who
REDDIT_ID= #reddit id
REDDIT_PASS= #reddit password
reddit=praw.Reddit(USER_AGENT) #creates bot
reddit.login(REDDIT_ID,REDDIT_PASS) #logsin
print reddit.is_logged_in()
images=reddit.get_subreddit(sub)
while True:
count=0
for sub in images.get_hot(limit=10):
imageLink=sub.url
print imageLink
n=str(count)
ul.urlretrieve(imageLink, "i" + n )
count+=1
file=[]
dir=os.getcwd()
for files in os.listdir("."):
if(files.endswith(".jpg|| .png"): # not sure if this will work
file.append(files)
changeBackGround(file,dir)
def changeBackGround(file, dir):
#Do back ground changing stuff here
def main():
subreddit=input("What subreddit would you like me to pull images from? ")
print "You chose " + subreddit
backGroundChanger(subreddit)
main()

This might work, maybe not; its untested.
Read up on the os.system function for a means to use system programs to set the background, like xsetbg in linux. Look here for setting the windows background (it only involves hacking the registry).
import os
import glob
import random
import sys
import time
import urllib
import praw
def backGroundChanger(sub):
USER_AGENT = 'wall paper changer for linux/windows by /u/**********' #specifies what my bot does and by who
REDDIT_ID = #reddit id
REDDIT_PASS = #reddit password
reddit = praw.Reddit(USER_AGENT) #creates bot
reddit.login(REDDIT_ID, REDDIT_PASS) #logsin
print reddit.is_logged_in()
images = reddit.get_subreddit(sub)
while True:
count = 0
for sub in images.get_hot(limit = 10):
imageLink = sub.url
print imageLink
n = str(count)
urllib.urlretrieve(imageLink, "i" + n )
count += 1
files = glob.glob("*.jpg") + glob.glob("*.png")
changeBackGround(files)
def changeBackGround(ifiles):
#Do back ground changing stuff here
the_file = ifiles[random.randint(0, len(ifiles) - 1)]
if(sys.platform.startswith("win")): # Windows
# Do this yourself
pass
elif(sys.platform.startswith("linux")): # Linux
os.system("xsetbg -center %s" % the_file)
def main():
subreddit = input("What subreddit would you like me to pull images from? ")
print "You chose " + subreddit
backGroundChanger(subreddit)
main()

Related

imports not used in while

I'm making a bot in python and it works normally, but I need a certain part of the code to be in an infinite loop, so when i put the code inside the "while True" it looks like my imports are unusable. can someone explain to me how i can solve this?ยด
import datetime
import os
import time
import cv2
import pytesseract
from playwright.sync_api import sync_playwright
caminho = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
data = datetime.datetime.now()
h = data.strftime("%h")
d = data.strftime("%d")
H = data.strftime("%H")
M = data.strftime("%M")
S = data.strftime("%S")
hd = h + d
t = H + M
pasta =f"C:/Kprints/{hd}"
chave = "****"
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("*****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[19]/button[1]').click()
time.sleep(3)
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[4]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input').click()
page.fill('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[6]/input', "****")
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/button').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[1]/img[1]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div[2]/div/div[2]').click()
page.locator('xpath=/html/body/div/div[5]/div[2]/div[2]/div/div/div/div/div/div[2]/div[5]/button').click()
time.sleep(1)
while True:
page.screenshot(path=f"{pasta}/{t}.png")
time.sleep(1)
img = cv2.imread(f"{pasta}/{t}.png")
time.sleep(1)
pytesseract.pytesseract.tesseract_cmd = caminho
texto = pytesseract.image_to_string(img)
time.sleep(1)
if not os.path.isdir(pasta):
os.mkdir(pasta)
list = os.listdir(pasta)
for arquivo in list:
if chave not in texto:
os.remove(f"{pasta}/{arquivo}")
Errors:
Unused import statement 'import os'
Unused import statement'import cv2'
Unused import statement 'import pytesseract'
This code is unreachable
Your analyzer is saying the code using them can't be reached because your while loop, being infinite, renders it impossible to reach any code after it. Either:
The loop never ends, or
The calls inside it raise an exception, that (thanks to no try blocks being involved) will bubble up (skipping the remaining code) and end the program.
Either way, as written, the code after the loop never runs, so those imports are effectively unused.
The question for you is: Do you expect/need the code after that loop to run? If so, the loop cannot be infinite and you need to change the code so it can end. If not, why is the code after the loop even there?
Those are not errors. Those should be just warnings.
Can you try re-run and post actual output here?
You code gets stuck in that loop so imports not used and yes pytesseract can not be reached.
Practice this code snippet first:
key = ""
while key != "q":
key = input("Enter a Key: ")
if key == "q":
break
print(f"You Entered: {key}")

Make tweepy search for the newest mentions instead of the oldest

Today I wrote a twitter bot that replies anybody who mentions it with a random image from a folder.
The problem here is that I'm a newbie in python and I don't know how to make it funcitonal at all. When I started running it, the bot started replying all the mentions from other users (I'm using an old account a friend gave to me), and that's not precisely what I want, even if it's working, but not as I desire.
The bot is replying all the mentions from the very beggining and it won't stop until all these are replied (the bot is now turned off, I don't want to annoy anybody)
How can I make it to only reply to latest mentions instead of the first ones?
here's the code:
import tweepy
import logging
from config import create_api
import time
import os
import random
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
api = create_api()
imagePath = random.choice(os.listdir("images/"))
while True:
for tweet in tweepy.Cursor(api.mentions_timeline).items():
try:
imagePath = random.choice(os.listdir("images/"))
tweetId = tweet.user.id
username = tweet.user.screen_name
api.update_with_media('images/' + imagePath, "#" + username + " ", in_reply_to_status_id=tweet.id)
print('Replying to ' + username + 'with ' + imagePath)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
time.sleep(12)
Thanks in advance.
I don't have the ability to test this code currently but this should work.
Instead of iterating over every tweet, it turns the iterator that tweepy.Cursor returns into a list and then just gets the last item in that list.
api = create_api()
imagePath = random.choice(os.listdir("images/"))
while True:
tweet_iterator = tweepy.Cursor(api.mentions_timeline).items()
latest_tweet = list(tweet_iterator)[-1]
try:
imagePath = random.choice(os.listdir("images/"))
tweetId = latest_tweet.user.id
username = latest_tweet.user.screen_name
api.update_with_media('images/' + imagePath, "#" + username + " ", in_reply_to_status_id=latest_tweet.id)
print('Replying to ' + username + 'with ' + imagePath)
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
time.sleep(12)
You will also want to keep track of what user you last replied to, so you don't just keep spamming the same person over and over.
This isn't the most efficient way of doing it but should be easy enough to understand:
latest_user_id = None
while True:
# Rest of the code
try:
if latest_user_id == latest_tweet.user.id:
# don't do anything
else:
latest_user_id = latest_tweet.user.id
# the rest of your code

Python code to tag Instagram user in photo? using Instagram API

This Python code automates posting on Instagram
import os
import time
import random
from os import listdir
from os.path import isfile, join
from random import randint
from InstagramAPI import InstagramAPI
PhotoPath = "D:\Kartinka\Avto" # Change Directory to Folder with Pics
IGUSER = "shukurioll0" # Change to your Instagram USERNAME
PASSWD = "********" # Change to your Instagram Password
# Change to your Photo Hashtag
IGCaption = "#Nature This is post "
os.chdir(PhotoPath)
ListFiles = sorted([f for f in listdir(PhotoPath) if isfile(join(PhotoPath, f))])
print(ListFiles)
print("Total Photo in this folder:" + str(len(ListFiles)))
# #Start Login and Uploading Photo
igapi = InstagramAPI(IGUSER, PASSWD)
igapi.login() # login
for i, _ in enumerate(ListFiles):
photo = ListFiles[i]
print("Progress :" + str([i + 1]) + " of " + str(len(ListFiles)))
print("Now Uploading this photo to instagram: " + photo)
igapi.uploadPhoto(photo, caption=IGCaption, upload_id=None)
os.remove(photo)
# sleep for random between 60 - 120s
n = randint(5,10)
print("Sleep upload for seconds: " + str(n))
time.sleep(n)
Here
IGCaption==contains post name, hashtags!
I need code that I can tag person in photo
I used this Instagram API
usertags Here used my API Who can configure with my code
Here used usertag for

Youtube V3 API doesn't sort video

So I have been using youtube api to scrape a channel. Everything was working fine until 3 days ago (03/15/2019) when the result isn't sorted anymore. It seems that no matter what I put in the order parameter, the results are all the same. Can anyone tell me why it isn't working? Here's the code snippet:
import re
import os
import json
import MySQLdb
from pytube import YouTube
import urllib
import isodate
import sys
def get_all_video_in_channel(channel_id):
api_key = '<MY KEY>'
video_url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id={}&key={}'
first_url = 'https://www.googleapis.com/youtube/v3/search?key={}&channelId={}&part=snippet,id&order=date&maxResults=50'.format(api_key, channel_id) #order by date but won't work
res = []
url = first_url
while True:
inp = urllib.urlopen(url)
resp = json.load(inp)
vidIds = []
for jobject in resp['items']:
if jobject['id']['kind'] == "youtube#video":
vidIds.append(jobject['id']['videoId'])
vidreq = urllib.urlopen(video_url.format(",".join(vidIds),api_key))
vidres = json.load(vidreq)
for vidjson in vidres['items']:
res.append(vidjson)
if (len(res) >= 50):
break
try:
next_page_token = resp['nextPageToken']
url = first_url + '&pageToken={}'.format(next_page_token)
except:
break
return res
c_id = 'UCycyxZMoPwg9cuRDMyQE7PQ'
episodes = get_all_video_in_channel(c_id)
Edit: I did some more research and people say that the API indeed is not working properly due to Youtube doing something with deleting the New Zealand shooting video and it will soon be working properly again.
I recommend you to see the answer https://stackoverflow.com/a/55220182/8327971. This is a known and acknowledged issue by Google: https://issuetracker.google.com/issues/128673552.

Setting Up livestreamer to Automatically Record twitch Streams

I have been looking for a way to record streams whilst not at home as past broadcasts are unsatisfactory to me with all their muted sections. I had a found one site to help get me started but when i went to check for replies to after commenting asking for help and including images of my script i see that my posting got deleted rather than answered. But i digress.
I know how to manually start livestreamer from the command prompt when the stream is live but as aforementioned i am looking for a solution for when i'm not home.
I am sharing what i have in the hopes that someone would be able to identify what is wrong and help me rectify all issues to get this working.
#This script checks if a user on twitch is currently streaming and then records the stream via livestreamer
from urllib.request import urlopen
from urllib.error import URLError
from threading import Timer
import time
import datetime
import json
import sys
import subprocess
import datetime
import os
import configparser
def check_user(user):
""" returns 0: online, 1: offline, 2: not found, 3: error """
global info
url = 'https://api.twitch.tv/kraken/streams/' + user +"/?client_id=###"
try:
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
if info['stream'] == None:
status = 1
else:
status = 0
except URLError as e:
if e.reason == 'Not Found' or e.reason == 'Unprocessable Entity':
status = 2
else:
status = 3
return status
def format_filename(fname):
# Removes invalid characters from filename
fname = fname.replace("/","")
fname = fname.replace("?","")
fname = fname.replace(":","-")
fname = fname.replace("\\","")
fname = fname.replace("<","")
fname = fname.replace(">","")
fname = fname.replace("*","")
fname = fname.replace("\"","")
fname = fname.replace("|","")
fname = fname.replace(" ","")
return fname
def loopcheck():
while True:
status = check_user(user)
if status == 2:
print("username not found. invalid username?")
elif status == 3:
print(datetime.datetime.now().strftime("%Hh%Mm%Ss")," ","unexpected error. will try again in 5 minutes.")
time.sleep(300)
elif status == 1:
print(user,"currently offline, checking again in",refresh,"seconds")
time.sleep(refresh) # 15 seconds
elif status == 0:
print(user,"online. stop.")
filename = user+" - "+datetime.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss")+" - "+(info['stream']).get("channel").get("status")+".mp4"
filename = format_filename(filename)
str1="livestreamer --twitch-oauth-token ### twitch.tv/"+user+" "+quality+" -o "+directory+filename
subprocess.call(str1)
print("Stream is done. Going back to checking..")
time.sleep(15)
def main():
global refresh
global user
global quality
global directory
print("Usage: check.py [refresh] [user] [quality]")
print("Usage: TwitchChecker.py [refresh] [user] [quality]")
refresh = 15.0
str1=""
refresh = 15.0
user = "###"
quality = "best"
directory = "C:\Users\###\Videos\###\\"
if(refresh<15):
print("Check interval should not be lower than 15 seconds")
refresh=15
print("Checking for",user,"every",refresh,"seconds. Record with",quality,"quality.")
loopcheck()
if __name__ == "__main__":
# execute only if run as a script
main()
set /p DUMMY=Hit ENTER to continue...
For the batch file i have:
#echo
C:\Python\python C:\Users\xxx\Videos\xxx\xxx.py
#echo off
All that happens when i click on either of the 2 files is that the command prompt window flashes quickly.
Thankies for any and all help!

Categories