Spaces:
No application file
No application file
Upload bot_img.py
Browse files- bot_img.py +66 -0
bot_img.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import aiohttp
|
2 |
+
import asyncio
|
3 |
+
from urllib.parse import quote, parse_qs, urlparse
|
4 |
+
from bs4 import BeautifulSoup
|
5 |
+
|
6 |
+
import bot_strings
|
7 |
+
import bot_chat
|
8 |
+
|
9 |
+
TRIES = {}
|
10 |
+
MAX_TRIES = 3
|
11 |
+
|
12 |
+
|
13 |
+
async def get_images(url, aiosession):
|
14 |
+
images = []
|
15 |
+
async with aiosession.get(url) as response:
|
16 |
+
content = await response.text()
|
17 |
+
soup = BeautifulSoup(content, "html.parser")
|
18 |
+
if img_tags := soup.find_all("img"):
|
19 |
+
images = [img.get('src') for img in img_tags]
|
20 |
+
return images
|
21 |
+
|
22 |
+
|
23 |
+
async def generate_image(userID, query, cookies, request_id=None):
|
24 |
+
global TRIES
|
25 |
+
headers = {
|
26 |
+
'User-Agent':
|
27 |
+
'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0 BingSapphire/24.1.410310303',
|
28 |
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
29 |
+
'Origin': 'https://www.bing.com',
|
30 |
+
'Referer': 'https://www.bing.com/images/create?FORM=GENILP',
|
31 |
+
'Accept-Language': 'en-US,en;q=0.5'
|
32 |
+
}
|
33 |
+
data = {'q': query,
|
34 |
+
'qs': 'ds'}
|
35 |
+
|
36 |
+
params = {'q': query,
|
37 |
+
'rt': 3,
|
38 |
+
'FORM': 'GENCRE'}
|
39 |
+
|
40 |
+
images, error = [], None
|
41 |
+
|
42 |
+
if userID in TRIES.keys():
|
43 |
+
return [], bot_strings.POCESSING_ALREADY_STRING, False
|
44 |
+
|
45 |
+
TRIES[userID] = 0
|
46 |
+
canceled = False
|
47 |
+
async with aiohttp.ClientSession(headers=headers, cookie_jar=cookies) as session:
|
48 |
+
async with session.post('https://www.bing.com/images/create', params=params, data=data) as response:
|
49 |
+
if not response.history:
|
50 |
+
error = bot_strings.PROCESSING_ERROR_STRING
|
51 |
+
else:
|
52 |
+
parsed_url = urlparse(str(response.url))
|
53 |
+
id = parse_qs(parsed_url.query)['id'][0]
|
54 |
+
async with session.get(f'https://www.bing.com/images/create/async/results/{id}?q={quote(query)}') as response:
|
55 |
+
if response.status == 200:
|
56 |
+
while not images:
|
57 |
+
if not (await bot_chat.is_pending(request_id)):
|
58 |
+
canceled = True
|
59 |
+
break
|
60 |
+
images = await get_images(str(response.url), session)
|
61 |
+
if TRIES[userID] > MAX_TRIES:
|
62 |
+
break
|
63 |
+
await asyncio.sleep(5)
|
64 |
+
|
65 |
+
del TRIES[userID]
|
66 |
+
return images, error, canceled
|