-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot.py
134 lines (124 loc) · 4.82 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import tweepy, json, time, os, random, builtins, requests, urllib.request
# Imports the needed requirements.
class log:
def info(text: str):
print(f"[Info] {text}")
def success(text: str):
print(f"[Success] {text}")
def error(text: str):
print(f"[Error] {text}")
# The class for outputting console logs.
log.info("Starting..")
# Prints a message declaring the bot is starting.
try:
with open("config.json", "r") as unloaded_config:
config = json.load(unloaded_config)
log.success("Config has been loaded")
except:
log.error("Config could not be loaded")
exit()
# Loads the config.
try:
auth = tweepy.OAuthHandler(config["consumerKey"], config["consumerSecret"])
auth.set_access_token(config["accessTokenKey"], config["accessTokenSecret"])
api = tweepy.API(auth)
log.success("Connected to the Twitter API")
except:
log.error("Connection could not be established to the Twitter API")
exit()
# Defines and connects to the Twitter API.
log.info(f"User: {api.me().screen_name}")
log.info(f"Followers: {api.me().followers_count}")
time.sleep(1)
# Prints basic information about the account when ready, then pauses for a second.
def post():
try:
upload = random.choice(os.listdir(config["directory"]))
if not upload.lower().endswith((".png", ".jpg", ".jpeg", ".gif", ".mp4")):
raise Exception
if config["enableOneTime"]:
with open("uploaded.json", "r") as unloaded_uploads:
file = json.load(unloaded_uploads)
if upload in file:
raise Exception
else:
file.append(upload)
api.update_with_media(config["directory"] + upload, config["tweetContent"])
if config["enableOneTime"]:
with open("uploaded.json", "w") as unloaded_uploads:
json.dump(file, unloaded_uploads)
if config["enableDeleteOnPost"]:
os.remove(config["directory"] + upload)
log.success(f"Uploaded {upload}!")
return True
except:
try:
log.error(f"Failed to upload {upload}. Trying again..")
except:
log.error("Failed to upload. Trying again..")
return False
# Defines the function for finding and posting files.
builtins.reddit_num = 0
builtins.reddit_name = config["redditNames"][reddit_num]
builtins.attempts = 0
builtins.failed = 0
mode = config["redditMode"]
# Defining vars for Reddit.
def reddit():
try:
with requests.get(f"https://www.reddit.com/r/{reddit_name}/{mode}.json", headers={"user-agent": "Simple-Tweeter"}) as url:
data = json.loads(url.content)["data"]["children"][attempts]["data"]
url = data["url"]
upload = url.split("/")[-1]
urllib.request.urlretrieve(url, upload)
if config["enableOneTime"]:
with open("uploaded.json", "r") as unloaded_uploads:
file = json.load(unloaded_uploads)
if upload in file:
raise Exception
else:
file.append(upload)
api.update_with_media(upload, config["tweetContent"])
os.remove(upload)
if config["enableOneTime"]:
with open("uploaded.json", "w") as unloaded_uploads:
json.dump(file, unloaded_uploads)
log.success(f"Uploaded {upload}!")
builtins.attempts += 1
builtins.failed = 0
return True
except:
try:
log.error(f"Failed to upload {upload}. Trying again..")
except:
log.error("Failed to upload. Trying again..")
builtins.attempts += 1
builtins.failed += 1
if failed > 9:
if len(config["redditNames"]) == 1: return False
elif len(config["redditNames"]) > reddit_num+1:
builtins.reddit_num +=1
builtins.reddit_name = config["redditNames"][reddit_num]
builtins.failed = 0
builtins.attempts = 0
log.success(f"Changed Reddit to: {reddit_name}")
else:
builtins.reddit_num = 0
builtins.reddit_name = config["redditNames"][reddit_num]
builtins.failed = 0
builtins.attempts = 0
log.success(f"Changed Reddit to: {reddit_name}")
return False
sleep_for = config["sleepTime"]
# Pulls the period of time to sleep for from config and defines it.
while True:
while True:
if config["enableReddit"]:
if reddit():
break
else:
if post():
break
log.info(f"Sleeping for {sleep_for}s")
time.sleep(sleep_for)
#Executes the post function and sleeps for the preset time.