forked from pablogs9/ThermalLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
338 lines (283 loc) · 9.96 KB
/
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# -*- coding: utf-8 -*-
import telebot
from telebot import types
import requests
import os
from enqueuer import EventQueue
from ESCPOS import *
from PIL import Image
import wget
import csv
import datetime
# Set up the printer serial Port
try:
# = Thermal("/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller_D-if00-port0") #LINUX
t = Thermal("/dev/ttyS8") #WINDOWS
print "Printer open OK"
except:
print "Printer error"
t = None
# Create a queue that will print the tasks as soon as the enter in the queue
eq = EventQueue()
# Token from bot father on telegram
# ejecutar /newbot
#
# USING ENV VARIABLES, PUT YOUR TOKEN HERE AS `API_TOKEN = "TOKEN"`
API_TOKEN = os.environ['TELEBOT_TOKEN']
bot = telebot.TeleBot(API_TOKEN)
user_dict = {}
# Get current date for displaying in our program
now = datetime.datetime.now()
FECHA = str(now.day) + "/" + str(now.month) + "/" + str(now.year)
class User:
def __init__(self, name):
self.name = name
self.apellidos = None
self.curso = None
self.centro = None
self.ciudad = None
self.mail = None
self.challenge = None # Bool that indicates if the user solve the challenge
self.question = None
def add_data_csv(user,imgPath):
#print("Writing Data: " + user.name + " " + user.apellidos + " " + user.curso + " " + user.centro + " " + user.ciudad + " " + user.mail)
fields = [str(user.name), str(user.apellidos), str(user.curso), str(user.centro), str(user.ciudad), str(user.mail), str(imgPath)]
with open('data.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
f.close()
def normalize(s):
replacements = (
("á", "a"),
("é", "e"),
("í", "i"),
("ó", "o"),
("ú", "u"),
("º", "o"),
("ñ", "\xA4"),
("Ñ", "\xA5"),
("¿", "\xA8")
)
for a, b in replacements:
s = s.replace(a, b).replace(a.upper(), b.upper())
return s
def printTicket(userImg, user, imgPath): #Pic, user data, and a bool that indicates if the user solved the challenge
# Añadimos la info de usuario al CSV
add_data_csv(user,imgPath)
print("Imprimiendo foto")
t.println("")
t.println("")
t.println("")
print "Printing logo"
im = Image.open("logo.jpg")
t.printOldBitmap(im)
t.println("")
t.println(" \xA8Quiero ser ingeniera?")
t.textAlignCenter(100)
t.println(FECHA)
print "Printing user image"
t.printOldBitmap(userImg)
t.println("")
t.println("")
t.setMargin(10) # 10 mm margin
t.set_print_density(10)
t.println(normalize("Nombre: " + str(user.name)))
t.set_print_density(0)
t.println(normalize("Apellidos: " + str(user.apellidos)))
t.println(normalize("Curso: " + str(user.curso)))
t.println(normalize("Centro: " + str(user.centro)))
t.println(normalize("Ciudad: " + str(user.ciudad)))
t.println(normalize("Email: " + str(user.mail)))
t.println("")
t.println("")
t.setMargin(21)
t.println("-Reto-")
t.setMargin(5)
t.println(normalize("Rosi es 3 años mayor que Lili. Toto tiene la mitad de años que Rosi. Lili tiene 11 años"))
t.println(normalize("¿Cuátos años tiene Toto?"))
t.println("")
t.setMargin(20)
t.println(normalize("Solución: 7 años"))
t.setMargin(5)
if user.challenge:
t.println(normalize("Superaste el reto!"))
im = Image.open("good.jpg")
t.printOldBitmap(im)
else:
t.println(normalize("No has superado el reto, pero siempre estará septiembre"))
im = Image.open("bad.jpg")
t.textAlignCenter(im.size[0])
t.printOldBitmap(im)
t.setMargin(10) # 10 mm margin left
t.println("https://granasat.ugr.es")
t.println("")
t.println("")
t.println("")
t.setMargin(17) # 10 mm margin
t.println("Aerospace Group GranaSAT")
t.textAlignCenter(50)
t.println("Orbiting your mind")
t.println("")
t.println("")
t.println("")
t.println("")
t.cutPaper()
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(message, "Hola!")
markup = types.ForceReply(selective=False)
msg = bot.send_message(message.chat.id, "Hola! Dime tu nombre!", reply_markup=markup)
bot.register_next_step_handler(msg, get_name)
def get_name(message):
try:
chat_id = message.chat.id
name = message.text.encode('utf-8')
user = User(name)
user_dict[chat_id] = user
markup = types.ForceReply(selective=False)
msg = bot.reply_to(message, '¿Cómo te apellidas?', reply_markup=markup)
bot.register_next_step_handler(msg, get_apellidos)
except Exception as e:
bot.reply_to(message, 'oooops')
def get_apellidos(message):
try:
chat_id = message.chat.id
apellidos = message.text.encode('utf-8')
user = user_dict[chat_id]
user.apellidos = apellidos
markup = types.ForceReply(selective=False)
msg = bot.reply_to(message, '¿De qué curso eres?', reply_markup=markup)
bot.register_next_step_handler(msg, get_curso)
except Exception as e:
bot.reply_to(message, 'oooops')
def get_curso(message):
try:
chat_id = message.chat.id
curso = message.text.encode('utf-8')
user = user_dict[chat_id]
user.curso = curso
markup = types.ForceReply(selective=False)
msg = bot.reply_to(message, '¿De qué centro eres?', reply_markup=markup)
bot.register_next_step_handler(msg, get_centro)
except Exception as e:
bot.reply_to(message, 'oooops')
def get_centro(message):
try:
chat_id = message.chat.id
centro = message.text.encode('utf-8')
user = user_dict[chat_id]
user.centro = centro
markup = types.ForceReply(selective=False)
msg = bot.reply_to(message, '¿De qué ciudad eres?', reply_markup=markup)
bot.register_next_step_handler(msg, get_ciudad)
except Exception as e:
bot.reply_to(message, 'oooops')
def get_ciudad(message):
try:
chat_id = message.chat.id
ciudad = message.text.encode('utf-8')
user = user_dict[chat_id]
user.ciudad = ciudad
markup = types.ForceReply(selective=False)
msg = bot.reply_to(message, '¿Cuál es tu mail?', reply_markup=markup)
bot.register_next_step_handler(msg, get_mail)
except Exception as e:
bot.reply_to(message, 'oooops')
from questions import questions
import copy
import random
def get_mail(message):
try:
chat_id = message.chat.id
mail = message.text.encode('utf-8')
user = user_dict[chat_id]
user.mail = mail
bot.send_message(chat_id, "¿Aceptarías un reto?")
user = user_dict[chat_id]
user.question = random.choice(questions)
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
shans = copy.copy(user.question["answers"])
random.shuffle(shans)
for ans in shans:
markup.add(ans)
msg = bot.send_message(chat_id, user.question["question"], reply_markup=markup)
bot.register_next_step_handler(msg, resolver_problema)
except Exception as e:
print e
bot.reply_to(message, 'oooops')
def resolver_problema(message):
try:
chat_id = message.chat.id
respuesta = message.text.encode('utf-8')
user = user_dict[chat_id]
print(respuesta)
print(user.question["answers"][0])
if respuesta == user.question["answers"][0]:
user.challenge = True
bot.reply_to(message, "Correcto")
else:
user.challenge = False
bot.reply_to(message, "Has fallado! Vuelve a intentarlo.")
msg = bot.send_message(chat_id, "Enviame una foto!")
bot.register_next_step_handler(msg, process_pic)
except Exception as e:
bot.reply_to(message, 'oooops')
def process_pic(message):
if message.content_type != "photo":
bot.reply_to(message, "Lo que me has enviado no es una foto!")
msg = bot.reply_to(message, 'Enviame una foto!')
bot.register_next_step_handler(msg, process_pic)
else:
bot.reply_to(message, "Muchas gracias")
chat_id = message.chat.id
user = user_dict[chat_id]
#print("New foto " + message.photo)
fileID = message.photo[-1].file_id
file = bot.get_file(fileID)
print 'file.file_path =', file.file_path
url_pic_path = "https://api.telegram.org/file/bot" + API_TOKEN + "/" + file.file_path
print(url_pic_path)
output = os.path.join("photos/", str(message.message_id) + ".jpg")
imgpath = str(message.message_id) + ".jpg"
wget.download(url=url_pic_path, out=output)
eq.enqueue(printTicket, [Image.open(output), user, imgpath])
@bot.message_handler(func=lambda m: True)
def echo_all(message):
bot.reply_to(message, "Para utilizar el bot envia /start")
#Web Server
import os
import threading
from flask import Flask, request, send_from_directory, send_file
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.debug = False
@app.route('/images/<filename>')
def serve_images(filename):
return send_file("photos/" + filename)
@app.route('/<path:filename>')
def serve_static(filename):
return send_from_directory("imagesWebApp", filename)
@app.route("/data")
def data():
root_dir = os.path.dirname(os.getcwd())
return send_file("data.csv")
@app.route("/")
def hello():
return send_file("imagesWebApp/index.html")
if __name__ == "__main__":
threading.Thread(target=app.run).start()
bot.polling()
# import os
# files = os.listdir("./photos")
# for name in files:
# im = Image.open("photos/" + name)
# t.textAlignCenter(im.size[0])
# t.printOldBitmap(im)
# t.println("Aerospace Group GranaSAT")
# t.textAlignCenter(50)
# t.println("Orbiting your mind")
# t.println("")
# t.println("")
# t.println("")
# t.println("")
# t.cutPaper()