-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.py
333 lines (285 loc) · 9.94 KB
/
main.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import asyncio
import json
from io import BytesIO
from os import getenv
import instaloader
import requests as r
import tzlocal
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from pyrogram import Client, errors, idle, raw, types, utils
from logger import getLogger
from utils import send_media_group
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
log = getLogger(__name__)
feedChatID = int(getenv("FEED_CHAT_ID", 0)) # chat ID to send Instagram feeds
storyChatID = int(getenv("STORY_CHAT_ID", 0)) # chat ID to send Instagram stories
username = getenv("USERNAME") # your Instagram username
RUNNING = {}
bot = Client(
"instaFeeds", getenv("API_ID", 0), getenv("API_HASH", ""), bot_token=getenv("BOT_TOKEN", "")
)
L = instaloader.Instaloader()
L.load_session_from_file(username) # type: ignore
scheduler = AsyncIOScheduler(timezone=str(tzlocal.get_localzone()))
def getLastPost(file):
with open(f"cache/{file}") as out:
return json.load(out)
def saveLast(data, file):
with open(f"cache/{file}", "w+") as out:
json.dump(data, out)
lastStory = getLastPost("stories.json")
lastFeed = getLastPost("post.json")
timeStamp = getLastPost("ts.json")
def get_post(post):
images = []
videos = []
if post.typename == "GraphSidecar":
for k in post.get_sidecar_nodes():
if k.is_video:
videos.append({"main": k.video_url, "thumb": k.display_url})
else:
images.append(k.display_url)
elif post.typename in ["GraphImage", "GraphStoryImage"]:
images.append(post.url)
elif post.typename in ["GraphVideo", "GraphStoryVideo"]:
videos.append({"main": post.video_url, "thumb": post.url})
return images, videos
async def getAlbumURL(post, caption=None):
ALBUM = []
if caption is None:
caption = (
f"[@{post.owner_username}](https://instagram.com/{post.owner_username}) | [🌐 Instagram](https://www.instagram.com/p/"
+ post.shortcode
+ ")\n\n"
+ (post.caption or "")
)
if caption and len(caption) > 1024:
caption = caption[:1024] + "..."
image, video = get_post(post)
for i in image:
ALBUM.append(types.InputMediaPhoto(i, caption=caption))
caption = None # using caption only for the first image of the group.
for i in video:
thumb = BytesIO()
resp = r.get(i["thumb"])
thumb.write(resp.content)
thumb.name = "thu.jpg"
ALBUM.append(types.InputMediaVideo(i["main"], caption=caption, thumb=thumb))
caption = None
return ALBUM
async def getAlbumBytes(post, caption=None):
ALBUM = []
if caption is None:
caption = (
f"[@{post.owner_username}](https://instagram.com/{post.owner_username}) | [🌐Instagram](https://www.instagram.com/p/"
+ post.shortcode
+ ")\n\n"
+ (post.caption or "")
)
if caption and len(caption) > 1024:
caption = caption[:1024] + "..."
image, video = get_post(post)
for i in image:
file = BytesIO()
resp = r.get(i)
file.write(resp.content)
file.name = "img.jpg"
ALBUM.append(types.InputMediaPhoto(file, caption=caption))
caption = None
for i in video:
file = BytesIO()
resp = r.get(i["main"])
file.write(resp.content)
file.name = "vid.mp4"
thumb = BytesIO()
resp = r.get(i["thumb"])
thumb.write(resp.content)
thumb.name = "thu.jpg"
ALBUM.append(types.InputMediaVideo(file, caption=caption, thumb=thumb))
caption = None
return ALBUM
async def sendMedia(media, post=None, story=None, breaker=None, ownerID=None):
# uploading media to telegram servers, without sending it anywhere
try:
return await send_media_group(bot, feedChatID, media=media)
except (errors.WebpageMediaEmpty, errors.WebpageCurlFailed):
if story:
media = await getStoryAlbumBytes(story, breaker, ownerID)
else:
media = await getAlbumBytes(post)
return await sendMedia(media, post, story, breaker, ownerID)
except errors.FloodWait as e:
await asyncio.sleep(e.value)
return await sendMedia(media, post, story, breaker, ownerID)
except Exception as e:
log.exception(e)
async def sendMessage(chat_id, multi_media):
try:
return await bot.invoke(
raw.functions.messages.SendMultiMedia(
peer=await bot.resolve_peer(chat_id),
multi_media=multi_media,
silent=None,
reply_to_msg_id=None,
schedule_date=utils.datetime_to_timestamp(None),
noforwards=None,
),
sleep_threshold=60,
)
except errors.MediaEmpty:
message = multi_media[0].message
entities = multi_media[0].entities
for i in multi_media:
try:
media = i.media
await bot.invoke(
raw.functions.messages.SendMedia(
peer=await bot.resolve_peer(chat_id),
media=media,
silent=None,
message=message,
reply_to_msg_id=None,
random_id=bot.rnd_id(),
entities=entities,
)
)
except Exception as e:
log.exception(e)
async def sendToChat(chatID, media):
try:
await sendMessage(chatID, media)
except errors.FloodWait as e:
await asyncio.sleep(e.value)
return await sendToChat(chatID, media)
except Exception as e:
log.exception(e)
async def getStoryAlbumURL(story, lastShort, ownerID=None):
ALBUM = []
medias = []
first = None
i = None
for i in story.get_items():
if i.shortcode == lastShort:
break
else:
medias.append(i)
if not first:
first = i.shortcode
if i:
ownerID = ownerID or str(i.owner_id)
lastStory[ownerID] = first or i.shortcode
saveLast(lastStory, "stories.json")
caption = None
for i in medias:
if caption is None:
caption = f"[@{i.owner_username}](https://instagram.com/{i.owner_username}) | [🌐 Story](https://www.instagram.com/{i.owner_username}/{i.mediaid})"
else:
caption = ""
album = await getAlbumURL(i, caption)
ALBUM += album
return ALBUM
async def getStoryAlbumBytes(story, lastShort, ownerID=None):
ALBUM = []
medias = []
first = None
i = None
for i in story.get_items():
if i.shortcode == lastShort:
break
else:
medias.append(i)
if not first:
first = i.shortcode
if i:
ownerID = ownerID or str(i.owner_id)
lastStory[ownerID] = first or i.shortcode
saveLast(lastStory, "stories.json")
caption = None
for i in medias:
if caption is None:
caption = f"[@{i.owner_username}](https://instagram.com/{i.owner_username}) | [🌐 Story](https://www.instagram.com/{i.owner_username}/{i.mediaid})"
else:
caption = ""
album = await getAlbumBytes(i, caption)
ALBUM += album
return ALBUM
def splitList(l, count=10):
return [l[i : i + count] for i in range(0, len(l), count)]
async def getStory():
for story in L.get_stories():
ownerID = str(story.owner_id)
lastPosted = lastStory.get(ownerID)
lastTimeStamp = timeStamp.get(ownerID)
_newTimeStamp = str(story.latest_media_utc)
if lastTimeStamp == _newTimeStamp:
log.info(f"no story update : {story.owner_username}")
continue
timeStamp[ownerID] = _newTimeStamp
saveLast(timeStamp, "ts.json")
lastShort = ""
if lastPosted:
lastShort = lastPosted
medias = splitList((await getStoryAlbumURL(story, lastShort, ownerID)))
for media in medias:
res = await sendMedia(media, story=story, breaker=lastShort, ownerID=ownerID)
if res:
await sendToChat(storyChatID, res)
saveLast(lastStory, "stories.json")
await asyncio.sleep(1)
async def getFeeds():
isFirst = None
MEDIA = []
breaker = lastFeed.get("last")
try:
for post in L.get_feed_posts():
if not isFirst:
isFirst = post.shortcode
if post.shortcode == breaker:
break
media = await getAlbumURL(post)
res = await sendMedia(media, post)
if res:
MEDIA.append(res)
except Exception as e:
log.exception(e)
if isFirst:
lastFeed["last"] = isFirst
saveLast(lastFeed, "post.json")
MEDIA.reverse() # reversing the list to keep the order of instagram posts
for i in MEDIA:
await sendToChat(feedChatID, i)
await asyncio.sleep(1)
@scheduler.scheduled_job(
"cron", hour="1,3,5,7,9,11,13,15,17,19", minute=00
) # running every 2 hours
async def runFeed():
while RUNNING.get("status"):
await asyncio.sleep(2)
log.info("waiting for previous run to finish!")
continue
RUNNING["status"] = True
try:
await getFeeds()
except Exception as e:
log.exception(e)
RUNNING["status"] = False
@scheduler.scheduled_job("cron", minute=00, hour="2,4,6,8,10,12,14,16,18")
async def runStory():
while RUNNING.get("status"):
await asyncio.sleep(2)
log.info("waiting for previous run to finish!")
continue
RUNNING["status"] = True
try:
await getStory()
except Exception as e:
log.exception(e)
RUNNING["status"] = False
async def main():
await bot.start()
scheduler.start()
log.info(f"{bot.me.username} started!")
await idle()
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())