2
0
mirror of https://github.com/Nick80835/microbot synced 2025-08-22 18:19:16 +00:00
microbot/ubot/modules/4chan.py

59 lines
1.8 KiB
Python
Raw Normal View History

2020-04-06 10:24:10 -04:00
# SPDX-License-Identifier: GPL-2.0-or-later
from random import choice
from aiohttp import ClientSession
from ubot.micro_bot import micro_bot
ldr = micro_bot.loader
BOARD_URL = "https://a.4cdn.org/{0}/threads.json"
POST_URL = "https://a.4cdn.org/{0}/thread/{1}.json"
CONTENT_URL = "https://i.4cdn.org/{0}/{1}{2}"
@ldr.add(pattern="4c(f|)")
async def fourchan(event):
if event.pattern_match.group(1):
as_file = True
else:
as_file = False
board = event.pattern_match.group(2)
session = ClientSession()
async with session.get(BOARD_URL.format(board)) as response:
if response.status == 200:
board_response = await response.json()
op_id = choice(choice(board_response)["threads"])["no"]
else:
2020-04-06 10:32:09 -04:00
await event.reply(f"`An error occurred, response code: `**{response.status}**")
2020-04-06 10:24:10 -04:00
await session.close()
return
async with session.get(POST_URL.format(board, op_id)) as response:
if response.status == 200:
post_response = await response.json()
post_info = choice([[i["tim"], i["ext"], i["com"] if "com" in i else None] for i in post_response["posts"] if "tim" in i])
post_file_url = CONTENT_URL.format(board, post_info[0], post_info[1])
else:
2020-04-06 10:32:09 -04:00
await event.reply(f"`An error occurred, response code: `**{response.status}**")
2020-04-06 10:24:10 -04:00
await session.close()
return
await session.close()
if not response:
2020-04-06 10:32:09 -04:00
await event.reply(f"`No results for board: `**{board}**")
2020-04-06 10:24:10 -04:00
return
try:
2020-04-06 10:32:09 -04:00
await event.reply(post_info[2].replace("<br>", "\n"), file=post_file_url, force_document=as_file, parse_mode="html")
2020-04-06 10:24:10 -04:00
return
except:
pass
2020-04-06 10:32:09 -04:00
await event.reply(f"`Failed to fetch media for board: `**{board}**")