Is There a Bot to Scan a Word Document and Then Upload It to Another System

Chatbots are oftentimes touted equally a revolution in the fashion users collaborate with engineering and businesses. They have a adequately uncomplicated interface compared with traditional apps, equally they only crave users to chat, and the chatbots are supposed to understand and practice whatever the user demands from them, at to the lowest degree in theory.

Many industries are shifting their client service to chatbot systems. That's considering of the huge drop in the cost compared to bodily humans, and too because of the robustness and abiding availability. Chatbots deliver a degree of user support without substantial boosted cost.

Today, chatbots are used in many scenarios, ranging from menial tasks such as displaying time and conditions data to more complex operations such equally rudimentary medical diagnosis and client communication/back up. You lot can devise a chatbot that will help your customers when they ask certain questions most your product, or y'all can make a personal assistant chatbot that tin can handle bones tasks and remind you lot when it's fourth dimension to head to a meeting or the gym.

There are a lot of options when information technology comes to where you lot can deploy your chatbot, and i of the well-nigh mutual uses are social media platforms, as most people utilize them on a regular footing. The same can be said of instant messaging apps, though with some caveats.

Telegram is one of the more than popular IM platforms today, equally it allows you to store letters on the cloud instead of just your device and it boasts good multi-platform support, every bit you tin can have Telegram on Android, iOS, Windows, and just about any other platform that can support the web version. Building a chatbot on Telegram is fairly simple and requires few steps that take very trivial time to consummate. The chatbot tin can be integrated in Telegram groups and channels, and it also works on its ain.

In this tutorial, nosotros will exist creating a Telegram bot that gives you an avatar image from Ambrosial Avatars. Our instance will involve edifice a bot using Flask and deploying information technology on a free Heroku server.

To complete this tutorial, you volition need Python 3 installed on your organization as well as Python coding skills. Also, a practiced understanding of how apps piece of work would be a good addition, just not a must, as we volition be going through nearly of the stuff we present in detail. Y'all too demand Git installed on your system.

Of course, the tutorial also requires a Telegram account, which is complimentary. You can sign up here. A Heroku account is required, also, and you tin get it for free here.

Bringing Your Telegram Bot to Life

To create a chatbot on Telegram, you need to contact the BotFather, which is essentially a bot used to create other bots.

The command you lot need is /newbot which leads to the following steps to create your bot:

Telegram bot tutorial - screenshot example

Your bot should have two attributes: a proper noun and a username. The name will show upward for your bot, while the username volition be used for mentions and sharing.

After choosing your bot name and username—which must end with "bot"—you volition get a bulletin containing your access token, and you'll obviously need to save your access token and username for afterwards, as you will be needing them.

Code the Chatbot Logic

Nosotros volition be using Ubuntu in this tutorial. For Windows users, most of the commands here will work without whatsoever issues, but should yous face any issues with the virtual environs setup, please consult this link. Equally for Mac users, this tutorial should work just fine.

First, let's create a virtual environment. It helps isolate your projection'due south requirements from your global Python environment.

          $ python -thousand venv botenv/                  

Now we volition take a botenv/ directory which will contain all the Python libraries we will exist using. Go ahead and actuate virtualenv using the following command:

          $ source botenv/bin/activate                  

The libraries we need for our bot are:

  • Flask: A micro spider web framework built in Python.
  • Python-telegram-bot: A Telegram wrapper in Python.
  • Requests: A popular Python http library.

You can install them in the virtual environment using pip command as follows:

          (telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests                  

Now let's browse our project directory.

          . ├── app.py ├── telebot │   ├── credentials.py │   |   . │   |   you can build your engine here │   |   . │   └── __init__.py └── botenv                  

In the credentials.py file we will need three variables:

          bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that nosotros will create afterwards"                  

Now permit's become dorsum to our app.py and become through the code step by footstep:

          # 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)                  

Now nosotros take the bot object which will be used for whatsoever action nosotros crave the bot to perform.

          # start the flask app app = Flask(__name__)                  

Nosotros also need to bind functions to specific routes. In other words, nosotros need to tell Flask what to do when a specific address is called. More detailed info almost Flask and routes can be found here.

In our example, the route office responds to a URL which is basically /{token}, and this is the URL Telegram will phone call to get responses for messages sent to the bot.

          @app.road('/{}'.format(TOKEN), methods=['POST']) def respond():    # retrieve the message in JSON and then transform information technology to Telegram object    update = telegram.Update.de_json(request.get_json(strength=True), bot)     chat_id = update.message.chat.id    msg_id = update.message.message_id     # Telegram understands UTF-viii, so encode text for unicode compatibility    text = update.message.text.encode('utf-8').decode()    # for debugging purposes only    impress("got text message :", text)    # the offset time you chat with the bot AKA the welcoming message    if text == "/outset":        # print the welcoming message        bot_welcome = """        Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate absurd looking avatars based on the name you enter then please enter a name and the bot will reply with an avatar for your name.        """        # ship the welcoming message        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        endeavor:            # clear the message nosotros got from whatever not alphabets            text = re.sub(r"\W", "_", text)            # create the api link for the avatar based on http://avatars.adorable.io/            url = "https://api.ambrosial.io/avatars/285/{}.png".format(text.strip())            # reply with a photo to the name the user sent,            # annotation that you tin transport photos by url and telegram will fetch it for you            bot.sendPhoto(chat_id=chat_id, photograph=url, reply_to_message_id=msg_id)        except Exception:            # if things went wrong            bot.sendMessage(chat_id=chat_id, text="There was a trouble in the name yous used, please enter different proper noun", reply_to_message_id=msg_id)     return 'ok'                  

The intuitive manner to make this function to work is that we will call it every 2d, so that it checks whether a new message has arrived, merely we won't be doing that. Instead, nosotros will be using Webhook which provides us a way of letting the bot phone call our server whenever a message is called, so that we don't demand to make our server suffer in a while loop waiting for a message to come.

So, we will brand a function that nosotros ourself need to call to activate the Webhook of Telegram, basically telling Telegram to call a specific link when a new message arrives. We will telephone call this office ane time just, when we first create the bot. If you change the app link, then you volition need to run this role again with the new link you have.

The road here tin be anything; you lot're the one who will call information technology:

          @app.route('/setwebhook', methods=['GET', 'Mail service']) def set_webhook():     # we use the bot object to link the bot to our app which live     # in the link provided by URL     due south = bot.setWebhook('{URL}{Claw}'.format(URL=URL, HOOK=TOKEN))     # something to let the states know things work     if s:         return "webhook setup ok"     else:         render "webhook setup failed"                  

Now that everything is set, allow's just make a fancy homepage and so that we know the engine is up.

          @app.route('/') def index():     return '.' if __name__ == '__main__':     # annotation the threaded arg which allow     # your app to have more than one thread     app.run(threaded=True)                  

Let'southward take a wait at the full version of 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=['Mail']) def reply():    # retrieve the message in JSON then transform it to Telegram object    update = telegram.Update.de_json(asking.get_json(force=True), bot)     chat_id = update.bulletin.chat.id    msg_id = update.bulletin.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 outset fourth dimension yous chat with the bot AKA the welcoming message    if text == "/starting time":        # 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 proper noun you enter and then please enter a name and the bot will reply with an avatar for your name.        """        # ship the welcoming bulletin        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        try:            # clear the bulletin nosotros got from any not 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 photograph to the proper noun the user sent,            # note that you can ship photos past url and telegram volition 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="In that location was a trouble in the name yous used, please enter different name", reply_to_message_id=msg_id)     render 'ok'  @app.route('/set_webhook', methods=['GET', 'Mail']) def set_webhook():    southward = bot.setWebhook('{URL}{Claw}'.format(URL=URL, Claw=TOKEN))    if s:        return "webhook setup ok"    else:        return "webhook setup failed"  @app.route('/') def index():    return '.'   if __name__ == '__main__':    app.run(threaded=Truthful)                  

That's the last scrap of code you volition write in our tutorial. Now we tin progress to the last stride, launching our app on Heroku.

Launch Our App on Heroku

We demand a couple of things before we make our app.

Heroku can't know what libraries your projection uses, so we have to tell it using the requirements.txt file—a common problem is that you misspell requirements, so be careful—to generate the requirements file using pip:

          pip freeze > requirements.txt                  

Now y'all have your requirements file ready to go.

Now you lot need the Procfile which tells Heroku where our app starts, and so create a Procfile file and add together the following:

          web: gunicorn app:app                  

A bounce step: You can add a .gitignore file to your project so that no-use files don't become uploaded to the repository.

From your Heroku dashboard, create a new app. Once you do, information technology will direct yous to the Deploy page. And so, open the Settings tab in a new window and copy the domain of the app which will be something like https://appname.herokuapp.com/ and paste information technology in the URL variable inside credentials.py.

Heroku dashboard screenshot

Now, go back to the Deploy tab and continue with the steps:

Note: Windows and macOS users tin follow the steps described here.

Log in to Heroku:

          $ heroku login                  

Please note that this method sometimes gets stuck in waiting for login, if this happens to yous, try to log in using:

          $ heroku login -i                  

Initialize a Git repository in our directory:

          $ git init $ heroku git:remote -a {heroku-projection-name}                  

Deploy the app:

          $ git add . $ git commit -k "commencement commit" $ git push heroku master                  

At this point, yous will see the building progress in your terminal. If everything went okay, y'all will see something like this:

          remote: -----> Launching... remote:        Released v6 remote:        https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... washed.                  

Now go to the app folio (the link of the domain you copied before) and add to the finish of the link /setwebhook so that the address will be something like https://appname.herokuapp.com/setwebhook. If you see webhook setup ok, that means you are gear up to become!

At present Go Talk to Your Bot

A live version of the bot

Finishing Touches, Tips, and Tricks

Now you lot have your Telegram bot up and running, 24/7, without any need for your intervention. Y'all can add together any logic you want to the bot, and so, for example, y'all can make your bot more realistic by adding a "typing" status and sending a photo condition as follows:

The next code snippet from the respond() function:

                      if text == "/first":        # impress 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 proper name you enter so please enter a name and the bot will respond with an avatar for your name.        """        # transport the welcoming message        bot.sendChatAction(chat_id=chat_id, activity="typing")        slumber(1.v)        bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)      else:        endeavour:            # clear the message nosotros got from any non alphabets            text = re.sub(r"\Due west", "_", 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())            # respond with a photo to the name the user sent,            # note that you can send photos by url and telegram will fetch information technology 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 incorrect            bot.sendMessage(chat_id=chat_id, text="In that location was a trouble in the name yous used, please enter different name", reply_to_message_id=msg_id)                  

As you can see in the snippet, we added a typing action when we are about to send the information near the bot which is in text format, and added an upload photo action when nosotros are almost to send a photo to make the bot more realistic. More actions tin can be found here.

Yous tin too alter the bot prototype and description from the BotFather aqueduct to brand it more friendly.

Many more simple examples of telegram bots can be found on the python-telegram-bot page on GitHub.

You can build upon our bot and make it the next super AI bot—all you demand to practise is to integrate your logic in the respond() function. For example, your logic can exist in a separate module and tin can be chosen inside of the respond() office like then:

          . ├── app.py ├── telebot │   ├── credentials.py │   ├──ai.py │   |   . │   |   yous tin can build your engine here │   |   . │   └── __init__.py └── botenv                  

And inside of ai.py :

          def generate_smart_reply(text):     # here we tin practice all our work     return "this is a smart reply from the ai!"                  

Import it now in the app.py :

          import re from time import slumber from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL                  

Then just telephone call it inside of the respond() lawmaking.

          def respond():    # retrieve the message in JSON and then transform information technology to Telegram object    update = telegram.Update.de_json(request.get_json(forcefulness=Truthful), bot)     chat_id = update.bulletin.chat.id    msg_id = update.message.message_id     # Telegram understands UTF-8, then encode text for unicode compatibility    text = update.message.text.encode('utf-8').decode()    # for debugging purposes only    print("got text bulletin :", text)    # hither phone call your smart answer message    reply = generate_smart_reply(text)    bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)                  

Now you can accept your bot work the way yous want—become ahead and create the next large thing!

I hope yous had fun building your first Telegram bot.

Additional Resources

  • Edifice a Chatbot using Telegram and Python
  • Setting your Telegram Bot WebHook the easy way
  • Python-telegram-bot Repository
  • Deploying with Git on Heroku
  • Python Telegram Bot documentation

salleemillan72.blogspot.com

Source: https://www.toptal.com/python/telegram-bot-tutorial-python

0 Response to "Is There a Bot to Scan a Word Document and Then Upload It to Another System"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel