-
Notifications
You must be signed in to change notification settings - Fork 2
/
WithoutVideo.py
158 lines (124 loc) · 5.24 KB
/
WithoutVideo.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import requests
import praw
import urllib.parse
import urllib.request
import logging
import pandas as pd
import time
from pytz import timezone
from datetime import datetime
import os
import json
from better_profanity import profanity
start = time.time()
print('running...')
INSTAGRAM_APP_ID = os.environ['INSTAGRAM_APP_ID']
IG_USER_ID = os.environ['IG_USER_ID']
IMGUR_CLIENT_ID = os.environ['IMGUR_CLIENT_ID']
IMGUR_CLIENT_SECRET = my_secret = os.environ['IMGUR_CLIENT_SECRET']
REDDIT_CLIENT_SECRET = os.environ['REDDIT_CLIENT_SECRET']
REDDIT_CLEINT_ID = os.environ['REDDIT_CLEINT_ID']
INSTAGRAM_APP_SECRET = os.environ['INSTAGRAM_APP_SECRET']
IMGUR_UPLOAD_URL = "https://api.imgur.com/3/upload.json"
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36'
# valid for two months]
USER_ACCESS = os.environ['USER_ACESS']
# logging
logging.basicConfig(filename='logs.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger = logging.getLogger(__name__)
# database update this to sql
df = pd.read_csv('my_reddit_meme_posts.csv')
database_links = df['short_link'].tolist()
# Task 1 Get the reddit posts
red = praw.Reddit(client_id=REDDIT_CLEINT_ID,
client_secret=REDDIT_CLIENT_SECRET,
user_agent=USER_AGENT)
subred = red.subreddit('memes').hot(limit=50)
red_post = None
for i in subred:
if (i.stickied is False) & (i.is_video is False) & (i.shortlink not in database_links) & (i.over_18 is False):
# valid instagram aspect ratios
width = i.preview['images'][0]['source']['width']
height = i.preview['images'][0]['source']['height']
aspect_ratio = width/height
if (aspect_ratio >= 0.8) & (aspect_ratio <= 1.19):
red_post = i
break
if red_post:
red_image_url = red_post.preview['images'][0]['source']['url']
short_link = red_post.shortlink
caption = red_post.title
redditor = red_post.author.name
else:
print('red post not defined')
logger.fatal('reddit post didn\'t have a valid image post increase the limit!')
raise Exception
# removing any curse words if any
caption = profanity.censor(caption, censor_char='🤐')
# adding extra bio
caption_final = caption + f"\n\n\n-----------------------------\n😏Credits are never unknown\n👉OP --> u/{redditor}\n{short_link}\n-----------------------------\n\nHashtags - \n#reddit #redditmemes #memesdaily #meme #memes #dailymemes #everyhour"
caption_encoded = urllib.parse.quote(caption_final.encode('utf8'))
unique_id = short_link.split('/')[-1]
# for image
data = {
'image': red_image_url,
'type': 'URL',
'name': f'{unique_id}.jpg',
'title': caption,
'privacy': 'public',
}
headers = {
"Authorization": f"Client-ID {IMGUR_CLIENT_ID}"
}
r_imgur = requests.post(
IMGUR_UPLOAD_URL,
headers=headers,
data=data
)
imgur_link_jpg = None
try:
imgur_link = r_imgur.json()['data']['link']
imgur_link_jpg = '.'.join(imgur_link.split('.')[:-1]) + '.jpg'
df.loc[len(df.index)] = [red_image_url, short_link, caption, redditor, imgur_link]
df.to_csv('my_reddit_meme_posts.csv', index=False)
df.to_csv('copy_my_reddit_database.csv', index=False)
except Exception as e:
logger.error(e)
container_id = None
if imgur_link_jpg:
# post meme on my instagram
posting_url = f'https://graph.facebook.com/v13.0/{IG_USER_ID}/media?image_url={imgur_link_jpg}&caption={caption_encoded}&access_token={USER_ACCESS}'
r_container = requests.post(posting_url)
if r_container.status_code == 200:
container_id = r_container.json()['id']
else:
logger.fatal(f'status is not 200 but it is {r_container.status_code} and value is {r_container.text}')
# posting
if container_id:
publish_url = f'https://graph.facebook.com/v13.0/{IG_USER_ID}/media_publish?creation_id={container_id}&access_token={USER_ACCESS}'
try:
lim = requests.get(f'https://graph.facebook.com/v13.0/{IG_USER_ID}/content_publishing_limit?fields=quota_usage,rate_limit_settings&access_token={USER_ACCESS}')
lim_num = lim.json()['data'][0]['quota_usage']
lim_num = int(lim_num)
lim_left_before = 25 - lim_num
lim_left_after = lim_left_before - 1
print(lim_left_after, 'posts left!')
with open('posts_left.json', 'w') as f:
json.dump({'posts_left': lim_left_after}, f)
if lim_num <= 25:
r_publish = requests.post(publish_url)
print(r_publish.json()['id'])
print('Post is live!')
logger.log(10, f'{lim_left_after} posts left')
else:
logger.fatal(f'limit exhausted! {lim_left_after} left')
print('fatal error, no post left please stop!')
raise FutureWarning
except Exception as e:
logger.log(e)
end = time.time()
ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %I:%M:%S %p')
print('I ran at', ind_time)
logger.info(f"Post created at {ind_time}")
print('Run time ', round(end-start, 2), 'seconds')