From 132969e31b3483fbf9c32fa1e5c77eff1937d3a8 Mon Sep 17 00:00:00 2001 From: Nick80835 Date: Mon, 6 Apr 2020 10:24:10 -0400 Subject: [PATCH] add 4chan --- ubot/modules/4chan.py | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ubot/modules/4chan.py diff --git a/ubot/modules/4chan.py b/ubot/modules/4chan.py new file mode 100644 index 0000000..fab0360 --- /dev/null +++ b/ubot/modules/4chan.py @@ -0,0 +1,61 @@ +# 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): + await event.edit(f"`Processing…`") + + 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: + await event.edit(f"`An error occurred, response code: `**{response.status}**") + 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: + await event.edit(f"`An error occurred, response code: `**{response.status}**") + await session.close() + return + + await session.close() + + if not response: + await event.edit(f"`No results for board: `**{board}**") + return + + try: + await event.client.send_file(event.chat_id, file=post_file_url, force_document=as_file, caption=post_info[2].replace("
", "\n"), parse_mode="html") + await event.delete() + return + except: + pass + + await event.edit(f"`Failed to fetch media for board: `**{board}**")