Advertisement
steve-shambles-2109

Get random images from 4chan

Nov 21st, 2019
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. '''
  2. 125-Get random images from 4chan
  3. stevepython.wordpress.com
  4.  
  5. pip3 install requests
  6.  
  7. IMPORTANT
  8. Don't remove the time.sleeps as must comply with 4chan's API rules.
  9. '''
  10.  
  11. import random
  12. import time
  13. import webbrowser
  14. from functools import lru_cache
  15.  
  16. import requests
  17.  
  18. boards = ['a', 'c', 'w', 'm', 'cgl', 'cm', 'n', 'jp', 'vp',  \
  19.           'v', 'vg','vr', 'co', 'g', 'tv', 'k', 'o', 'an',  \
  20.           'tg','sp', 'asp','sci', 'int', 'out', 'toy', 'biz',  \
  21.           'i', 'po', 'p', 'ck','ic', 'wg', 'mu', 'fa', '3',  \
  22.           'gd','diy', 'wsg', 's', 'hc','hm', 'h', 'e', 'u',  \
  23.           'd', 'y', 't', 'hr', 'gif', 'trv','fit', 'x', 'lit',  \
  24.           'adv','lgbt', 'mlp', 'b', 'r', 'r9k','pol', 'soc',  \
  25.           's4s']
  26.  
  27.  
  28. def api(path):
  29.     time.sleep(1.5)
  30.     return requests.get(f'http://a.4cdn.org/{path}.json').json()
  31.  
  32.  
  33. @lru_cache()
  34. def board_data(board):
  35.     return api(board + '/catalog')
  36.  
  37.  
  38. def r4chan():
  39.     """
  40.    Returns [ random image URL, random image's thread URL ]
  41.    """
  42.     board = random.choice(boards)
  43.  
  44.     thread = random.choice([
  45.         thread['no']
  46.         for page in board_data(board)
  47.         for thread in page["threads"]
  48.     ])
  49.  
  50.     image = random.choice([
  51.         f"{post['tim']}{post['ext']}"
  52.         for post in api(f'{board}/thread/{thread}')['posts']
  53.         if 'tim' in post
  54.     ])
  55.  
  56.     return (
  57.         f'https://is2.4chan.org/{board}/{image}',
  58.         f'https://boards.4chan.org/{board}/thread/{thread}',
  59.     )
  60.  
  61.  
  62. # Opens x amount of image URLs in web browser
  63. def main(numberOfImages):
  64.     for i in range(numberOfImages):
  65.         image_url, thread = r4chan()
  66.         webbrowser.open(image_url)
  67.         print(thread)
  68.  
  69. # change the 10 to how many images you require
  70. main(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement