Costruire il tuo primo robot Telegram: una guida passo passo
Pubblicato: 2022-03-11I chatbot sono spesso pubblicizzati come una rivoluzione nel modo in cui gli utenti interagiscono con la tecnologia e le aziende. Hanno un'interfaccia abbastanza semplice rispetto alle app tradizionali, poiché richiedono solo agli utenti di chattare e i chatbot dovrebbero capire e fare tutto ciò che l'utente richiede loro, almeno in teoria.
Molti settori stanno spostando il loro servizio clienti sui sistemi di chatbot. Ciò sia per l'enorme calo dei costi rispetto agli esseri umani reali, sia per la robustezza e la disponibilità costante. I chatbot offrono un certo grado di supporto agli utenti senza sostanziali costi aggiuntivi.
Oggi i chatbot vengono utilizzati in molti scenari, che vanno da attività umili come la visualizzazione di dati temporali e meteorologici a operazioni più complesse come diagnosi mediche rudimentali e comunicazione/supporto con i clienti. Puoi ideare un chatbot che aiuterà i tuoi clienti quando fanno determinate domande sul tuo prodotto, oppure puoi creare un chatbot assistente personale in grado di gestire attività di base e ricordarti quando è il momento di andare a una riunione o in palestra.
Ci sono molte opzioni quando si tratta di dove distribuire il tuo chatbot e uno degli usi più comuni sono le piattaforme di social media, poiché la maggior parte delle persone le usa regolarmente. Lo stesso si può dire delle app di messaggistica istantanea, anche se con alcuni avvertimenti.
Telegram è una delle piattaforme di messaggistica istantanea più popolari oggi, poiché ti consente di archiviare messaggi sul cloud anziché solo sul tuo dispositivo e vanta un buon supporto multipiattaforma, poiché puoi avere Telegram su Android, iOS, Windows e quasi qualsiasi altra piattaforma in grado di supportare la versione web. Costruire un chatbot su Telegram è abbastanza semplice e richiede pochi passaggi che richiedono pochissimo tempo per essere completati. Il chatbot può essere integrato nei gruppi e nei canali di Telegram e funziona anche da solo.
In questo tutorial, creeremo un bot di Telegram che ti darà un'immagine avatar da Adorable Avatars. Il nostro esempio riguarderà la creazione di un bot utilizzando Flask e la sua distribuzione su un server Heroku gratuito.
Per completare questo tutorial, avrai bisogno di Python 3 installato sul tuo sistema e delle abilità di codifica Python. Inoltre, una buona comprensione di come funzionano le app sarebbe una buona aggiunta, ma non un must, poiché esamineremo la maggior parte delle cose che presentiamo in dettaglio. Hai anche bisogno di Git installato sul tuo sistema.
Naturalmente, il tutorial richiede anche un account Telegram, che è gratuito. Puoi iscriverti qui. È richiesto anche un account Heroku e puoi ottenerlo gratuitamente qui.
Dai vita al tuo robot Telegram
Per creare un chatbot su Telegram, devi contattare il BotFather, che è essenzialmente un bot utilizzato per creare altri bot.
Il comando di cui hai bisogno è /newbot
che porta ai seguenti passaggi per creare il tuo bot:
Il tuo bot dovrebbe avere due attributi: un nome e un nome utente. Il nome verrà visualizzato per il tuo bot, mentre il nome utente verrà utilizzato per le menzioni e la condivisione.
Dopo aver scelto il nome e il nome utente del bot, che devono terminare con "bot", riceverai un messaggio contenente il token di accesso e ovviamente dovrai salvare il token di accesso e il nome utente per dopo, poiché ne avrai bisogno.
Codifica la logica del chatbot
Useremo Ubuntu in questo tutorial. Per gli utenti Windows, la maggior parte dei comandi qui funziona senza problemi, ma se dovessi riscontrare problemi con la configurazione dell'ambiente virtuale, consulta questo link. Per quanto riguarda gli utenti Mac, questo tutorial dovrebbe funzionare bene.
Innanzitutto, creiamo un ambiente virtuale. Aiuta a isolare i requisiti del tuo progetto dal tuo ambiente Python globale.
$ python -m venv botenv/
Ora avremo una directory botenv/
che conterrà tutte le librerie Python che useremo. Vai avanti e attiva virtualenv
usando il seguente comando:
$ source botenv/bin/activate
Le librerie di cui abbiamo bisogno per il nostro bot sono:
- Flask: un framework micro web costruito in Python.
- Python-telegram-bot: un wrapper di Telegram in Python.
- Richieste: una popolare libreria http Python.
Puoi installarli nell'ambiente virtuale usando il comando pip come segue:
(telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests
Ora esaminiamo la nostra directory di progetto.
. ├── app.py ├── telebot │ ├── credentials.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv
Nel file credentials.py
avremo bisogno di tre variabili:
bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that we will create later"
Ora torniamo al nostro app.py ed esaminiamo il codice passo dopo passo:
# import everything from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL
global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN)
Ora abbiamo l'oggetto bot che verrà utilizzato per qualsiasi azione che richiediamo al bot di eseguire.
# start the flask app app = Flask(__name__)
Abbiamo anche bisogno di associare funzioni a percorsi specifici. In altre parole, dobbiamo dire a Flask cosa fare quando viene chiamato un indirizzo specifico. Informazioni più dettagliate su Flask e percorsi possono essere trovate qui.
Nel nostro esempio, la funzione route risponde a un URL che è fondamentalmente /{token}
, e questo è l'URL che Telegram chiamerà per ottenere risposte per i messaggi inviati al bot.
@app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok'
Il modo intuitivo per far funzionare questa funzione è che la chiameremo ogni secondo, in modo che controlli se è arrivato un nuovo messaggio, ma non lo faremo. Invece, utilizzeremo Webhook che ci fornisce un modo per consentire al bot di chiamare il nostro server ogni volta che viene chiamato un messaggio, in modo da non dover far soffrire il nostro server in un ciclo di attesa in attesa che arrivi un messaggio.
Quindi, creeremo una funzione che noi stessi dobbiamo chiamare per attivare il Webhook di Telegram, in pratica dicendo a Telegram di chiamare un collegamento specifico quando arriva un nuovo messaggio. Chiameremo questa funzione solo una volta, quando creeremo il bot per la prima volta. Se modifichi il link dell'app, dovrai eseguire nuovamente questa funzione con il nuovo link che hai.
Il percorso qui può essere qualsiasi cosa; sei tu che lo chiamerai:
@app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook(): # we use the bot object to link the bot to our app which live # in the link provided by URL s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) # something to let us know things work if s: return "webhook setup ok" else: return "webhook setup failed"
Ora che tutto è impostato, creiamo una homepage di fantasia in modo da sapere che il motore è acceso.
@app.route('/') def index(): return '.' if __name__ == '__main__': # note the threaded arg which allow # your app to have more than one thread app.run(threaded=True)
Diamo un'occhiata alla versione completa di app.py:
import re from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) app = Flask(__name__) @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' @app.route('/set_webhook', methods=['GET', 'POST']) def set_webhook(): s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) if s: return "webhook setup ok" else: return "webhook setup failed" @app.route('/') def index(): return '.' if __name__ == '__main__': app.run(threaded=True)
Questo è l'ultimo bit di codice che scriverai nel nostro tutorial. Ora possiamo passare all'ultimo passaggio, lanciando la nostra app su Heroku.

Avvia la nostra app su Heroku
Abbiamo bisogno di un paio di cose prima di creare la nostra app.
Heroku non può sapere quali librerie utilizza il tuo progetto, quindi dobbiamo dirlo usando il file requirements.txt
- un problema comune è che hai sbagliato a scrivere i requisiti, quindi fai attenzione - per generare il file dei requisiti usando pip:
pip freeze > requirements.txt
Ora hai il file dei requisiti pronto per l'uso.
Ora hai bisogno del Procfile
che dice a Heroku dove inizia la nostra app, quindi crea un file Procfile
e aggiungi quanto segue:
web: gunicorn app:app
Un passaggio di rimbalzo: puoi aggiungere un file .gitignore
al tuo progetto in modo che i file non utilizzati non vengano caricati nel repository.
Dalla dashboard di Heroku, crea una nuova app. Una volta fatto, ti indirizzerà alla pagina di distribuzione . Quindi, apri la scheda Impostazioni in una nuova finestra e copia il dominio dell'app che sarà qualcosa come https://appname.herokuapp.com/
e incollalo nella variabile URL all'interno di credentials.py
.
Ora torna alla scheda Distribuisci e procedi con i passaggi:
Nota: gli utenti Windows e macOS possono seguire i passaggi descritti qui.
Accedi a Heroku:
$ heroku login
Tieni presente che questo metodo a volte si blocca waiting for login
, se ti capita, prova ad accedere usando:
$ heroku login -i
Inizializza un repository Git nella nostra directory:
$ git init $ heroku git:remote -a {heroku-project-name}
Distribuisci l'app:
$ git add . $ git commit -m "first commit" $ git push heroku master
A questo punto, vedrai l'avanzamento della costruzione nel tuo terminale. Se tutto è andato bene, vedrai qualcosa del genere:
remote: -----> Launching... remote: Released v6 remote: https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done.
Ora vai alla pagina dell'app (il link del dominio che hai copiato prima) e aggiungi alla fine del link /setwebhook
in modo che l'indirizzo sia qualcosa come https://appname.herokuapp.com/setwebhook
. Se vedi webhook setup ok
, significa che sei pronto per partire!
Ora vai a parlare con il tuo bot
Tocchi finali, consigli e trucchi
Ora hai il tuo bot Telegram attivo e funzionante, 24 ore su 24, 7 giorni su 7, senza bisogno del tuo intervento. Puoi aggiungere qualsiasi logica desideri al bot, quindi, ad esempio, puoi rendere il tuo bot più realistico aggiungendo uno stato di "digitazione" e inviando uno stato di foto come segue:
Il prossimo frammento di codice dalla funzione respond()
:
if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendChatAction(chat_id=chat_id, action="typing") sleep(1.5) bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendChatAction(chat_id=chat_id, action="upload_photo") sleep(2) bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)
Come puoi vedere nello snippet, abbiamo aggiunto un'azione di digitazione quando stiamo per inviare le informazioni sul bot che sono in formato testo e abbiamo aggiunto un'azione di caricamento foto quando stiamo per inviare una foto per rendere il bot più realistico . Ulteriori azioni possono essere trovate qui.
Puoi anche modificare l'immagine e la descrizione del bot dal canale BotFather per renderlo più amichevole.
Molti esempi più semplici di bot di telegram possono essere trovati sulla pagina python-telegram-bot su GitHub.
Puoi basarti sul nostro bot e renderlo il prossimo robot super AI: tutto ciò che devi fare è integrare la tua logica nella funzione respond()
. Ad esempio, la tua logica può trovarsi in un modulo separato e può essere chiamata all'interno della funzione respond()
in questo modo:
. ├── app.py ├── telebot │ ├── credentials.py │ ├──ai.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv
E all'interno di ai .py:
def generate_smart_reply(text): # here we can do all our work return "this is a smart reply from the ai!"
Importalo ora nell'app .py:
import re from time import sleep from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL
Quindi chiamalo semplicemente all'interno del codice respond()
.
def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # here call your smart reply message reply = generate_smart_reply(text) bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)
Ora puoi fare in modo che il tuo bot funzioni come desideri: vai avanti e crea la prossima grande cosa!
Spero ti sia divertito a costruire il tuo primo bot di Telegram.
Risorse addizionali
- Costruire un Chatbot usando Telegram e Python
- Impostare il tuo WebHook Bot di Telegram in modo semplice
- Repository Python-telegram-bot
- Distribuzione con Git su Heroku
- Documentazione Python Telegram Bot