[PYTHON] Make a Tweet box for Pepper

Making motions and conversations in Pepper can be very interesting, but it still makes me want to connect to a social network.

If you write Python in Python Box, you can do various things, but even if you look at the official document, there is no way to import an external library. ・ ・ ・ If you think HOW TO IMPORT PYTHON FILES IN YOUR PEPPER APPS? There was, so I will try it.

Create a Twitter Tweet box

First of all, let's get an idea of what you need. To read Access Twitter API with Python, it seems that the following elements are required to access Twitter.

Also, I wonder if the following is required as a library imported from the script.

Based on these, we will consider realizing the following Twitter Tweet box.

tweet-design.png

As for the specifications of the Tweet box,

  1. Input onStart is a string type and receives the content message you want to tweet
  2. When input is entered in onStart, tweet processing will be performed.
  3. If successful, onStopped is output. No value ("van" type)
  4. If it fails, onFailed is output. Status code (numerical value) is passed
  5. Consumer Key, Consumer Secret, Access Token, Access Token Secret required to access Twitter API are given by parameters
  6. Access to Twitter API is written in Python, and the OAuth library to be imported is saved as a project file.

Feeling like that. As a procedure,

  1. Make a Python box on Choregraphe
  2. Prepare the library to import from the Python script
  3. Write a Python script

I will try in the order of.

Try to make

Creating a box

First, create a box shape on Choregraphe.

  1. Right-click on the flow diagram and select ** [Python ...] under [New Box] ** new-python-box.png

  2. Enter ** Tweet in the name ** add-new-box.png

  3. Change the onStart input type to a string. Enter ** Click the Settings button on Start [A] ** and then click the ** Type drop-down list [B] ** edit-onstart-type-1.png

Then, a list of types will appear. ** Select [String] ** and click the [OK] button. edit-onstart-type-2.png

  1. Next, add onFailed to the output. Click the ** Add [+] button in the output ** add-onfailed-1.png

Since the setting dialog appears in the same way as input, enter ** onFailed in Name [A] ** and change Type to ** [number] [B] ** add-onfailed-2.png

  1. Add parameters. Click the ** Add [+] button for the variable [A] **, enter ** Consumer Key in Name [B] **, change Type to ** [String] [C] **, and then click [ Click the OK button add-param-1.png

When you press the [OK] button, you can see that the Consumer Key has been added to the variable list. add-param-2.png

  1. Add Consumer Secret, Access Token, Access Token Secret in the same way as 5. add-param-3.png

  2. Click the [OK] button to create a ** Tweet box ** in the flow diagram. new-tweet-box.png

Now the outside of the box is ready.

Library preparation

In the Tweet box, we will import the following libraries for OAuth authentication.

Looking at the requirements.txt of this library, I found that the following libraries are also needed, so these too I will include it.

Originally, I thought that I should use a package management tool properly, but first of all, I feel like using the above three libraries, and I will try to incorporate the library files into the project by the following procedure.

  1. requests-oauthlib, requests, [oauthlib](https://github. Get files from 3 repositories (com / idan / oauthlib) git-download-zip.png

This time, select ** [Download ZIP] ** and zip the files in the repository.

  1. Create a lib folder in an appropriate folder, unzip the three downloaded ZIP files, and put them together in the following configuration.

    • lib
      • requests_oauthlib
        • __init__.py
        • ...
      • oauthlib
        • __init__.py
        • ...
      • requests
        • __init__.py
        • ...
  2. Click the ** Add [+] button in the [Project Contents] panel and select [Import Folder ...] ** import-folder.png

  3. The [Select Folder to Import] dialog opens. Select the lib folder created in 2. and click the ** [Select Folder] button **. import-folder-dialog.png

  4. The lib directory will be added to the file list, so expand the directory tree and make sure the files are imported. imported-lib.png

You should now be able to import the Python library as a project file (should). Next, as a Python script for the Tweet box, write code that uses these libraries to tweet.

Python script writing

Double-click the Tweet box to open the script editor and paste the script below.

class MyClass(GeneratedClass):
    def __init__(self):
        GeneratedClass.__init__(self)

    def onLoad(self):
        self.framemanager = ALProxy("ALFrameManager")
        self.folderName = None

    def onUnload(self):
        import sys
        if self.folderName and self.folderName in sys.path:
            sys.path.remove(self.folderName)
        self.folderName = None

    def onInput_onStart(self, p):
        import sys, os
        self.folderName = os.path.join(
                    self.framemanager.getBehaviorPath(self.behaviorId), "../lib")
        if self.folderName not in sys.path:
            sys.path.append(self.folderName)
        for moduleName in os.listdir(self.folderName):
            #Module reload
            if moduleName in sys.modules:
                self.logger.info("Loaded: %s, %s" % (moduleName, sys.modules[moduleName].__file__))
                reload(sys.modules[moduleName])
        from requests_oauthlib import OAuth1Session
        self.logger.info("Tweeting... %s" % p)

        url = "https://api.twitter.com/1.1/statuses/update.json"

        #Tweet body
        params = {"status": p}

        twitter = OAuth1Session(self.getParameter("Consumer Key"),
                        self.getParameter("Consumer Secret"),
                        self.getParameter("Access Token"),
                        self.getParameter("Access Token Secret"))
        req = twitter.post(url, params = params)

        if req.status_code == 200:
            self.logger.info("OK")
            self.onStopped()
        else:
            self.logger.warn("Failed: %d" % req.status_code)
            self.onFailed(req.status_code)

    def onInput_onStop(self):
        self.onUnload() #it is recommended to reuse the clean-up as the box is stopped
        self.onStopped() #activate the output of the box

The point of the code is ...

  1. First, get a reference to ALFrameManager (used for path resolution of files in the project) at onLoad and initialize variables.

    def onLoad(self):
        self.framemanager = ALProxy("ALFrameManager")
        self.folderName = None
    
  2. The Python library added to [Project Contents] by sys.path can be imported at the start of onStart processing.

    def onInput_onStart(self, p):
        import sys, os
        self.folderName = os.path.join(
                    self.framemanager.getBehaviorPath(self.behaviorId), "../lib")
        if self.folderName not in sys.path:
            sys.path.append(self.folderName)
    
  3. Load the Python library in the project and process it

       from requests_oauthlib import OAuth1Session
       self.logger.info("Tweeting... %s" % p)
       ...
    
  4. After the process is completed, call the output by the return value of the Twitter API call.

       ...
       if req.status_code == 200:
           self.logger.info("OK")
           self.onStopped()
       else:
           self.logger.warn("Failed: %d" % req.status_code)
           self.onFailed(req.status_code)
    
  5. When unloading, remove the path for the project's Python library from sys.path

    def onUnload(self):
       import sys
       if self.folderName and self.folderName in sys.path:
           sys.path.remove(self.folderName)
       self.folderName = None
    

Feeling like. Personally, rewriting the sys.path feels a bit brute force ... I hope that pip will be well integrated in the future.

Operation check

To try out the created Tweet box, create the following application.

  1. Place Data Edit> Text Edit in the standard box library test-box-1.png

  2. Connect the boxes as follows test-box-2.png

  3. Set ** Consumer Key, Consumer Secret, Access Token, Access Token Secret ** obtained from Twitter in the parameter of Tweet box. test-box-3.png

  4. Enter the content you want to tweet in the Text Edit box test-box-4.png

Now you have created a flow to tweet any message. It worked on a real Pepper machine or a virtual robot (Mac only). Cannot be executed by Windows virtual robot. It seems that the ssl module is not valid ...

You can make Pepper tweet like this. I was thinking that if I could take a picture of the camera and tweet it, Pepper would be able to handle the live hackathon work. I will continue to write if I have any material.

Recommended Posts

Make a Tweet box for Pepper
Make Qt for Python app a desktop app
ROS course 107 Make a client for rosblidge
Make a chessboard pattern for camera calibration
Let's make a Backend plugin for Errbot
Make for VB6.
Make a bot for Skype on EC2 (CentOS)
Make a histogram for the time being (matplotlib)
Understand Python for Pepper development. -Python box self-made function-
Let's make a module for Python using SWIG
Understand Python for Pepper development. -Introduction to Python Box-
Make a squash game
Make a function decorator
Make a distance matrix
[For play] Let's make Yubaba a LINE Bot (Python)
I'll make a password!
Make a Nyan button
Make a Tetris-style game!
Make a Base64 decoder
Make an IP address allocation / allocation list for a certain area
I made a box to rest before Pepper gets tired
Experiment to make a self-catering PDF for Kindle with Python
How to make a Python package (written for an intern)
Let's make a Discord Bot.
Make a Blueqat backend ~ Part 1
[Statistics for programmers] Box plot
Make an MQTT Publisher box
Make a Blueqat backend ~ Part 2
[Django] Make a pull-down menu
Make a LINE BOT (chat)
Pepper Tutorial (5): Using a Tablet
Make a bookmarklet in Python
Make a fortune with Python
Make Responder a daemon (service)
Pepper box library test consideration
Made a command for FizzBuzz
Let's make a rock-paper-scissors game
Make a fire with kdeplot
Make an MQTT Subscriber box
Make a math drill print
PyPI registration steps for those who want to make a PyPI debut
Let's make a WEB application for phone book with flask Part 1
Make a rain notification bot for Hangouts Chat at explosive speed
Let's make a WEB application for phone book with flask Part 2
Spigot (Paper) Introduction to how to make a plug-in for 2020 # 01 (Environment construction)
How to make a unit test Part.1 Design pattern for introduction
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
I tried to make a strange quote for Jojo with LSTM