Bot de Telegram, expresando tus emociones en un mensaje

¡Hola!



En este artículo, describiré mi bot de telegramas, que todavía está funcionando.



Por qué se creó el bot, su propósito y habilidades



En realidad, una persona usa una variedad de sonidos para expresar sus emociones y relaciones. Pero casi todos los sistemas de inteligencia artificial y asistentes de voz son "demasiado inteligentes". Simplemente descartan los sonidos emocionales, no comprenden y no pueden usar las interjecciones correctamente. Por eso, creé un bot, y abre la posibilidad de un habla natural, llena de tarareos, chillidos, sollozos, gruñidos y un centenar de otros tonos emocionales y semitonos.

Supongo que el algoritmo desarrollado funcionará en el sector comercial, por ejemplo, rastreando el estado emocional del cliente y dirigiendo la ramificación del algoritmo para prevenir sus posibles acciones. Las emociones son los primeros reguladores del comportamiento, y por el tono del habla o, por ejemplo, por una risa, es fácil rastrear la confusión e irritación del usuario y reaccionar antes de que comience a maldecir y exigir.

También puede darles a los propios asistentes de voz más "humanidad". Es posible que se aclaren la garganta antes de una larga conferencia o una sonrisa en lugar de explicar con una voz estándar que se trataba de una broma.

En la práctica médica, el programa ayudará a determinar la condición de un paciente que no puede hablar articuladamente y, mediante sollozos individuales, guiará al personal hacia el procedimiento de tratamiento. Se puede aplicar a categorías específicas de enfermedades como el autismo y la dislexia.

En la mensajería instantánea, el bot ayudará a transmitir sentimientos y relaciones a través de la red en pie de igualdad, además o en lugar de los emoji estándar.

Como plataforma de experimentación y desarrollo, utilizo Telegram messenger.

Por el momento, @YouToneBot devuelve el sonido de la emoción al smiley estándar.

En el futuro, está previsto enseñar al bot a realizar la operación inversa, es decir, a emitir "emoji" al tono del sonido.



¿Cómo será al final?



, , ! , , .



imagen

imagen

imagen



, , . , , .

Python, PyTelegramBotApi.

, . , , , .. PyTelegramBotApi send_voice() id , message_handler() message.voice.file_id.

, : JSON , , id .

, , id, . , "python ", , id .

:



{
    "emoji1": "voice_id1",
    "emoji2": "voice_id2",
    "emoji3": "voice_id3",
    "emoji4": "voice_id4",
    "emoji5": "voice_id5",
    "emoji6": "voice_id6",
}
#-   ,  "emoji" == ~


.



.

YouTone(), .

def init(self) TOKEN, VOICE_SOUNDS

TOKEN

VOICE_SOUNDS — , id #

, init, self.BOT,



TL.TeleBot(self.TOKEN)


, .

, 3 ,

LS_handler()

start_handler() — (/start /get)

local_lerning()

LS_handler() echo



LS_handler()
def LS_handler(self):
    @self.BOT.message_handler(content_types=['text'])
    def send_text(message):
        def msg(message_text):
            self.BOT.send_message(message.chat.id, str(message_text))
        msg(message.text)


start_handler() /start



start_handler()
def start_handler(self):
    @self.BOT.message_handler(commands=['start', "get"])
    def commands(message):
        if message.text == "/start":
            self.BOT.send_message(message.chat.id, '.      ')


local_lerning(). , , , .

, tkinter. tkitner , , tkitner " ", " ", ( ):



id



3 ,

window_smile() — tkitner

bot_work() — , .

save_sound() — id



, window_smile()



window_smile()
def window_smile():#    local_lerning()
    self.root = Tk()
    self.root.geometry("500x500")
    self.smile_tkinter = Label(text=self.AUDIO_SOUNDS_ITEMS[self.index][0],font='Times 30')
    self.open_sound = Button(text=" ",font='Times 10',command=lambda: webbrowser.open(url=r"/////.ogg"))
    self.Y_or_N = Button(text=" ",font='Times 15',command=save_sound)
    self.info = Label(text="""\n\n\n\n\n\n\n  , ,\n ,\n  ' ',\n  ,\n   ,\n ,\n   .""",font="Consolas 11")
    self.smile_tkinter.pack()
    self.open_sound.pack()
    self.Y_or_N.pack()
    self.info.pack()
    self.root.mainloop() 


bot_work() , , "/////.ogg",



bot_work()
def bot_work():
    @self.BOT.message_handler(content_types=['text',"voice"])
    def send_text(message):
        def msg(message_text):
            self.BOT.send_message(message.chat.id, str(message_text))
        self.smile_now = self.SOUNDS_DB[self.index][0]
        self.smile_tkinter.config(text=self.smile_now)

        try:
            self.id_voice = message.voice.file_id
            self.voice_info = self.BOT.get_file(file_id=self.id_voice)
            self.voice_file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(self.TOKEN, self.voice_info.file_path)).content

        except BaseException as e:
            print(e)
        else:
            with open("/////.ogg", "wb") as f:
                f.write(self.voice_file)


get_file(), id ( ), id requests, .

id , self.voice_id.



save_sound()
def save_sound():

    self.voices_good.update({self.smile_now:str(self.id_voice)})
    self.index += 1
    self.smile_now = self.SMILES_DB[self.index][0]

    self.smile_tkinter.config(text=self.smile_now)
    with open("data.txt","w",encoding="utf-8") as f:
        f.write(str(self.voices_good))


" ".

.

, self.index, , .. self.SMILES_DB



local_lerning(), 2 ,

window_smile() bot_work().

threading.



from threading import Thread
th1 = Thread(target=window_smile)
th1.start()
th2 = Thread(target=bot_work)
th2.start()


local_lerning()
def local_lerning(self):
    from threading import Thread
    self.smile_now = None
    self.index = 0
    self.id_voice = None
    self.voices_good = {

    }
    self.smile_tkinter = None

    def save_sound():

        self.voices_good.update({self.smile_now:str(self.id_voice)})
        self.index += 1
        self.smile_now = self.AUDIO_SOUNDS_ITEMS[self.index][0]

        self.smile_tkinter.config(text=self.smile_now)
        with open("data.txt","w",encoding="utf-8") as f:
            f.write(str(self.voices_good))

    def window_smile():
        self.root = Tk()
        self.root.geometry("500x500")
        self.smile_tkinter = Label(text=self.AUDIO_SOUNDS_ITEMS[self.index][0],font='Times 30')
        self.open_sound = Button(text=" ",font='Times 10',command=lambda: webbrowser.open(url=r"C:\Program Files\JetBrains\projects\telegram\voice.ogg"))
        self.Y_or_N = Button(text=" ",font='Times 15',command=save_sound)
        self.info = Label(text="""\n\n\n\n\n\n\n  , ,\n ,\n  ' ',\n  ,\n   ,\n ,\n   .""",font="Consolas 11")
        self.smile_tkinter.pack()
        self.open_sound.pack()
        self.Y_or_N.pack()
        self.info.pack()
        self.root.mainloop()

    def bot_work():
        @self.BOT.message_handler(content_types=['text',"voice"])
        def send_text(message):
            def msg(message_text):
                self.BOT.send_message(message.chat.id, str(message_text))

            def snd_doc(name_doc):
                self.BOT.send_document(message.chat.id, open(name_doc, "rb"))

            self.smile_now = self.AUDIO_SOUNDS_ITEMS[self.index][0]
            self.smile_tkinter.config(text=self.smile_now)

            try:
                self.id_voice = message.voice.file_id
                self.voice_info = self.BOT.get_file(file_id=self.id_voice)
                self.voice_file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(self.TOKEN, self.voice_info.file_path)).content

            except BaseException as e:
                print(": ",e)
            else:
                with open("voice.ogg", "wb") as f:
                    f.write(self.voice_file)

    th1 = Thread(target=window_smile)
    th1.start()
    th2 = Thread(target=bot_work)
    th2.start()


.

imagen



, . .

, .



. , inline.

, , , , , .



message_list = list(message.text)
is_send = False
for word in message_list:
    if word in self.VOICE_SOUNDS:
        if self.VOICE_SOUNDS[word]:
            snd_voice(voice_id=self.VOICE_SOUNDS[word])
            print("smile has been found")
            is_send = True
            break
if not is_send:
    print("smile has been not found")


LS_handler()
def LS_handler(self):
    @self.BOT.message_handler(content_types=['text'])
    def send_text(message):
        def msg(message_text):
            self.BOT.send_message(message.chat.id, str(message_text))

        def snd_doc(name_doc):
            self.BOT.send_document(message.chat.id, open(name_doc, "rb"))
        def snd_voice(voice_id: str):
            self.BOT.send_voice(message.chat.id,voice=voice_id)

        message_list = list(message.text)
        is_send = False
        for word in message_list:
            if word in self.VOICE_SOUNDS:
                if self.VOICE_SOUNDS[word]:
                    snd_voice(voice_id=self.VOICE_SOUNDS[word])
                    is_send = True
                    break
        if not is_send:
            msg("      


LS_handler(), , inline_handler()



inline

inline , , , -



inline_handler()
def inline_handler(self):
    @self.BOT.inline_handler(lambda query: len(query.query) > 0)
    def query_text(query):
        message_list = list(query.query)
        #    ,   ,   ;)
        output_msg = [types.InlineQueryResultArticle(
            id="1",
            title="      ",
            input_message_content=types.InputTextMessageContent(message_text="     ")
        )]
        is_send = False
        id_now = 1#id  
        for word in message_list:
            try:
                self.VOICE_SOUNDS[word]
            except KeyError:
                pass
            else:
                if self.VOICE_SOUNDS[word]:
                    if is_send == False:
                        output_msg = []
                    is_send = True
                    if not word in [i.title for i in output_msg]:#       ,    ;)
                        output_msg.append(types.InlineQueryResultCachedVoice(
                            id=str(id_now),
                            voice_file_id=self.VOICE_SOUNDS[word],
                            title=str(word),
                            caption=query.query
                        ))
                    else:
                        pass#           
                    id_now +=1 #    id  
        self.BOT.answer_inline_query(query.id, output_msg)


, , — .

.. , , ( break), , . .



inline



imagen



, , .

@YouToneBot , , , .. .

!




All Articles