Make a bot for Skype on EC2 (CentOS)

Keep a bot on Skype

It's terribly new, but I decided to invite the bot to Skype. It is a work memo at that time.

chatbot.gif

EC2 configuration

The bot hut is EC2 (CentOS6).

skype4py-bot-house.gif

item value
region ap-northeast-1
AMI CentOS 6 (ami-25436924)

Installation

skype4py-install.gif

The following is a list of commands assuming that you are logged in with root privileges.

Advance preparation

Yum install what you need in advance.

ec2# yum install -y http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
ec2# yum install -y qtwebkit.i686 webkitgtk.i686 alsa-lib.i686 libXv.i686 libXScrnSaver.i686 gtk2-engines.i686 PackageKit-gtk-module.i686 libcanberra.i686 libcanberra-gtk2.i686 pulseaudio-libs.i686 alsa-plugins-pulseaudio.i686
ec2# yum install -y x11vnc ipa-gothic-fonts xauth Xvfb dbus-x11 wget

Install Skype

Installation

ec2# cd /usr/src
ec2# wget http://www.skype.com/go/getskype-linux-beta-dynamic -O skype-4.3.0.37.tar.bz2
ec2# tar xjvf /usr/src/skype-4.3.0.37.tar.bz2 -C /usr/local
ec2# dbus-uuidgen > /var/lib/dbus/machine-id
ec2# ln -s /usr/local/skype-4.3.0.37 /usr/local/skype
ec2# ln -s /usr/local/skype /usr/share/skype
ec2# ln -s /usr/local/skype/skype /usr/local/bin/skype
ec2# useradd skype
ec2# mkdir /var/db/skype /var/run/skype/ /var/log/skype/
ec2# chown skype:skype /var/db/skype /var/run/skype/ /var/log/skype/

Creating a startup script

Create a startup script like the one below.

/etc/init.d/skype


#!/bin/bash
#
# Init file for daemonized Skype service
#
### BEGIN INIT INFO
# Provides:          skype
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# X-Interactive:     false
# Short-Description: Start/stop daemonized Skype service
### END INIT INFO
#
# chkconfig: 345 80 10
#
# processname: skype
#
# pidfile: /var/run/skype.pid
#

if [ -r /etc/rc.d/init.d/functions ]; then
    . /etc/rc.d/init.d/functions
    log_daemon_msg() {
        msg=$1
        prog=$2
        echo -n $"$msg $prog: "
    }
    log_end_msg() {
        if [ "$1" = "0" ]; then
            success
        elif [ "$1" = "1" ]; then
            failure
        fi
        echo
    }
elif [ -r /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
else
    echo "Could not find a helper script needed to run this script."
    exit 1
fi

DAEMON_USER=skype
PROGNAME=`basename $0`
PIDFILE=/var/run/skype.pid
XSERVERNUM=20
XAUTHFILE=/home/skype/.Xauthority
LOGFILE=/var/log/skype/error.log
DBPATH=/var/log/skype/
XAUTHPROTO=.
SKYPE=/usr/local/skype-4.3.0.37/skype
USERNAME= #Please list the skype count for your bot
PASSWORD= #Please include the skype count password for your bot

[ -f /etc/sysconfig/skype ] && . /etc/sysconfig/skype

prog="skype"
RETVAL=0

dircheck() {
    if [ ! -d `dirname "$1"` ]; then
        echo "`dirname \"$1\"` does not exist"
        return 1
    else
        return 0
    fi
}

start() {
    log_daemon_msg "Starting" "skype"
    if ! dircheck "$LOGFILE" || ! dircheck "$XAUTHFILE"; then
        log_end_msg 1
        echo
        RETVAL=1
        return 
    fi 
    MCOOKIE=`mcookie` && \
    sudo -u "$DAEMON_USER" env XAUTHORITY=$XAUTHFILE sh -c "xauth add \":$XSERVERNUM\" \"$XAUTHPROTO\" \"$MCOOKIE\" >> \"$LOGFILE\" 2>&1" && \
    sudo -u "$DAEMON_USER" env XAUTHORITY=$XAUTHFILE sh -c "Xvfb :$XSERVERNUM -screen 0 800x600x8 -nolisten tcp >> \"$LOGFILE\" 2>&1 & echo \$!" >"$PIDFILE" &&
    sleep 3 && \
    ( sudo -u "$DAEMON_USER" env LD_LIBRARY_PATH=/usr/local/skype-4.3.0.37/:$LD_LIBRARY_PATH DISPLAY=:$XSERVERNUM XAUTHORITY=$XAUTHFILE SKYPE="$SKYPE" sh -c "echo \"$USERNAME $PASSWORD\" | nohup \"$SKYPE\" --dbpath=\"$DBPATH\" --pipelogin &") >> "$LOGFILE" 2>&1 && \
    (log_end_msg 0 && [ -d /var/lock/subsys ] && touch /var/lock/subsys/skype || true) \
        || (RETVAL=$?; kill -TERM `cat $PIDFILE`; log_end_msg 1)
}

stop() {
    log_daemon_msg "Stopping" "skype"
    if [ -e "$PIDFILE" ]; then
        kill -TERM `cat $PIDFILE` && \
        rm -f $PIDFILE && \
        if [ -d /var/lock/subsys ]; then rm -f /var/lock/subsys/skype; fi && \
        log_end_msg 0 || log_end_msg 1
    else
        log_end_msg 1
        RETVAL=1
    fi
}

usage() {
    echo "Usage: $PROGNAME {start|stop|restart}"
}

case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        usage
        RETVAL=255
        ;;
esac

exit $RETVAL

Grant execute permission.

ec2# chmod +x /etc/init.d/skype

Launch Skype

ec2# /etc/init.d/skype start

Access with VNC

iptables settings

Let's free port 5900 for VNC.

ec2# vi /etc/sysconfig/iptables
ec2# service iptables restart

Start VNC

ec2# x11vnc -display :20

Access the started VNC with VNC Viewer

Download and install the client software from TigerVNC Project Japanese Top Page - SourceForge.JP.

You can check the global IP address of the EC2 instance you are currently logged in to with the following command.

ec2# curl http://169.254.169.254/latest/meta-data/public-ipv4;echo

Launch TigerVNC Viewer and connect to (EC2 IP address): 5900 VNC-Viewer-Access.gif

Once connected, select a language and click "Agree" VNC-Skype-01.gif

The sign-in screen will appear, but if you leave it as it is With USERNAME / PASSWORD described in the startup script, Log in without permission. VNC-Skype-02.gif

When the screen after login appears, leave VNC Viewer for a while Return to work on the server side.

Conversation with the bot

Install Skype4Py

ec2# wget https://pypi.python.org/packages/source/d/distribute/distribute-0.6.49.tar.gz
ec2# tar xpvf distribute-0.6.49.tar.gz
ec2# python distribute-0.6.49/setup.py install
ec2# easy_install Skype4Py

Write a bot script

As a sample When you call it a "bot" Write a script that returns "| ΦωΦ) ...".

bot.py


# encoding: utf-8

import Skype4Py
import time

def handler(msg, event):
    if event == u"RECEIVED":
        if msg.Body == u"Bot":
            msg.Chat.SendMessage(u"|ΦωΦ) ...")

def main():
    skype = Skype4Py.Skype(Transport='x11')
    skype.OnMessageStatus = handler
    skype.Attach()
    while True:
        time.sleep(1) 

if __name__ == "__main__":
    main()

Launch the bot

ec2# export DISPLAY=:20;
ec2# python bot.py

On the VNC Viewer side that was left as it is, The following message will be displayed, so Check "Remember this selection" and click "Yes". VNC-Skype-03.gif

Try talking to your bot from another skype

unnamed.png

Well done ☆

Clean up

Let's shut down the VNC server. (Skype is still running, so there is no problem)

Raise bots

Let's install various reactions on the bot.

# encoding: utf-8

import Skype4Py
import time
import re #← Add

def handler(msg, event):

    if event == u"RECEIVED":

        #----Perfect matching
        if msg.Body == u"I am":
            msg.Chat.SendMessage(u"In you")
            return

        #----Search
        if re.search(u"you", msg.Body, re.S):
            msg.Chat.SendMessage(u"With me")

        #----Multiple lines
        if re.search(u"Get up", msg.Body, re.S):
            gataMsg = u"""Oh!!
    ∧∧ ∩
    (`・ Ω ・)/
⊂ No
    (Tsuno
     (No
 ___/(___
/  (___/
 ̄ ̄ ̄ ̄ ̄ ̄
"""
            msg.Chat.SendMessage(gataMsg)

        #----List extraction
        if re.search(u'I', msg.Body, re.S):
            list = re.findall(u'I', msg.Body, re.S)
            cnt = len(list)
            msg.Chat.SendMessage(u"[Self-consciousness warning] I: "+str(cnt))

        #----String replacement
        # note: python 2.6 series re.flags cannot be used in sub...
        #       http://docs.python.jp/2/library/re.html#re.sub
        if re.search(u'I', msg.Body):
            lines = msg.Body.splitlines()
            msg.Chat.SendMessage(u'understood.')
            for line in lines :
                you = re.sub(u'you', u'-you-', line)
                you = re.sub(u'I', u'you', you)
                you = re.sub(u'-you-', u'I', you)
                msg.Chat.SendMessage(you)
            msg.Chat.SendMessage(u'That's right.')

def main():
    skype = Skype4Py.Skype(Transport='x11')
    skype.OnMessageStatus = handler
    skype.Attach()
    while True:
        time.sleep(1) 

if __name__ == "__main__":
    main()

skype-bot-chat-05.gif

Invite bots to groups

There are "cloud-based" and "P2P-based" things in Skype chat The recently created group seems to be a "cloud-based" chat.

"What are the chat commands and roles? --Skype Support FAQ " https://support.skype.com/ja/faq/FA10042/

···so, Is it a SkypeApi specification, a Skype4Py specification, or a problem with my writing style? For "cloud-based" groups, bots didn't recognize the group well.

Therefore, “Invite bots to groups” If you want to “bots notify the group of messages” I will use "P2P base".

The currently open group To check if it is "cloud-based" or "P2P-based" From the message input field, throw the following command.

/get name

From the explanation on the above Skype-FAQ page, it seems that it can be determined as follows.

If the group name response starts with "19: ...", then you are using cloud-based chat. If the group name response starts with "#skypename ...", you are using P2P-based chat.

To create a "P2P-based" group, From the message input field (any chat is OK), throw the following command.

/createmoderatedchat

If possible, it is desirable for the bot itself to throw this command. (Because the resident bot can become an administrator)

It's also a hassle to do from VNC Viewer, so log in to your bot account on your PC I think it's better to work there.

Let's add members to the newly created "P2P-based" group.

Notify a message

It ’s not just a passive reaction, I would like to be actively notified by bots.

To users

Please change the user name of the notification destination as appropriate. By registering the following command in the scheduler etc. At any time (on time, event occurrence, etc.) It is possible to notify the message, It can be used as a reminder or alert notification.

Notification script

send_message_for_user.py


# -*- coding: utf-8 -*-
import Skype4Py
import sys

user = 'username' #Rewrite required

argvs = sys.argv
acnt = len(argvs)

skype = Skype4Py.Skype(Transport='x11')
skype.Attach()

msg = argvs[1] if acnt > 1 and argvs[1] else 'energy?'

chat = skype.CreateChatWith(user)
chat.SendMessage(msg)

Notification command

ec2# export DISPLAY=:20;
ec2# python send_message_for_group.py 'Animation will start in 30 minutes'

To the group

Notifications to groups are a little special Find the target group from the list of chats you belong to I am trying to notify the message only when it is the corresponding group.

Notification script

send_message_for_group.py


# -*- coding: utf-8 -*-
import Skype4Py
import sys

argvs = sys.argv
acnt = len(argvs)

skype = Skype4Py.Skype(Transport='x11')
skype.Attach()

msg = argvs[1] if acnt > 1 and argvs[1] else 'energy?'

for chat in skype.Chats :
    if chat.Name == '#skype_group_name/$1234567890abcdef': #Rewrite required
        chat.SendMessage(msg)

Notification command

ec2# export DISPLAY=:20;
ec2# python send_message_for_group.py 'It's lunch time, everyone.'

Finally

When using it for business, please be careful about security.

Referenced site

■ aws marketplace : CentOS 6 (x86_64) - with Updates https://aws.amazon.com/marketplace/ordering?productId=adc4348e-1dc3-41df-b833-e86ba57a33d6

■ Build SkypeBot (Skype4Py) on CentOS 6.3 [2013/03/09] https://mistymagich.wordpress.com/2013/03/09/centos6-3%E3%81%ABskypebot%E3%82%92%E6%A7%8B%E7%AF%89/

■ How to make a bot for Skype that runs on Linux [2010/09/26] http://d.hatena.ne.jp/moriyoshi/20100926/1285517353

Recommended Posts

Make a bot for Skype on EC2 (CentOS)
Make Jupyter Notebook a service on CentOS
Make a parrot return LINE Bot on AWS Cloud9
[For play] Let's make Yubaba a LINE Bot (Python)
Procedure for creating a Line Bot on AWS Lambda
Let's make a Discord Bot.
Make a LINE BOT (chat)
Build a python environment on CentOS 7.7 for your home server
Make a Tweet box for Pepper
How to make a slack bot
Create a python environment on centos
Build a python3 environment on CentOS7
Make a rain notification bot for Hangouts Chat at explosive speed
Make a Discord Bot that you can search for and paste images
A memo with Python2.7 and Python3 on CentOS
Make Unity Accelerator a service on Linux
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 Twitter Bot with Python!
Let's make a Backend plugin for Errbot
I tried to make a translation BOT that works on Discord using googletrans
Make a Twitter trend bot with heroku + Python
Create a LINE BOT with Minette for Python
Build a python environment with ansible on centos6
Make a histogram for the time being (matplotlib)
A memorandum for touching python Flask on heroku
Build a Kubernetes environment for development on Ubuntu
Make a LINE WORKS bot with Amazon Lex
Let's make a module for Python using SWIG
Anyway, I'm at home, so let's make a (site) screenshot function bot on Discord!
Make for VB6.
Initial settings for using Python3.8 and pip on CentOS8
Make a morphological analysis bot loosely with LINE + Flask
Specify the volume on linux and make a sound
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
Procedure for manually installing Java (jdk1.8) on Linux (CentOS7)
Build a local development environment for Laravel6.X on Mac
Create a QR code for the URL on Linux
Build a Python extension for E-Cell 4 on Windows 7 (64bit)
Make a BOT that shortens the URL of Discord
Make your cursor a photo of your choice on Linux
Preparation for processing pbm images on a pixel-by-pixel basis
A memo of installing Chainer 1.5 for GPU on Windows
Make a breakpoint on the c layer with python
[Part 2] Let's build a web server on EC2 Linux
Make the model a string on a Django HTML template
Procedure for building a CDK environment on Windows (Python)
[Super easy] Let's make a LINE BOT with Python.
Beginners will make a Bitcoin automatic trading bot aiming for a lot of money! Part 3 [Local Bot]
Beginners will make a Bitcoin automatic trading bot aiming for a lot of money! Part 4 [Serverless]