repl.it
@paulfears/

meme bot

Python

This uses a webcrawler to get images from the internet, then combines them with PIL to create memes all rolled into a sarcastic chat bot

fork
loading
Files
  • main.py
  • assets
  • math
  • memes
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
from bs4 import BeautifulSoup
import requests
import PIL
from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO
import os
import sys
import time
from termcolor import cprint 
results = {}  #helps ease the load on google servers

def bing(term):
  src = []
  headers = {"user-agent":"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"}
  data = requests.get("https://www.bing.com/images/search?q="+term, headers=headers).text
  
  data = data.split("murl":"")
  
  i =0 
  for item in data:
    if i >=1:
      src.append(item.split("&quot")[0])
    i+=1
  
  return src
  
def get_image(term):
	try:

		return results[term]

	except KeyError:

		pass
	"+".join(term.split())
	url = "https://www.google.com/search?q=" + term + "&source=lnms&tbm=isch"
	source = requests.get(url).text
	doc = BeautifulSoup(source, "html.parser")
	src = []
	for img in doc.find_all('img'):

		if "Image result for" in img['alt']:
			
			src.append(img['src'])
	results[term] = src
	return src


def make_image(src, resize=False):
	file = BytesIO(requests.get(src).content)
	img = Image.open(file)
	if (resize):
		img = img.resize((500, 500))
	img.save("assets/or.png", "png")
	return img


def random_action():
	with open("assets/actions.txt", "r") as f:
		return f.read().split("\n")[random.randrange(1000)]


def meme_text(term):
	with open("assets/templates", "r") as f:
		words = f.read()
		
		words = words.split("%")
		
		joke = words[random.randint(1,(len(words)-1))]
		joke = joke.replace("{term}", term)
		joke = joke.replace("{action}", random_action())
		joke = joke.split("&")
		
	return joke


def generate_meme(term, file, resize=False, engine="bing"):
  if(engine=="google"):
    imgs = get_image(term)
  if(engine=="bing"):
    imgs = bing(term)
  img = imgs[random.randrange(len(imgs))]
  img = make_image(img, resize=resize)
  draw = ImageDraw.Draw(img)
  font_black = ImageFont.truetype("assets/meme.ttf", 40)
  font_white = ImageFont.truetype("assets/meme.ttf", 39)
  text = meme_text(term)
  make_dir("memes/"+term)
  with open(file,"w+") as f:
    pass
  draw.text((200, 0), text[0], (0, 0, 0), font=font_black)
  draw.text((200, 0), text[0], (230, 230, 230), font=font_white)
  draw.text((200, 450), text[1], (0, 0, 0), font=font_black)
  draw.text((200, 450), text[1], (230, 230, 230), font=font_white)
  img.save(file, "png")
  return img
  
def mprint(words, color="cyan"):
  print("meme bot:", end=" ")
  cprint(words+"\n", color)

def make_dir(directory):
  if not os.path.exists(directory):
    os.makedirs(directory)

def tally(meme):
  try:
    data[meme] +=1
  except:
    data[meme] = 1
  data['memes'] +=1
    
cprint("meme bot online...","red")
mprint("Hello I can make memes, do math, and have basic conversations")
time.sleep(2)
mprint("unfortunatly to view your memes you will have to wait till you exit")
time.sleep(0.5)
mprint("luckily all your memes will be in the meme directory after the session", color="magenta")
time.sleep(0.5)
mprint("so make sure to check the memes and math folder after the session",color="magenta")
mprint("you are probibly wondering how to work me if so type 'help'")
time.sleep(0.5)
mprint("or you can just type 'commands' to see all commands")
commands = ["meme","help","commands", "engine", "meme +word"]
data = {"memes":0, "random memes":0}


engine = "google"

while(True):

  search = input("you: ")
  if(len(search)<2):
    continue
  search = search.lower()
  searchlist = search.split()
  try:
    float(search[0])
    mprint(str(eval(search)))
    img = Image.open("assets/brain.jpg")
    draw = ImageDraw.Draw(img)
    font_black = ImageFont.truetype("assets/meme.ttf", 52)
    
    draw.text((0,0), "inferior being: "+search, (0,0,0), font=font_black)
    draw.text((500,600), "meme bot: "+str(eval(search)), (0,0,0),font=font_black)
    del draw
    t = time.time()
    make_dir("math")
    name = "math/m"+str(time.time())+".png"
    with open(name, "w+") as f:
      pass
    img.save(name,"png")
    continue
  except:
    pass
  if(search == "help"):
    mprint("I make memes! like really make them")
    time.sleep(1)
    mprint("you can ask me to generate memes on any topic")
    time.sleep(1)
    mprint("simply type 'meme' then a subject")
    time.sleep(1)
    mprint("if no subject is given I will pick one")
    time.sleep(1)
    mprint("you can see how many memes you made by typing 'queue'")
    time.sleep(1)
    mprint("you may notice that your memes are too blurry")
    time.sleep(1)
    mprint("you can help fix this by switching the engine to bing")
    time.sleep(1)
    mprint("this is done using the 'engine' command")
    time.sleep(1)
    mprint("however bing is know for being irrelavant")
    
    continue
  if(search == "engine"):
    while(True):
      mprint("which engine would you like to use?")
      mprint("1) google (most relivant)", color="blue")
      mprint("2) bing (highest img quality)", color="red")
      e = input("you: ")
      if(e == "1"):
        engine = "google"
        mprint("you engine is now google")
        break
      elif(e == "2"):
        engine = "bing"
        mprint("your engine is now bing")
        break
      else:
        mprint("oops thats not a valid input")
    continue
    
  if(search == "commands"):
    print(commands)
    continue
  if(searchlist[0] == "meme"):
    if(len(searchlist)>1):
      term = " ".join(searchlist[1:])
      
      make_dir("memes/"+term)
      try:
        generate_meme(term, "memes/"+term+"/"+term+str(random.random())+".png", resize=True, engine=engine)
      except:
        pass
      tally(term)
      time.sleep(2)
     

    else:
      topics = ["legos","george bush","clinton","daddy","vsauce", "robot"]
      generate_meme(random.choice(topics), "memes/random"+str(random.random())+".png", resize=True, engine=engine)
      tally("random meme")
      time.sleep(2)
      
      
    mprint("done using the "+engine+" engine")
    mprint(str(data))
    continue

  if "meme" in searchlist:
    mprint("looks like you trying to make a meme. ")
    mprint("what about?")
    term = input("you: ")
    while(True):
      mprint("should I use 1)google (most relevant) or 2)bing (highest quality)")
      n_engine = input("you: ")
      if(n_engine=='1'):
        n_engine = "google"
        break
      elif(n_engine=='2'):
        n_engine = "bing"
        break
    make_dir("memes/term")
    generate_meme(term,"memes/"+term+"/"+term+str(random.random())+".png", engine=n_engine, resize=True)
    tally(term)
    mprint("done using the "+engine+" engine")
    mprint(str(data))
    
    
    
  yes_no = ["can", "do", "will", "may", "should", "are", "is", "am"]
  if(searchlist[0] in yes_no):
    mprint(random.choice(["yes", "no"]))
    continue
  if(searchlist[0] == "who"):
    mprint(random.choice(["brad pit", "you", "george bush", "big man", "huge bigger", "Mr. jumper", "mr.smith", "old man"]))
    continue
  if(searchlist[0] == "how"):
    mprint(random.choice(["I don't know", "you should figure it out"]))
    continue
  if(searchlist[0] == "which"):
    mprint(random.choice(["I would go with both", "I would go with neither"]))
    continue
  if(searchlist[0] == "what"):
    if(searchlist[1] == "is"):
      try:
        print(search[9:2])
        float(search[9:2])
        print(search[8:1])
        mprint(str(eval(search[8:])))
        img = Image.open("assets/brain.jpg")
        draw = ImageDraw.Draw(img)
        font_black = ImageFont.truetype("assets/meme.ttf", 52)
    
        draw.text((0,0), "inferior being: "+search, (0,0,0), font=font_black)
        draw.text((500,600), "meme bot: "+str(eval(search)), (0,0,0),font=font_black)
        del draw
        t = time.time()
        make_dir("math")
        name = "math/m"+str(time.time())+".png"
        with open(name, "w+") as f:
          pass
        img.save(name,"png")
        continue
      except:
        pass
      things = ["a big thing", "a little thing", "a medium problem", "stupid", "a problem", "I dont care"]
      mprint(random.choice(things))
      continue