Ejemplo n.º 1
0
    def notify_user(self, user_id, link):
        """
        Given user_id and link to online classroom, notify them of the upcoming class and share the online classroom link
        braincert.join_class(braincert_id, userId, userName, isTeacher, lessonName, courseName)
        """

        user = db.get_user_by_id(user_id)
        firstname = user["firstname"]
        chat_id = user["tgchat"]

        now = datetime.datetime.now()

        # If the class is not today, mention the date
        if now.date() != self.start.date():
            ClassDate = self.start.date().strftime(' on %b, %d')
        else:
            ClassDate = " today"

        message = (
            "Hey %s, your class %s of %s is going to start%s at %s:%s. Please join the class via your [personal link](%s)"
            % (firstname, self.class_title, self.course_title, ClassDate,
               str(self.start.hour), str(self.start.minute), link))

        print("Message for %s : \n %s" % (chat_id, message))
        sender.sender(chat_id, message)
Ejemplo n.º 2
0
 def setsmtp(self, address, port):
     '''
      设置smtp服务器指令\n
      param address 用户邮箱地址\n
      param port 邮箱授权码\n
     '''
     sender().setSMTPServer(address, port)
Ejemplo n.º 3
0
 def setuser(self, user, password):
     '''
      设置用户信息指令\n
      param user 用户邮箱地址\n
      param password 邮箱授权码/密码,根据邮箱的要求决定
     '''
     sender().setUserInfo(user, password)
Ejemplo n.º 4
0
def add_nginx_host(instance_id=None, host=None, port=None):
    msg_id = instance_id
    msg_type = "add"
    node_id = "client"
    message = dict(msg_type=msg_type, msg_id=msg_id, dst_host=host, dst_port=port, node_id=node_id)
    message = str(message)
    sender(message)
    LOG.info("Send to multicast: %s" % message)
Ejemplo n.º 5
0
 def handle_accept(self):
     conn, addr = self.accept()
     print '--- Connect --- '
     print self.TCP_connects
     print "key (addr) :", addr
     key = addr
     TCP_Forwarder.TCP_connects[key] = {}.fromkeys(
         ['sender', 'receiver', 'attribute'])
     TCP_Forwarder.TCP_connects[key]["attribute"] = {}
     sender(receiver(conn, key, self), self.remoteip, self.remoteport, key,
            self)
Ejemplo n.º 6
0
 def msjsend(self, key):
     print "sending menssage" + str(key)
     self.current_setting
     if key in self.current_setting:
         val = lookup(self.current_setting,key)
         topic = val[topic_index]
         msg = val[msg_index]
         msg_type = val[type_index]
         sender(msg, topic, msg_type)
     else:
         print "No existe ese boton"
Ejemplo n.º 7
0
def add_nginx_host(instance_id=None, host=None, port=None):
    msg_id = instance_id
    msg_type = "add"
    node_id = "client"
    message = dict(msg_type=msg_type,
                   msg_id=msg_id,
                   dst_host=host,
                   dst_port=port,
                   node_id=node_id)
    message = str(message)
    sender(message)
    LOG.info("Send to multicast: %s" % message)
Ejemplo n.º 8
0
def main():
    s = socket.socket()
    s.listen(5)
    entered_name = input("Enter your username:"******"Enter the IP you wish to connect to:")
    currentuser = User(entered_name, entered_ip, "Online")
    sock_data = connect(currentuser.ip_address, currentuser.port,
                        currentuser.username)
    daemon = threading.Thread(target=listener_daemon,
                              args=(sock_data, ),
                              daemon=True)
    daemon.start()
    sender(sock_data)
Ejemplo n.º 9
0
def del_nginx_host(instance_id=None):
    msg_id = instance_id
    msg_type = "del"
    node_id = "client"
    result = running_t.query_one(uuid=instance_id)
    try:
        port = result["port"]
    except KeyError:
        LOG.info("Error occured in get port.")
        return
    message = dict(msg_type=msg_type, msg_id=msg_id, server=port, node_id=node_id)
    message = str(message)
    sender(message)
    LOG.info("Send to multicast: %s" % message)
Ejemplo n.º 10
0
    def __init__(self, angle_num, imgs_if_tester=None):
        if imgs_if_tester is not None:
            self.is_test = True
            self.angles_imgs_lst = []
            self.angles_imgs_counter = []
            for i in range(angle_num):
                img_names = os.listdir(imgs_if_tester[i])
                sorted_img_names = sorted(img_names, key=first_2_chars)
                img_array = []
                for j in range(len(sorted_img_names)):
                    img_array.append(
                        cv2.cvtColor(
                            cv2.imread(imgs_if_tester[i] +
                                       sorted_img_names[j]),
                            cv2.COLOR_RGB2BGR))
                print(sorted_img_names)
                self.angles_imgs_lst.append(img_array)
                self.angles_imgs_counter.append(-1)
        else:
            self.is_test = False

        if (IS_PI):
            self.socket = sender.sender()
        else:
            self.socket = listener.listener()
Ejemplo n.º 11
0
def main(event, context):
    request = urllib.parse.parse_qs(event['body'])

    form_items = [['name', 'your name'], ['email', 'the e-mail address'],
                  ['subject', 'the subject'], ['message', 'the message']]

    for item in form_items:
        if item[0] not in request:
            return response_error(400, "Please fill " + item[1])

    if ('page' not in request) or (request['page'][0] not in ['HawkEvents']):
        return response_error(400, "Unknown Page")

    if 'g-recaptcha-response' not in request:
        return response_error(400, "Google reCAPTCHA Response Not Found")

    verify_result = verifier(request['page'][0],
                             request['g-recaptcha-response'][0])

    if not verify_result['success']:
        return response_error(403, "Google reCAPTCHA Failed")

    to_emails = {'HawkEvents': '*****@*****.**'}

    status, msg = sender(
        request['email'][0], to_emails[request['page'][0]],
        '[{} - {}] '.format(request['page'][0], request['name'][0]) +
        request['subject'][0], request['message'][0])

    if status:
        return {"statusCode": 200, "body": "Thank you!"}
    else:
        return response_error(500, "We cannot send the email: " + msg)
Ejemplo n.º 12
0
 def sendmails(self, mailList, subjectText, msgText):
     '''
     循环发送邮件\n
     param mailList 收件人列表,应为csv文件
     param subjetText 主题文件,为txt格式,里面包含邮件的主题
     param msgText 邮文,为txt格式,包含邮件的主要内容
     '''
     mailCore = sender()
     userRet = mailCore.getUserInfo()
     smtpRet = mailCore.getSMTPServer()
     # 判断输入的是否正确
     if not userRet:
         print('用户信息不完善,请用setuser命令设置用户信息')
         return
     elif not smtpRet:
         print('smtp服务器信息不完善,请用setsmtp命令设置smtp服务器及其端口信息')
     if not os.path.exists(mailList):
         print('发送名单路径不存在')
         return
     if not os.path.exists(subjectText):
         print('主题文件路径不存在')
         return
     if not os.path.exists(msgText):
         print('邮件正文文件路径不存在')
         return
     mailCore.sendMails(mailList, subjectText, msgText)
Ejemplo n.º 13
0
def extractor(email: MailMessage = None):
    """
    :param email: MailMessage object
    
    extract infos from the mail object
    """
    print("Extracting datas from email...")
    # extract email infos
    expeditor = email.from_values[
        'full'] if email.from_values else f"<{email.from_}>"
    subject = email.subject if email.subject else None
    content = email.text if email.text != "\r\n" else None
    attachments = [(att.filename, att.payload)
                   for att in email.attachments] if email.attachments else None
    sender_att = False
    print("Extract finished !")
    # return if empty email
    if not subject and not content and not attachments:
        return

    # extract and zip attachments if any
    if attachments:
        print("Attachments found, zipping files...")
        sender_att = True
        for att in attachments:
            with open(ATT_FOLDER + att[0], 'wb') as f:
                f.write(att[1])
        files = [x for x in Path(ATT_FOLDER).iterdir() if x.is_file()]
        with ZipFile(ATT_FOLDER + "attachments.zip", 'w') as zip:
            for f in files:
                zip.write(f, str(f).replace("attachments/", ""))
        print("Zip file created successfully !")

    # send the mail on discord via the sender
    # pprint((expeditor, subject, content, sender_att))
    sender(expeditor=expeditor,
           subject=subject,
           content=content,
           attachments=sender_att)

    # empty attachments dir
    if attachments:
        print("Detecting files in ./attachments ...")
        files = [x for x in Path(ATT_FOLDER).iterdir()]
        for f in files:
            remove(f)
        print("Attachments folder has been emptied !")
Ejemplo n.º 14
0
def del_nginx_host(instance_id=None):
    msg_id = instance_id
    msg_type = "del"
    node_id = "client"
    result = running_t.query_one(uuid=instance_id)
    try:
        port = result['port']
    except KeyError:
        LOG.info("Error occured in get port.")
        return
    message = dict(msg_type=msg_type,
                   msg_id=msg_id,
                   server=port,
                   node_id=node_id)
    message = str(message)
    sender(message)
    LOG.info("Send to multicast: %s" % message)
Ejemplo n.º 15
0
 def callback(self, ch, method, properties, body):
     print("[recver] %r:%r" % (method.routing_key, body))
     body_str = body.decode('utf8')
     body_dict = json.loads(body_str)
     result = proces(body_dict['cmd'])
     send = sender.sender()
     send.exchange()
     t = threading.Thread(send.run_back, args=(body_dict['id'], result))
     t.start()
Ejemplo n.º 16
0
def main():
	myQueue = queue.Queue() #Make an empty queue to have things pushed to
	r = Router.Router("start.txt", myQueue)
	s = pullSocket.pullSocket(myQueue)
	send = sender.sender(myQueue)

	r.start()
	s.start()
	send.start()
Ejemplo n.º 17
0
async def main(cfg):
    logging.basicConfig(filename=cfg["LOGFILE"],
                        level=cfg["LOGLEVEL"],
                        format=cfg["LOG_FORMAT"],
                        datefmt=cfg["LOG_DATEFMT"])

    try:
        tasks = asyncio.gather(asyncio.create_task(receiver(cfg)),
                               asyncio.create_task(sender(cfg)))
        await tasks
    except (KeyboardInterrupt, asyncio.CancelledError):
        tasks.cancel()
Ejemplo n.º 18
0
def customize():
    form = MyForm()
    print(form.validate_on_submit())
    if form.validate_on_submit():
        obj = request.form.to_dict()
        del obj['csrf_token']
        obj['varlist'] = obj['varlist'].split(',')
        obj['colist'] = obj['colist'].split(',')
        obj['xstart'] = int(obj['xstart'])
        obj['ystart'] = int(obj['ystart'])
        obj['zstart'] = int(obj['zstart'])
        obj['xend'] = int(obj['xend'])
        obj['yend'] = int(obj['yend'])
        obj['zend'] = int(obj['zend'])
        obj['precision'] = float(obj['precision'])
        if (not judge.judge(obj['function'], obj['colist'] + obj['varlist'])):
            return render_template('customize.html', form=form)
        else:
            print("ok")
        sender.sender(obj, asyncio.new_event_loop())
        return redirect('/success')
    return render_template('customize.html', form=form)
Ejemplo n.º 19
0
 def __init__(self, master=None):
     if master is not None:
         screenwidth = master.winfo_screenwidth()
         screenheight = master.winfo_screenheight()
         alignstr = '%dx%d+%d+%d' % (300, 120, (screenwidth - 320) / 2,
                                     (screenheight - 200) / 2)
         master.geometry(alignstr)
         master.update()
     super().__init__(master)
     self.mailCore = sender()
     self.mailCore.login()
     self.master = master
     self.grid()
     self.create_widgets()
Ejemplo n.º 20
0
 def __init__(self, angle_num, imgs_if_tester=None):
     if imgs_if_tester is not None:
         self.is_test = True
         self.angles_imgs_lst = []
         self.angles_imgs_counter = []
         for i in range(angle_num):
             img_names = os.listdir(imgs_if_tester[i])
             sorted_img_names = sorted(img_names, key=first_2_chars)
             img_array = []
             for j in range(len(sorted_img_names)):
                 img_array.append(
                     misc.imread(imgs_if_tester[i] + sorted_img_names[j]))
             print(sorted_img_names)
             self.angles_imgs_lst.append(img_array)
             self.angles_imgs_counter.append(-1)
     else:
         self.is_test = False
         gpio.setmode(gpio.BCM)
         self.init_vib()
     if (IS_PI):
         self.socket = sender.sender()
     else:
         self.socket = listener.listener()
Ejemplo n.º 21
0
 def newprocess(
 ):  # zamkniecie okna odbiorczego, utworzenie nowej, czystej instacji programu
     window2.destroy()
     start = sender.sender()
Ejemplo n.º 22
0
def main():
	parser = argparse.ArgumentParser(
		description = 'rqsh send and receive untility tool')

	#------------Main Args------------------
	parser.add_argument('-q', nargs = '+', help = 'quickly send a command and wait for result -> Unreliable')
	parser.add_argument('-s', nargs = '+', help = 'send data, do not wait for response')
	parser.add_argument('-l', action = 'store_true', help = 'run in listen mode, dump incoming data to cmd')
	parser.add_argument('-x', action = 'store_true', help = 'run in execute mode, ')
	parser.add_argument('-i', nargs='?', help="network interface, REQUIRED")

	#-------------Debugging Args-----------------------
	parser.add_argument('-d', help="debug mode", action='store_true')
	parser.add_argument('-p', nargs = '?', type = int, help = 'define non-default port #', default = 5005)
	parser.add_argument('-m', nargs = '?', type = str, help = 'define multicast group address', default = "224.3.29.71")
	#TODO self test mode

	#--------------File Transfer Args------------------
	parser.add_argument('-g', nargs='+', help = 'get a file from a destination running -x mode',
		metavar = 'address:file [local_dest]')

	parser.add_argument('-t', nargs='+', help = 'transmit (send) a file to a destination running -x mode',
		metavar = 'local_file address[:dest]')

	#--------tuning/performance args----------
	parser.add_argument('-lr', nargs = '?', type = float,
		default = 0.0, help = 'expected lose rate, will calculate the N for encoder')

	#--------------Main-----------------------
	args = None
	args = parser.parse_args(sys.argv[1:] if args is None else args)

	interfaces = netifaces.interfaces()
	my_ip = None
	for i in interfaces:
		if i == args.i:
			my_ip = netifaces.ifaddresses(i).get(netifaces.AF_INET)[0]['addr']
	if args.d:
		print my_ip
	if my_ip == None:
		print 'invalid network interface'
		exit(1)

	sndr = sender(loss = args.lr, mc_group = args.m, port = args.p, debug = args.d, ip=my_ip)

	#----------------decision tree---------------
	data_header = 0
	host_ip = None
	host_file  = None
	local_file = None
	#Data header types
	#0 = plaintext dump/command response
	#1 = command
	#2 = request file
	#3 = file dump/file response

	if args.q: #quicksend single command
		data_header = 1
		recv = receiver(port = args.p, exe = False, mc_group = args.m, debug = args.d)
		recv.blacklist(my_ip)
		t_id = threading.Thread(target = recv.start, kwargs = {'max_messages':1})
		t_id.daemon = True
		t_id.start()

	elif args.l: #launch daemon in listen mode
		recv = receiver(port = args.p, exe = False, mc_group = args.m, debug = args.d)
		recv.start(max_messages = -1)
	
	elif args.x: #launch daemon in exe mode
		recv = receiver(port = args.p, exe = True, mc_group = args.m, debug = args.d, sndr=sndr)
		recv.blacklist(my_ip)
		recv.start(max_messages = -1)

	elif args.g: #get file
		#also TODO build a file only mode
		
		recv = receiver(port = args.p, exe = True, mc_group = args.m, debug = args.d)
		recv.blacklist(my_ip)
		t_id = threading.Thread(target = recv.start, kwargs = {'max_messages':1})
		t_id.daemon = True
		t_id.start()

		data_header = 2
		if len(args.g) < 1:
			print 'give arguments to -g please!'
			exit(1)
		try:
			host_ip = args.g[0].split(':')[0]
			host_file = args.g[0].split(':')[1]
			if len(args.g) > 1:
				local_file = args.g[1]
			else:
				local_file = os.path.join(os.getcwd(), os.path.split(host_file)[1])
		except:
			print 'invalid syntax to -g'
			exit(1)

	elif args.t: #transmit file
		data_header = 3
		if len(args.t) < 1:
			print 'give arguments to -t please!'
			exit(1)
		try:
			local_file = args.t[0]
			host_ip = args.t[1].split(':')[0]
			if len(args.t[1].split(':')) > 1:
				host_file = argt.g[1].split(':')[1]
			else:
				os.path.split(local_file)[1]
		except:
			print 'invalid syntax to -t'
			exit(1)
	
	if args.q or args.s or args.g or args.t:
		#Data header types
		#0 = plaintext dump/command response
		#1 = command
		#2 = request file
		#3 = file dump/file response

		#data header syntax
		# 0: [header (this number)]\d[text size]\d[text]
		# 1: [header]\d[command]
		# 2: [header]\d[host_ip]\d[host_file]\d[local_file]
		# 3: [header]\d[dest_file aka host_file]\d[payload_size]\d[payload]
	
		#TODO find a better delimeter
		delim = '#' #delimiter for rqsh syntax 
		
		#this front-end only needs to deal with 'sending' types, 1,2,3
		data = str(data_header) + delim

		if data_header == 2:
			data += host_ip + delim + host_file + delim + local_file
		
		elif data_header == 3:
			file = open(local_file, 'r')
			payload = file.read()
			file.close()
		
			data += host_file + delim + payload_size + delim + payload

		elif data_header == 1:
			try: 
				for i in args.q:
					data += i + ' '
			except: pass

			try:
				for j in args.s:
					data += j + ' '
				data = data[:-1]
			except: pass

	sndr.send(data)
	
	if args.q or args.g:
		input() #wait for all threads to finish
Ejemplo n.º 23
0
def echo(bot, update):
    texto1 = update.message['text']
    chat_id = update.message.chat_id
    message_id = update.message.message_id
    name = update.message.from_user['first_name']
    user = unidecode(name)
    command = unidecode(texto1)
    print("\n\tTexto recibido: ", command)
    if read_database(chat_id) == None:
        bot.sendMessage(
            chat_id,
            text=
            "Antes de continuar, debes actualizar tus preferencias de idioma\n\nBefore you continue, you have to update your language preferences"
        )
        key_l(bot, update)
    elif command == 'Al descargar':  # This checks if the message was from keyboards in function 'errores.py' and assigns a value for redirecting them to 'botones.py'
        value = 'Ed'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Otro...":
        value = 'O'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Archivo vacio (0.00 Bytes)":
        value = 'V'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "El video no puede ser obtenido":
        value = 'U'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Descarga muy lenta":
        value = 'S'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Error al buscar la cancion":
        value = 'fi'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Mostrar todos los errores":
        value = 'mn'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Otro error no registrado":
        value = 'LK'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "El bot no hace nada":
        value = 'Z'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "While downloading":
        value = 'Eden'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Other...":
        value = 'Oen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Empty file (0.00 Bytes)":
        value = 'Ven'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Video can't be downloaded":
        value = 'Uen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Downloading very slowly":
        value = 'Sen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Error while searching the song":
        value = 'fien'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Show all registered errors":
        value = 'mnen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "Another error not registered":
        value = 'LKen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif command == "The bot is not responding":
        value = 'Zen'
        print(value)
        botones(bot, update, chat_id, message_id, value, user)
    elif 'es' in read_database(chat_id):
        print(
            "\n-----------------------------------------------------------------------------------------------------------------"
        )
        print("Debug [1]")
        print(
            "-----------------------------------------------------------------------------------------------------------------"
        )
        try:
            query0 = re.search("(?P<url>https?://[^\s]+)", command).group(
                "url"
            )  # It gets the first URL from message (if exists. Else, raises "AtributteError")
            Id = get_yt_video_id(query0)
            try:
                print("\tEjecutando descarga directa...")
                print("\tID: ", Id)
                if (Id == None):
                    raise IndexError(
                        'El enlace proporcionado no tiene un formato conocido, o no contiene el ID del vídeo, o no es un enlace de YouTube'
                    )
                else:
                    stndr_yt = "http://youtube.com/watch?v="
                    title1 = getVidTitle(Id, chat_id, bot, update)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                        Id, API)
                    print("\tURL API (2): ", url2)
                    datas = urlopen(url2).read()
                    json_data2 = json.loads(datas)
                    length = json_data2["items"][0]['contentDetails'][
                        'duration']
                    print("\tDuración (ISO): ", length)
                    dur = isodate.parse_duration(length)
                    print("\tDuración: ", dur)
                    durS = dur.total_seconds()
                    print("\tDuración en segundos: ", durS)
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    if (durS >= 5400):
                        bot.sendMessage(
                            chat_id,
                            "La duración de la canción/vídeo elegido es demasiado larga (más de una hora y media). La descarga se cancela"
                        )
                        if path.exists(video_file):
                            os.remove(video_file)
                        if path.exists(title_file):
                            os.remove(title_file)
                    else:
                        bot.sendMessage(chat_id,
                                        text="_Comenzando la descarga..._",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                        time.sleep(1)
                        sender(bot, update, chat_id, user)
            except IndexError:
                print(
                    "<<<<< IndexError al obtener información sobre el enlace (no existente) >>>>>"
                )
                bot.sendMessage(
                    chat_id,
                    text=
                    "El enlace que nos has proporcionado no se corresponde con ningún vídeo.\n\nRevisa que está escrito correctamente o utiliza el bot @vid para buscar el vídeo (escribe /vid para saber cómo utilizarlo)"
                )
        except AttributeError:  # The message is not containing an URL. So it's simple text message (query = command)
            query = command
            try:
                print("\tEjecutando búsqueda...")
                Id = getVidId(query, chat_id, bot, update)
                url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                    Id, API)
                url_title = "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet&key={}".format(
                    Id, API)
                print("\tURL de la api: ", url2)
                datas = urlopen(url2).read()
                json_data2 = json.loads(datas)
                length = json_data2["items"][0]['contentDetails']['duration']
                data_t = urlopen(url_title).read()
                json_title = json.loads(data_t)
                title = json_title["items"][0]["snippet"]["title"]
                print("\tDuración (ISO): ", length)
                dur = isodate.parse_duration(length)
                print("\tDuración: ", dur)
                durS = dur.total_seconds()
                print("\tDuración en segundos: ", durS)
                if (durS >= 5400):
                    bot.sendMessage(
                        chat_id,
                        "Aquí tienes la URL del vídeo encontrado: http://youtube.com/watch?v="
                        + Id + "")
                    bot.sendMessage(
                        chat_id,
                        "La duración del vídeo es demasiado larga (más de una hora y media).\n\nLa descarga se cancela"
                    )
                else:
                    title_prev = title.translate(
                        {ord(c): None
                         for c in ':"/\!@#$'})
                    title_prev2 = title_prev.replace("." or ",", " ")
                    title1 = title_prev2.translate({
                        ord('á'): 'a',
                        ord('é'): 'e',
                        ord('í'): 'i',
                        ord('ó'): 'o',
                        ord('ú'): 'u',
                        ord('ñ'): 'n'
                    })
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    bot.sendMessage(
                        chat_id,
                        "La canción encontrada es esta: http://youtube.com/watch?v="
                        + Id + " ")
                    key_a(bot, update)
            except ValueError:
                print(
                    "\n\t<<<<<< Error al buscar el vídeo (no encontrado) | ID: ",
                    chat_id, ">>>>>>\n")
                bot.sendMessage(
                    chat_id,
                    "No hemos encontrado ninguna canción en base a los términos de búsqueda especificados.\n\nPrueba a escribir sin tildes o busca tu vídeo con   @vid   directamente desde el teclado"
                )
            except IndexError:
                print(
                    "\n<<<<<<\"IndexError\" heredado de la función anterior (getVidId) | ID: ",
                    chat_id, ">>>>>>\n"
                )  # When IndexError is raised in 'getVidId', main function raises too. So as for this, we set it to "IndexError inherited from getVidId"
    elif 'en' in read_database(chat_id):
        print(
            "\n-----------------------------------------------------------------------------------------------------------------"
        )
        print("Debug [1]")
        print(
            "-----------------------------------------------------------------------------------------------------------------"
        )
        try:
            query0 = re.search("(?P<url>https?://[^\s]+)", command).group(
                "url"
            )  # As the bot is multi-langauge, two functions are needed
            Id = get_yt_video_id(query0)
            try:
                print("\tEjecutando descarga directa...")
                print("\tID: ", Id)
                if (Id == None):
                    raise IndexError(
                        'El enlace proporcionado no tiene un formato conocido, o no contiene el ID del vídeo, o no es un enlace de YouTube'
                    )
                else:
                    stndr_yt = "http://youtube.com/watch?v="
                    title1 = getVidTitle(Id, chat_id, bot, update)
                    url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                        Id, API)
                    print("\tURL API (2): ", url2)
                    datas = urlopen(url2).read()
                    json_data2 = json.loads(datas)
                    length = json_data2["items"][0]['contentDetails'][
                        'duration']
                    print("\tDuración (ISO): ", length)
                    dur = isodate.parse_duration(length)
                    print("\tDuración: ", dur)
                    durS = dur.total_seconds()
                    print("\tDuración en segundos: ", durS)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title1)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    if (durS >= 5400):
                        bot.sendMessage(
                            chat_id,
                            "Video lenght is too long (more than 1 hour and a half). Download cancelled"
                        )
                        if path.exists(video_file):
                            os.remove(video_file)
                        if path.exists(title_file):
                            os.remove(title_file)
                    else:
                        bot.sendMessage(chat_id,
                                        text="_Starting download..._",
                                        parse_mode=telegram.ParseMode.MARKDOWN)
                        time.sleep(1)
                        sender(bot, update, chat_id, user)
            except IndexError:
                print(
                    "<<<<< IndexError al obtener información sobre el enlace (no existente) >>>>>"
                )
                bot.sendMessage(
                    chat_id,
                    text=
                    "The link you provided does not refer to any videos.\n\nCheck if it's writed correctly or use the bot @vid to search the video (type /vid to learn how to use it)"
                )
        except AttributeError:
            query = command
            try:
                print("\tEjecutando búsqueda...")
                Id = getVidId(query, chat_id, bot, update)
                url2 = "https://www.googleapis.com/youtube/v3/videos?id={}&part=contentDetails&key={}".format(
                    Id, API)
                url_title = "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet&key={}".format(
                    Id, API)
                print("\tURL de la api: ", url2)
                datas = urlopen(url2).read()
                json_data2 = json.loads(datas)
                length = json_data2["items"][0]['contentDetails']['duration']
                data_t = urlopen(url_title).read()
                json_title = json.loads(data_t)
                title = json_title["items"][0]["snippet"]["title"]
                print("\tDuración (ISO): ", length)
                dur = isodate.parse_duration(length)
                print("\tDuración: ", dur)
                durS = dur.total_seconds()
                print("\tDuración en segundos: ", durS)
                if (durS >= 5400):
                    bot.sendMessage(
                        chat_id,
                        "Here is the URL of the video found: http://youtube.com/watch?v="
                        + Id + "")
                    bot.sendMessage(
                        chat_id,
                        "Video lenght is too long (more than 1 hour and a half). Download cancelled"
                    )
                else:
                    title_prev = title.translate(
                        {ord(c): None
                         for c in ':"/\!@#$'})
                    title_prev2 = title_prev.replace("." or ",", " ")
                    title1 = title_prev2.translate({
                        ord('á'): 'a',
                        ord('é'): 'e',
                        ord('í'): 'i',
                        ord('ó'): 'o',
                        ord('ú'): 'u',
                        ord('ñ'): 'n'
                    })
                    title_def = unidecode(title1)
                    title_file = "title_{}.txt".format(chat_id)
                    video_file = "url_{}.txt".format(chat_id)
                    file = open(title_file, 'w')
                    file.write(title_def)
                    file.close()
                    file = open(video_file, 'w')
                    yt_url = "https://youtube.com/watch?v={}".format(Id)
                    file.write(yt_url)
                    file.close()
                    bot.sendMessage(
                        chat_id,
                        "The found song is this: http://youtube.com/watch?v=" +
                        Id + " ")
                    key_aen(bot, update)
            except ValueError:
                print(
                    "\n\t<<<<<< Error al buscar el vídeo (no encontrado) | ID: ",
                    chat_id, ">>>>>>\n")
                bot.sendMessage(
                    chat_id,
                    "We did not find any songs based on the specified search terms.\n\nTry typing without titles or searching your video with  @vid  directly from the keyboard"
                )
            except IndexError:
                print(
                    "\n<<<<<<\"IndexError\" heredado de la función anterior (getVidId) | ID: ",
                    chat_id, ">>>>>>\n")
Ejemplo n.º 24
0
def examplethree():
    obj = genSampleObj(
        "sin(z) * z * x * t * cos(t) - z * cos(x) * y * sin(t) * sin(y * t)")
    sender.sender(obj, asyncio.new_event_loop())
    return redirect('/success')
Ejemplo n.º 25
0
filter_=rrcfilter(K*n_up+1,n_up , 1,1)
g=filter_.ir()
#Plot.timesignal(g,"g")
#Channel matrix
H=1/np.sqrt(2)*((np.random.randn(RA,SA))+1j/np.sqrt(2)*(np.random.randn(RA,SA)))
#H=np.array([[1-0.5*1j,1]])
#H=np.array([[0.5,0.1,-0.3j,0.2+0.8j]])
#H=np.array([[-0.3j,-0.3j,-0.3j,-0.3j]])
#H=np.ones([RA,SA])
f_est=[]
    #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#fl=FLL(g,n_up)
gardner=gardner_timing_recovery(n_up)
for i in range(0,1):
    #sender
    sender_=sender(N,N_known,Ni,Nd,mpsk_map,filter_,k)
    print("n_start=",sender_.n_start,sender_.n_start*n_up,(sender_.n_start+N_known)*n_up)
    #training symbols(/bits) which may be shared with receiver, when a data-aided method is used
    symbols_known=sender_.symbols_known
    #symbols_known=ss
    symbols=sender_.symbols
    ibits=sender_.ibits
#    dbits=sender_.dbits
    ibits_known=sender_.ibits_known
    index=bitarray2dec(ibits_known)
   # dbits_known=sender_.dbits_known
    
    
    s_BB=sender_.bbsignal()
    group_delay = (g.size - 1) // 2
#    s_BB=s_BB[group_delay:-group_delay]
Ejemplo n.º 26
0
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   If you have a applicable agreement with GreenSocs Ltd, the terms of that
#   agreement prevail.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
#   02110-1301  USA
#
# ENDLICENSETEXT

import gs

from sender import sender
from receiver import receiver

# Describe the system
sender1 = sender()
receiver1 = receiver()

# Start!
gs.start()
Ejemplo n.º 27
0
def exampleone():
    obj = genSampleObj(
        "z - ((20 / (abs(x * x + y * y) + (20 / 4))) *  sin((x * x + y * y - t)* 1.0)) /5.0"
    )
    sender.sender(obj, asyncio.new_event_loop())
    return redirect('/success')
Ejemplo n.º 28
0
def examplesixth():
    obj = genSampleObj("x * x  + y * y / 3 * 4  - z * z  * 2  - t")
    sender.sender(obj, asyncio.new_event_loop())
    return redirect('/success')
Ejemplo n.º 29
0
def exampleforth():
    obj = genSampleObj("sin(z) * x * t - z * z * cos(y)")
    sender.sender(obj, asyncio.new_event_loop())
    return redirect('/success')
Ejemplo n.º 30
0
	def __init__(self, ServerIP, ServerPort):
		self.ServerAddr = (ServerIP, ServerPort)
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.connect(self.ServerAddr)
		self.Receiver = receiver.receiver(self.sock)
		self.Sender = sender.sender(self.sock)
Ejemplo n.º 31
0
from sender import sender
from receiver import receiver
sender('text', 'text1', 'text2')
sender('text1', 'text', 'text2')
receiver('text2')
Ejemplo n.º 32
0
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
# 
#   If you have a applicable agreement with GreenSocs Ltd, the terms of that
#   agreement prevail.
# 
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
# 
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
#   02110-1301  USA 
# 
# ENDLICENSETEXT

import gs_sa as gs

from sender import sender
from receiver import receiver


# Describe the system
sender1 = sender()
receiver1 = receiver()

# Start!
gs.start()
Ejemplo n.º 33
0
def sm(SNR_dB,N,N_known,threshold):
#def sm(SNR_dB,n):
    #number of sender antennas
    SA=4
    #number of receiver antennas
    RA=4
    #data bits modulation order (BPSK)
    M=2
    mpsk_map=np.array([1,-1])
    #mpsk_map =1/np.sqrt(2) * np.array([1+1j, -1+1j, 1-1j, -1-1j], dtype=complex)
    #symbol duration
    T=1*1e-6
    #Frequency offset
    #f_off=np.random.randint(-0.001/T,0.001/T)
    f_off=np.random.randint(0.01/T,0.05/T)
#    N_known=int(1//T//f_off/n)
#    N=10*N_known
    #phase offset
    phi_off=np.random.random()*2*np.pi
    #number of Index bits per symbol
    Ni=int(np.log2(SA))
    #number of Data bits per symbol
    Nd=int(np.log2(M))
            #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Upsampling rate
    n_up=1
    # RRC Filter (L=K * sps + 1, sps, t_symbol, rho)
    filter_=rrcfilter(8*n_up+1,n_up , 1,0.5)
            #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Channel matrix
    H=1/np.sqrt(2)*((np.random.randn(RA,SA))+1j/np.sqrt(2)*(np.random.randn(RA,SA)))
    #H=np.ones([RA,SA])
            #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #sender
    sender_=sender(N,N_known,Ni,Nd,mpsk_map,filter_)
    #print("n_start=",sender_.n_start)
    #training symbols(/bits) which may be shared with receiver, when a data-aided method is used
    symbols_known=sender_.symbols_known
    ibits=sender_.ibits
    dbits=sender_.dbits
    n_start=sender_.n_start
    ibits_known=sender_.ibits_known
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #with Filter(noch zu bearbeiten,überabtastung!)
    receiver_=receiver(H,sender_,SNR_dB,filter_,mpsk_map)
    receiver_.channel()
    r_mf=receiver_.r_mf
    
    #BER for perfect sync
    yi,yd=receiver_.detector(r_mf,H)
    BERi_0,BERd_0=test.BER(yi,yd,Ni,Nd,ibits,dbits)
    
    
    #with offsets
    off=np.exp(1j*2*np.pi*f_off*np.arange(r_mf.shape[0])*T/filter_.n_up)
    r_off_ft=r_mf*np.repeat(off,RA).reshape([-1,RA])*np.exp(1j*phi_off)

 
    
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #coarse Estimation for f_off (draft)
    f_off_coarse=0
    

        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #coarse synchronisation 
    off_syc=np.exp(-1j*2*np.pi*f_off_coarse*np.arange(r_mf.shape[0])*T/filter_.n_up)
    r_syc_coarse=r_off_ft*np.repeat(off_syc,RA).reshape([-1,RA])
    
      #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Sampling Clock Synchronization
    
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Joint Estimation for f_off,n_start and CSI 
    j=joint_estimation()
    j.function(r_syc_coarse,N,N_known,T,ibits_known,symbols_known,SA,RA)
    f_est=j.f_est
    n_est=j.n_est
    H_est=j.H_est

        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Synchronisation
    off_syc=np.exp(-1j*2*np.pi*f_est*(np.arange(r_mf.shape[0]))*T)
    r_f_syc=r_syc_coarse*np.repeat(off_syc,RA).reshape([-1,RA])
    
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #Detection and BER Test 
    yi,yd=receiver_.detector(r_f_syc,H_est)
    #yi,yd=rr.detector(H_est,SNR_dB,mpsk_map,r_ft_syc)
    BERi,BERd=test.BER(yi,yd,Ni,Nd,ibits,dbits)
    
    
    #
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    #
    #if BERi<=threshold and BERd<=threshold and n_start==n_est:
    if n_start==n_est:
        count=1
    else:
        count=0
        
    
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    return count    
Ejemplo n.º 34
0
parser.add_argument(
    '-p',
    dest='port',
    type=int,
    help=('Specifies the port number that the chat will listen and send at. '
          'Default is {}.'.format(DEFAULT_PORT)),
    default=DEFAULT_PORT,
    metavar='PORT')
parser.add_argument(
    '-d',
    dest='dest',
    help=('Specifies the broadcast ip address. '
          'Default is the local subnetwork {}.'.format(DEFAULT_BROADCAST_IP)),
    default=DEFAULT_BROADCAST_IP,
    metavar='BROADCAST-IP')

args = parser.parse_args()

username = input('Enter your name:')

receiveThread = Thread(target=receiver,
                       kwargs={
                           'port': args.port,
                           'username': username,
                           'broadcast_ip': args.dest
                       })
receiveThread.start()
time.sleep(1)  # Make sure the receiver is listening before starting to send
sender(username=username, ip_address=args.dest, port=args.port)
Ejemplo n.º 35
0
def botones(
    bot, update, chat_id, message_id, value, user
):  # 'value' is obtained from "def buttons" in 'TeleBotSongDownloader.py'
    star = "https://goo.gl/12AADY"
    hour_spain = "http://24timezones.com/es_husohorario/madrid_hora_actual.php"
    hour_eng = "http://24timezones.com/world_directory/time_in_madrid.php"
    if value == "1":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Prueba a intentar la descarga de nuevo.\n\nPrueba a introducir la URL del vídeo directamente (suele funcionar en la mayoría de los casos).\n\nDisculpa las molestias. *Si necesitas más ayuda*, escribe  /errors",
                chat_id=chat_id,
                message_id=message_id,
                parse_mode=telegram.ParseMode.MARKDOWN)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Retry the download.\n\nTry to put the video URL directly (it usually works in almos cases).\n\nSorry for the inconvenience. *If you need more help*, type  /errors",
                chat_id=chat_id,
                message_id=message_id,
                parse_mode=telegram.ParseMode.MARKDOWN)
    elif value == "2":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Muchas gracias por utilizarme 😄\n\n\nPara descargar otra canción, puedes: \n\nescribirme directamente el *título* 🎵,\nmandar la *URL* del vídeo 📎,\n*buscar* el vídeo con  @vid ▶,\n/help _para más ayuda_\n\n*¿Te gusta este bot?* 👍 No dudes en enviarme tus comentarios [haciendo clic aquí]("
                + star + ")",
                parse_mode=telegram.ParseMode.MARKDOWN,
                chat_id=chat_id,
                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Thank you so much for using me 😄\n\n\nTo download another song, you can: \n\nsend me directly *the title of the video* 🎵,\nsend me *the URL of the video* 📎,\n*search the video* with @vid ▶,\n/help _for get assistance_\n\n*Do you like this bot?* 👍 Please send me your opinions [by clicking here]("
                + star + ")",
                parse_mode=telegram.ParseMode.MARKDOWN,
                chat_id=chat_id,
                message_id=message_id)

    elif value == "Ax":
        if 'es' in read_database(chat_id):
            bot.editMessageText(text="_Comenzando la descarga..._",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(text="_Starting download..._",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        sender(bot, update, chat_id, user)
    elif value == "Ay":
        if 'es' in read_database(chat_id):
            bot.editMessageText(text="*Descarga cancelada*",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(text="*Download cancelled*",
                                parse_mode=telegram.ParseMode.MARKDOWN,
                                chat_id=chat_id,
                                message_id=message_id)
        if path.exists(title_file):
            os.remove(title_file)
        if path.exists(video_file):
            os.remove(video_file)
    elif value == "en":
        bot.editMessageText(
            text=
            "_Preferences updated correctly..._\n\nIf you want to *change your language*, just use the command /preferences\n\n_If you were trying to download a video, please start again._",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        data = None
        write_database(user, chat_id, value, data)
    elif value == "es":
        bot.editMessageText(
            text=
            "_Preferencias actualizadas correctamente..._\n\nPara *cambiar el idioma en cualquier momento*, ejecuta /preferences\n\n_Si estabas intentando descargar un vídeo, por favor comienza de nuevo._",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        data = None
        write_database(user, chat_id, value, data)
    elif value == "glish":
        bot.editMessageText(
            text=
            "_Preferences updated correctly..._\n\nIf you want to *change your language*, just use the command /preferences",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        value = "en"
        data = "Something"
        write_database(user, chat_id, value, data)
    elif value == "castell":
        bot.editMessageText(
            text=
            "_Preferencias actualizadas correctamente..._\n\nPara *cambiar el idioma en cualquier momento*, ejecuta /preferences",
            parse_mode=telegram.ParseMode.MARKDOWN,
            chat_id=chat_id,
            message_id=message_id)
        value = "es"
        data = "Something"
        write_database(user, chat_id, value, data)
    elif value == "Ed":
        key_ed(bot, update, chat_id)
    elif value == "O":
        key_o(bot, update, chat_id)
    elif value == "V":
        bot.sendMessage(
            chat_id,
            text=
            "Algunas veces, el servidor *sufre un colapso* 😫 y no se envían correctamente las canciones.\
        \n\nEsto se soluciona volviendo a pedirle al servidor que _descargue la canción_",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "U":
        bot.sendMessage(
            chat_id,
            text=
            "Cuando el vídeo no puede ser obtenido _directamente desde Telegram_ (a causa del servidor de descargas), \
se manda un *enlace* 📎 para descargarlo y luego ya se puede conseguir directamente desde Telegram",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Z":
        bot.sendMessage(
            chat_id,
            text=
            "El bot puede no mostrar respuesta debido a un error ⚠ que no tenemos registrado. \
Todos los días revisamos los errores del bot, por lo que debería solucionarse en esta semana 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "S":
        bot.sendMessage(
            chat_id,
            text=
            "Cuando se produce una descarga muy lenta, entran en juego varios factores fundamentales:\
        \n\nSi la canción 🎶 que quieres descargar es *muy larga*, se va a necesitar mayor tiempo 🕒 dependiendo de la _calidad de audio_ que tengas elegida (usa /preferences para cambiarlo)\
        \n\n*Tu ubicación* 🛰 es determinante, pues cuanto más lejos te encuentres del servidor más se tarda.\
        \n*Los usuarios activos* 👨‍👩‍👧‍👦 provocan una demora en los tiempos de descarga.\n*El servidor puede haberse bloqueado* 🌁.\
        \n*El servidor de descargas* ❌ no responde, siendo esta última la razón más usual para descargas lentas.\
        \n\nSin poder decir mucho más, *paciencia*: tarde o temprano la canción se acaba enviando y sino, pondremos medios para ello 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "LK":
        bot.sendMessage(
            chat_id,
            text=
            "Es posible que seas el descubridor de *un fallo nuevo* (weeh 😱👏🎉‼),\
 por lo que si quieres comentarlo ve a [este enlace](" + star +
            "), puntúa el bot ⭐ y a continuación, *deja una reseña* 📝.\nLas leemos _todos los días_, por lo que agradeceremos mucho tu aportación.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "fi":
        bot.sendMessage(
            chat_id,
            text=
            "Algunas veces, introduciendo *solo el nombre de la canción* 🎤 o *solo el artista* 💃 no es suficiente para el bot para encontrar *la canción que quieres*.\
        \n\nPara ello, te recomendamos que *ejecutes* /vid *para obtener una canción concreta* desde Telegram.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "mn":
        bot.sendMessage(
            chat_id,
            text=
            "_A continuación se muestran todos los errores registrados más comunes:_\n\n\n \"El bot manda un mensaje diciendo que *no se puede descargar* pero me manda un link para hacerlo\"\n\nEsto se produce en la mayoría de los casos debido a que la *página de descargas todavía no tiene la información que necesita Telegram para poder descargar el vídeo directamente*.\nUna vez lo descargas desde la página web, se suele _poder descargar desde el bot_.\n\n \"El bot dice que *no se ha encontrado nada*\"\n\nEsto se suele producir porque o bien *solo has introducido el nombre del artista* o porque *el vídeo no existe*. Prueba a utilizar el Bot   @vid    para _mandar directamente la URL del vídeo que quieras obtener_. (escribe   /vid    para más información).\n\n\"El archivo de audio tiene una parte que pone un número del estilo: _\"1234567\"_\"\n\nEl archivo que se envía tiene una ID asociada a cada usuario pues así no se extravía por el camino o produce algún fallo en el servidor.\nEstamos trabajando en una solución posible.\n\n\"El bot *tarda mucho en descargar* algunas canciones\"\n\nCuando ocurre esto, puede ser o bien porque nuestro servidor está *colapsado con solicitudes* o porque la plataforma que utilizamos para descargar el vídeo *no responde o tiene que atender demasiadas peticiones*. No hay solución posible más que esperar a que se envíe la canción o, en su defecto, un enlace para descargarla.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Eden":
        key_eden(bot, update, chat_id)
    elif value == "Oen":
        key_oen(bot, update, chat_id)
    elif value == "Ven":
        bot.sendMessage(
            chat_id,
            text=
            "Sometimes the server *collapses* 😫 and the songs are not sent correctly.\
        \n\nThis is resolved by asking the server again to _download the song_",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Uen":
        bot.sendMessage(
            chat_id,
            text=
            "When a video can't be obtained _directly from Telegram_ (because of the download server), \
we provide you *a link* 📎 for downloading and then you can get it directly from Telegram",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Zen":
        bot.sendMessage(
            chat_id,
            text=
            "The bot can be not able to show response because of a non-registered error ⚠. \
We check everyday the information about happened errors and it should be solved in this week 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "Sen":
        bot.sendMessage(
            chat_id,
            text=
            "When a very slow download is happening, some key factors are relevant:\
        \n\nIf the song 🎶 you were trying to download is *very long*, more time is needed 🕒 depending on chosen _audio quality_ (use /preferences for changing it)\
        \n\n*Your location* 🛰 is determinant, as when far away you are from the server and it takes longer to send you the song.\
        \n*Active users* 👨‍👩‍👧‍👦 can cause a delay in download-times.\n*Server can have got frozen* 🌁.\n*Download server* is not responding ❌, being this the most usual reason why downloads perform slowly.\
        \n\nI can only tell you *patience*: sooner or later your song will be availabe to download from Telegram by a way or other 😄",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "LKen":
        bot.sendMessage(
            chat_id,
            text=
            "It's possible that you are the discoverer of a *new error* (weeh 😱👏🎉‼), so if you would like us to get known about it go to [this link]("
            + star + "), \
rate the bot ⭐ an then *leave a review* 📝.\nWe read them _every day_, so we will appreciate so much your contribution.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "fien":
        bot.sendMessage(
            chat_id,
            text=
            "Sometimes, giving the bot *only the name of the song* 🎤 or *only the artist* 💃 is not enough to find *the song you are looking for*.\
\n\nFor this, we recommend you *to execute* /vid *in order to get a specific song* directly from Telegram.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "mnen":
        bot.sendMessage(
            chat_id,
            text=
            "_Now we are displaying all registered common-errors:_\n\n\n \"The bot sends a message telling that *is not possible to download the song* but sends me a link to do it\"\n\nThis happens because *the download page we use still not have the information needed by Telegram to download the video directly*.\nOnce you have downloaded it from the web page, you can usually _download it from the bot_.\n\n \"The bot says that *nothing was found*\"\n\nThis usually happens because or *you have only send the artist name* or because *the video doesn't exist*. Try to use the bot  @vid  to _send the video URL directly_ (type  /vid  to learn how to use this bot).\n\n\"The audio file has a numbered part like: _\"1234567\"_\"\n\nThe audio file the bot sends you has your ID attached in order to send it only to you.\nWe are working on a possible solution.\n\n\"It takes a long time for the bot to download songs\"\n\nWhen this occur, can be becauseour server is *collapsed* or most probably because the *download platform* we are using is down. There is no possible solution more than waiting for the video to be downloaded.",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=ReplyKeyboardRemove())
    elif value == "3":
        bot.editMessageText(text="Por favor, espere...",
                            chat_id=chat_id,
                            message_id=message_id)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        try:
            url_file = descarga(mp3_name)
        except FileNotFoundError:
            url_file = descarga(complete_name_file)
        bot.sendMessage(
            text=
            "Para los usuarios de dispositivos iOS 📱 (iPhone - iPad), aquí tenéis un enlace de [descarga directa]("
            + url_file +
            ") (_recomendamos utilizar un explorador alternativo a Safari pues sino no se podrán guardar las descargas_. Prueba con *Dolphin Browser*",
            chat_id=chat_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        value = "iOS"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_f(bot, update, chat_id)
        except PermissionError:
            key_f(bot, update, chat_id)
    elif value == "5":
        bot.editMessageText(text="Please, wait...",
                            chat_id=chat_id,
                            message_id=message_id)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        try:
            url_file = descarga(mp3_name)
        except FileNotFoundError:
            url_file = descarga(complete_name_file)
        bot.sendMessage(
            text=
            "For iOS users 📱 (iPhone - iPad), here you have [a direct download link]("
            + url_file +
            ") (_we recommend to use an alternative browser to Safari in order to save your song_. Try with *Dolphin Browser*",
            chat_id=chat_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        value = "iOS"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_fen(bot, update, chat_id)
        except PermissionError:
            key_fen(bot, update, chat_id)
    elif value == "4":
        bot.editMessageText(
            text=
            "Perfecto, muchas gracias por tu colaboración (era solo para ayudar a los usuarios de iOS con la descarga)",
            chat_id=chat_id,
            message_id=message_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        value = "Android"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_f(bot, update, chat_id)
        except PermissionError:
            key_f(bot, update, chat_id)
    elif value == "6":
        bot.editMessageText(
            text=
            "Perfect, thank you so much for your colaboration (that was only for helping iOS users with the download)",
            chat_id=chat_id,
            message_id=message_id,
            parse_mode=telegram.ParseMode.MARKDOWN)
        title_file = "title_{}.txt".format(chat_id)
        video_file = "url_{}.txt".format(chat_id)
        save_path = '/home/javialonso/BOT/Songs/'
        link = open(video_file, 'r')
        titulo = open(title_file, 'r')
        url = link.readline()
        name = titulo.readline()
        link.close()
        titulo.close()
        Id = get_yt_video_id(url)
        ad_quality = read_audio(chat_id)
        if ad_quality == None:
            ad_quality = "256k"
        mp3_name = "{}_{}_{}.mp3".format(name, Id, ad_quality)
        complete_name_file = save_path + mp3_name
        value = "Android"
        write_os(chat_id, user, value)
        try:
            if path.exists(video_file):
                os.remove(video_file)
            if path.exists(title_file):
                os.remove(title_file)
            if path.exists(mp3_name):
                os.rename('/home/javialonso/BOT/' + mp3_name,
                          complete_name_file)
            key_fen(bot, update, chat_id)
        except PermissionError:
            key_fen(bot, update, chat_id)
    elif value == "lang":
        bot.editMessageText(text="Actualizando preferencias de idioma...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_l(bot, update, chat_id)
    elif value == "langen":
        bot.editMessageText(text="Updating language preferences...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_l2(bot, update, chat_id)
    elif value == "os":
        bot.editMessageText(
            text="Actualizando preferencias de sistema operativo...",
            chat_id=chat_id,
            message_id=message_id)
        key_os(bot, update, chat_id)
    elif value == "osen":
        bot.editMessageText(text="Updating operative system preferences...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_osen(bot, update, chat_id)
    elif value == "droid":
        bot.editMessageText(
            text=
            "Preferencias actualizadas correctamente...\n\nUsa /preferences para cambiarlas en cualquier momento",
            chat_id=chat_id,
            message_id=message_id)
        value = "Android"
        write_os(chat_id, user, value)
    elif value == "droiden":
        bot.editMessageText(
            text=
            "Preferences updated correctly...\n\nUse /preferences for changing them whenever you want",
            chat_id=chat_id,
            message_id=message_id)
        value = "Android"
        write_os(chat_id, user, value)
    elif value == "ios":
        bot.editMessageText(
            text=
            "Preferencias actualizadas correctamente...\n\nUsa /preferences para cambiarlas en cualquier momento",
            chat_id=chat_id,
            message_id=message_id)
        value = "iOS"
        write_os(chat_id, user, value)
    elif value == "iosen":
        bot.editMessageText(
            text=
            "Preferences updated correctly...\n\nUse /preferences for changing them whenever you want",
            chat_id=chat_id,
            message_id=message_id)
        value = "iOS"
        write_os(chat_id, user, value)
    elif value == "ad":
        bot.editMessageText(
            text="Actualizando preferencias de calidad de audio...",
            chat_id=chat_id,
            message_id=message_id)
        key_ad(bot, update, chat_id)
    elif value == "aden":
        bot.editMessageText(text="Updating audio quality preferences...",
                            chat_id=chat_id,
                            message_id=message_id)
        key_aden(bot, update, chat_id)
    elif value == "LQ":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
                chat_id=chat_id,
                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Audio quality preferences saved correctly. Use /preferences for changing them whenever you want",
                chat_id=chat_id,
                message_id=message_id)
        value = "120k"
        set_audio(chat_id, value)
    elif value == "MQ":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
                chat_id=chat_id,
                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Audio quality preferences saved correctly. Use /preferences for changing them whenever you want",
                chat_id=chat_id,
                message_id=message_id)
        value = "256k"
        set_audio(chat_id, value)
    elif value == "HQ":
        if 'es' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Calidad de audio guardada correctamente. Usa /preferences para cambiarla en cualquier momento",
                chat_id=chat_id,
                message_id=message_id)
        elif 'en' in read_database(chat_id):
            bot.editMessageText(
                text=
                "Audio quality preferences saved correctly. Use /preferences for changing them whenever you want",
                chat_id=chat_id,
                message_id=message_id)
        value = "320k"
        set_audio(chat_id, value)
Ejemplo n.º 36
0
def examplefifth():
    obj = genSampleObj("z -  cos( sqrt( x * x + y * y ) ) - t")
    sender.sender(obj, asyncio.new_event_loop())
    return redirect('/success')
Ejemplo n.º 37
0
def Send_eamil(sender, password, content, receive):
    receives = receive
    msg = MIMEMultipart()

    msg["Subject"] = "雲涯筆尖文化"
    msg["From"] = sender
    if len(receives) > 1:
        msg["To"] = ",".join(receives)
    else:
        msg["To"] = receives[0]

    part = MIMEText(content, _charset="UTF-8")
    msg.attach(part)
    try:
        smtp = smtplib.SMTP_SSL("smtp.126.com")
        smtp.login(sender, password)
        smtp.sendmail(sender, receives, msg.as_string())

        print("邮件发送成功")

    except smtplib.SMTPException as e:
        print("ERROR,发送失败")
    finally:
        smtp.quit()


sender, password = sender.sender()
content = "测试邮件发送功能"
recevice = ["*****@*****.**"]
Send_eamil(sender, password, content, recevice)