whatsapp via command line interface (yowsup)


Kali ini kita mencoba menggunakan youwsup untuk mengirim pesan atau menerima pesan via command line interface

diasumsikan python sudah terinstall di komputer anda

#step 1
#download youwsup
wget https://github.com/tgalal/yowsup/archive/master.zip
#unzip
unzip /master.zip
#cd yowsup-master

#step 2
#install youwsup
python setup.py install

#step 3 Registration
#Registrasi
yowsup-cli registration –requestcode sms –phone 62XXXXXXXX –cc 62 –mcc 510 –mnc 10
–phone 62XXXXXXXX = isi dengan nomor anda beserta kode negara tanpa “+” sebagai contoh 62812115478
–mcc 510 = isi dengan kode mcc misal telkomsel 510
–mnc 456 = isi dengan kode mnc misal telkomsel 10

#tunggu sms beberapa saat
#kirim balik kode yang didapatkan via sms
yowsup-cli registration –register 123456 –phone 49XXXXXXXX –cc 49

#Step 4 dapatkan Username dan password jika registrasi berhasil
#Username => login : nomor_telepon
#password ==> pwd : FcXXXXXXXXXXXXXXXXX-
Screenshot from 2016-02-02 19:53:21

#Selesai

Mengirim Pesan
#yowsup-cli demos -l -s nomor tujuan
yowsup-cli demos -l 62812115478:FcXXXXXXXXXXXXXXXXX= -s 62812115444 “Testing WhatsApp…”

Menggunakan interaktif mode
/yowsup-master$ yowsup-cli demos -l 62812115478:FcXXXXXXXXXXXXXXXXX= -y

setelah muncul [offline] ketik /L
[offline]:/L

setelah itu mendapatkan konfirmasi connect
Auth: Logged in!
[connected]:

ketik /help untuk mendapatkan petujuk menggunakan interaktif mode
[connected]:/help

misal ingin mengirimkan pesan
/message send 62812115444 “apa kabar?”

untuk menerima pesan akan langsung ditampilkan
misal
[62812115444@s.whatsapp.net(02-02-2016 21:01)]:[FdXXXXXXXXXXXXXXXXX] kabar baik

 

referensi:

http://manpages.ubuntu.com/manpages/wily/man1/yowsup-cli.1.html

https://github.com/tgalal/yowsup

Install OpenCV raspberry pi


#step 1
update&upgrade , Update firmwire
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo rpi-update

reboot
$ sudo reboot

install beberapa developer tools
$ sudo apt-get install build-essential git cmake pkg-config

install image I/O packages
$ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev

install video I/O packages
$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev

install GTK development library yang merupakan sub-module dari OpenCV yang dapat menampilkan images kedalam layar kita dan membuat GUI yang sederhana
$ sudo apt-get install libgtk2.0-dev

install beberapa dependecies
$ sudo apt-get install libatlas-base-dev gfortran

install Python 2.7 dan Python 3 header file sehingga dapat mengkompile openCV + python
$ sudo apt-get install python2.7-dev python3-dev

#step 2
$ cd ~
$ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.0.0.zip
$ unzip opencv.zip

$ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.0.0.zip
$ unzip opencv_contrib.zip

#sampai sini dulu

#step 3
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

 

install numpy, cukup memakan waktu sekitar 15 menit, harap bersabar
$ pip install numpy

$ cd ~/opencv-3.0.0/
jika anda ingin menginstall di usb atau drive lain anda dapat mengubah direktory seperti yang saya lakukan dikarenakan keterbatasan sdcard yang saya punya sebagai berikut, namun sebelumnya pastikan usb sudah termount

$ cd /media/usb/opencv-3.0.0/

$ cd build
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.0.0/modules \
-D BUILD_EXAMPLES=ON \
-D BUILD_SHARED_LIBS=OFF ..

-D BUILD_SHARED_LIBS=OFF .. ditambahkan untuk membuat OpenCV dapat berjalan di java, jika java missing library dapat di install
sudo apt-get install openjdk-7-jdk
dan
sudo apt-get install ant

setelah itu
export JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-arm-vfp-hflt

setelah itu jalan kan cmake kembali, pastikan configurasi cmake seperti yang anda inginkan, sebagai contoh berikut

— Detected version of GNU GCC: 49 (409)
— Found ZLIB: /usr/lib/arm-linux-gnueabihf/libz.so (found suitable version “1.2.8”, minimum required is “1.2.3”)
— Found ZLIB: /usr/lib/arm-linux-gnueabihf/libz.so (found version “1.2.8”)
— checking for module ‘gtk+-3.0’
— package ‘gtk+-3.0’ not found
— checking for module ‘gtk+-2.0’
— package ‘gtk+-2.0’ not found
— checking for module ‘gthread-2.0’
— package ‘gthread-2.0’ not found
— checking for module ‘gstreamer-base-1.0’
— package ‘gstreamer-base-1.0’ not found
— checking for module ‘gstreamer-video-1.0’
— package ‘gstreamer-video-1.0’ not found
— checking for module ‘gstreamer-app-1.0’
— package ‘gstreamer-app-1.0’ not found
— checking for module ‘gstreamer-riff-1.0’
— package ‘gstreamer-riff-1.0’ not found
— checking for module ‘gstreamer-pbutils-1.0’
— package ‘gstreamer-pbutils-1.0’ not found
— checking for module ‘gstreamer-base-0.10’
— package ‘gstreamer-base-0.10’ not found
— checking for module ‘gstreamer-video-0.10’
— package ‘gstreamer-video-0.10’ not found
— checking for module ‘gstreamer-app-0.10’
— package ‘gstreamer-app-0.10’ not found
— checking for module ‘gstreamer-riff-0.10’
— package ‘gstreamer-riff-0.10’ not found
— checking for module ‘gstreamer-pbutils-0.10’
— package ‘gstreamer-pbutils-0.10’ not found
— checking for module ‘libdc1394-2’
— package ‘libdc1394-2’ not found
— checking for module ‘libdc1394’
— package ‘libdc1394’ not found
— Looking for linux/videodev.h
— Looking for linux/videodev.h – not found
— Looking for linux/videodev2.h
— Looking for linux/videodev2.h – found
— Looking for sys/videoio.h
— Looking for sys/videoio.h – not found
— Looking for libavformat/avformat.h
— Looking for libavformat/avformat.h – found
— Looking for ffmpeg/avformat.h
— Looking for ffmpeg/avformat.h – not found
— checking for module ‘libgphoto2’
— package ‘libgphoto2’ not found
— Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
— To enable PlantUML support, set PLANTUML_JAR environment variable or pass -DPLANTUML_JAR= option to cmake
— Found PythonInterp: /usr/bin/python2.7 (found suitable version “2.7.9”, minimum required is “2.7”)
— Found PythonLibs: /usr/lib/arm-linux-gnueabihf/libpython2.7.so (found suitable exact version “2.7.9”)
— Found PythonInterp: /usr/bin/python3.4 (found suitable version “3.4.2”, minimum required is “3.4”)
— Found PythonLibs: /usr/lib/arm-linux-gnueabihf/libpython3.4m.so (found suitable exact version “3.4.2”)
— Found apache ant 1.9.4: /usr/bin/ant
— Could NOT find Matlab (missing: MATLAB_MEX_SCRIPT MATLAB_INCLUDE_DIRS MATLAB_ROOT_DIR MATLAB_LIBRARIES MATLAB_LIBRARY_DIRS MATLAB_MEXEXT MATLAB_ARCH MATLAB_BIN)
— VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
— videoio: Removing WinRT API headers by default

— General configuration for OpenCV 3.0.0 =====================================
— Version control: unknown

— Platform:
— Host: Linux 4.1.15-v7+ armv7l
— CMake: 3.0.2
— CMake generator: Unix Makefiles
— CMake build tool: /usr/bin/make
— Configuration: RELEASE

— C/C++:
— Built as dynamic libs?: NO
— C++ Compiler: /usr/bin/c++ (ver 4.9.2)
— C++ flags (Release): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
— C++ flags (Debug): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
— C Compiler: /usr/bin/cc
— C flags (Release): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -O3 -DNDEBUG -DNDEBUG
— C flags (Debug): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -g -O0 -DDEBUG -D_DEBUG
— Linker flags (Release):
— Linker flags (Debug):
— Precompiled headers: YES
— Extra dependencies: /usr/lib/arm-linux-gnueabihf/libpng.so /usr/lib/arm-linux-gnueabihf/libz.so /usr/lib/arm-linux-gnueabihf/libtiff.so /usr/lib/arm-linux-gnueabihf/libjasper.so /usr/lib/arm-linux-gnueabihf/libjpeg.so v4l1 v4l2 avcodec avformat avutil swscale avresample stdc++ dl m pthread rt
— 3rdparty dependencies: libwebp IlmImf

— OpenCV modules:
— To be built: hal core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d java stitching videostab python2 python3
— Disabled: world
— Disabled by dependency: –
— Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev viz

— GUI:
— QT: NO
— GTK+: NO
— GThread : NO
— GtkGlExt: NO
— OpenGL support: NO
— VTK support: NO

— Media I/O:
— ZLib: /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.8)
— JPEG: /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver )
— WEBP: build (ver 0.3.1)
— PNG: /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.2.50)
— TIFF: /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 – 4.0.3)
— JPEG 2000: /usr/lib/arm-linux-gnueabihf/libjasper.so (ver 1.900.1)
— OpenEXR: build (ver 1.7.1)
— GDAL: NO

— Video I/O:
— DC1394 1.x: NO
— DC1394 2.x: NO
— FFMPEG: YES
— codec: YES (ver 56.1.0)
— format: YES (ver 56.1.0)
— util: YES (ver 54.3.0)
— swscale: YES (ver 3.0.0)
— resample: YES (ver 2.1.0)
— gentoo-style: YES
— GStreamer: NO
— OpenNI: NO
— OpenNI PrimeSensor Modules: NO
— OpenNI2: NO
— PvAPI: NO
— GigEVisionSDK: NO
— UniCap: NO
— UniCap ucil: NO
— V4L/V4L2: Using libv4l1 (ver 1.6.0) / libv4l2 (ver 1.6.0)
— XIMEA: NO
— Xine: NO
— gPhoto2: NO

— Other third-party libraries:
— Use IPP: NO
— Use Eigen: NO
— Use TBB: NO
— Use OpenMP: NO
— Use GCD NO
— Use Concurrency NO
— Use C=: NO
— Use pthreads for parallel for:
— YES
— Use Cuda: NO
— Use OpenCL: YES

— OpenCL:
— Version: dynamic
— Include path: /media/usb/opencv-3.0.0/3rdparty/include/opencl/1.2
— Use AMDFFT: NO
— Use AMDBLAS: NO

— Python 2:
— Interpreter: /usr/bin/python2.7 (ver 2.7.9)
— Libraries: /usr/lib/arm-linux-gnueabihf/libpython2.7.so (ver 2.7.9)
— numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.8.2)
— packages path: lib/python2.7/dist-packages

— Python 3:
— Interpreter: /usr/bin/python3.4 (ver 3.4.2)
— Libraries: /usr/lib/arm-linux-gnueabihf/libpython3.4m.so (ver 3.4.2)
— numpy: /usr/lib/python3/dist-packages/numpy/core/include (ver 1.8.2)
— packages path: lib/python3.4/dist-packages

— Python (for build): /usr/bin/python2.7

— Java:
— ant: /usr/bin/ant (ver 1.9.4)
— JNI: /usr/lib/jvm/java-1.7.0-openjdk-armhf/include /usr/lib/jvm/java-1.7.0-openjdk-armhf/include /usr/lib/jvm/java-1.7.0-openjdk-armhf/include
— Java wrappers: YES
— Java tests: YES

— Matlab:
— mex: NO

— Documentation:
— Doxygen: NO
— PlantUML: NO

— Tests and samples:
— Tests: YES
— Performance tests: YES
— C/C++ Examples: YES

— Install path: /usr/local

— cvconfig.h is in: /media/usb/opencv-3.0.0/build
— —————————————————————–

— Configuring done
— Generating done
— Build files have been written to: /media/usb/opencv-3.0.0/build
pi@raspberrypi /media/usb/opencv-3.0.0/build $

setelah semuanya sudah sesuai dengan keinginan anda jalankan
$ make -j4
waktu make cukup memakan waktu yang lama, harap bersabar….

jika tidak ada error, lakukan perintah install
$ sudo make install
$ sudo ldconfig

Step terakhir Finishing

check opencv
ls -l /usr/local/lib/python2.7/dist-packages/
total 12428
-rw-r–r– 1 root staff 10372 Nov 28 08:16 clonevirtualenv.py
-rw-r–r– 1 root staff 10905 Nov 28 08:16 clonevirtualenv.pyc
-rw-r–r– 1 root staff 12600608 Jan 12 21:12 cv2.so

jika tidak menemukan cv2.so check di /site-packages/

step verifiy
$ python
Python 2.7.9 (default, Mar 8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import cv2
>>> cv2.__version__
‘3.0.0’
>>>

terlihat import cv2 sukses dan versinya

sumber:

http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/

https://dvsaraiva.wordpress.com/2015/06/13/build-opencv-3-0-gold-edition/

 

Plot grafik ping time delay


setelah kita membuat program sederhana untuk meplot grafik temperature kali ini kita mencoba membuat grafik plot delay ping, seperti yang kita ketahui ping pada terminal akan menghasilkan hasil seperti berikut

Screenshot from 2015-09-19 14:17:05

sekarang kita mencoba memplot kolom time menggunakan bahasa pemgoraman python, pada dasarnya program ini hanya menggabungkan script deteksi suhu dengan script Python Ping


import os, sys, socket, struct, select, time
import serial # import Serial Library
import numpy  # Import numpy
import matplotlib.pyplot as plt #import matplotlib library
from drawnow import *

ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
tempF= []
#arduinoData = serial.Serial('/dev/ttyACM0', 9600) #Creating our serial object named arduinoData
plt.ion() #Tell matplotlib you want interactive mode to plot live data

 
def checksum(source_string):
    """
    I'm not too confident that this is right but testing seems
    to suggest that it gives the same answers as in_cksum in ping.c
    """
    sum = 0
    countTo = (len(source_string)/2)*2
    count = 0
    while count<countTo:
        thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
        sum = sum + thisVal
        sum = sum & 0xffffffff # Necessary?
        count = count + 2
 
    if countTo<len(source_string):
        sum = sum + ord(source_string[len(source_string) - 1])
        sum = sum & 0xffffffff # Necessary?
 
    sum = (sum >> 16)  +  (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
 
    # Swap bytes. Bugger me if I know why.
    answer = answer >> 8 | (answer << 8 & 0xff00)
 
    return answer
 
 
def receive_one_ping(my_socket, ID, timeout):
    """
    receive the ping from the socket.
    """
    timeLeft = timeout
    while True:
        startedSelect = time.time()
        whatReady = select.select([my_socket], [], [], timeLeft)
        howLongInSelect = (time.time() - startedSelect)
        if whatReady[0] == []: # Timeout
            return
 
        timeReceived = time.time()
        recPacket, addr = my_socket.recvfrom(1024)
        icmpHeader = recPacket[20:28]
        type, code, checksum, packetID, sequence = struct.unpack(
            "bbHHh", icmpHeader
        )
        if packetID == ID:
            bytesInDouble = struct.calcsize("d")
            timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
            return timeReceived - timeSent
 
        timeLeft = timeLeft - howLongInSelect
        if timeLeft <= 0:
            return
 
 
def send_one_ping(my_socket, dest_addr, ID):
    """
    Send one ping to the given >dest_addr<.
    """
    dest_addr  =  socket.gethostbyname(dest_addr)
 
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    my_checksum = 0
 
    # Make a dummy heder with a 0 checksum.
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
    bytesInDouble = struct.calcsize("d")
    data = (192 - bytesInDouble) * "Q"
    data = struct.pack("d", time.time()) + data
 
    # Calculate the checksum on the data and the dummy header.
    my_checksum = checksum(header + data)
 
    # Now that we have the right checksum, we put that in. It's just easier
    # to make up a new header than to stuff it into the dummy.
    header = struct.pack(
        "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
    )
    packet = header + data
    my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
 
 
def do_one(dest_addr, timeout):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root."
            )
            raise socket.error(msg)
        raise # raise the original error
 
    my_ID = os.getpid() & 0xFFFF
 
    send_one_ping(my_socket, dest_addr, my_ID)
    delay = receive_one_ping(my_socket, my_ID, timeout)
 
    my_socket.close()
    return delay
 
 
def verbose_ping(dest_addr, timeout = 2, count = 4):
  	def verbose_ping(dest_addr, timeout = 2, count = 4):
  	cnt = 0
	
	while True: # While loop that loops forever
		delay  =  do_one(dest_addr, timeout) #read the line of text from the serial port
		tempF.append(delay)                     #Build our tempF array by appending temp readings
		drawnow(makeFig)                       #Call drawnow to update our live graph
		plt.pause(.000001)                     #Pause Briefly. Important to keep drawnow from crashing
		cnt=cnt+1
		if(cnt>50):                            #If you have 50 or more points, delete the first one from the array
			tempF.pop(0)      


 
def makeFig(): #Create a function that makes our desired plot
    #delay  =  do_one(dest_addr, timeout)
    #plt.ylim(int(delay)-3,int(delay)+3)                                 #Set y min and max values
    plt.title('My Live Streaming Sensor Data')      #Plot the title
    plt.grid(True)                                  #Turn the grid on
    plt.ylabel('Temp C')                            #Set ylabels
    plt.plot(tempF, 'ro-')       #plot the temperature
    plt.legend(loc='upper left')                    #plot the legend
  

if __name__ == '__main__':
    #verbose_ping("heise.de")
    #verbose_ping("google.com")
    #verbose_ping("a-test-url-taht-is-not-available.com")
    verbose_ping("192.168.0.1")

grafik yang dihasilkan sebagai berikut

Screenshot from 2015-09-19 14:27:49

Caesar Cipher di Twitter dengan Python


Setelah sebelum nya kita membahas bagaimana koneksi python dan twitter dan memposting dari file text. Sekarang kita mencoba untuk memposting tweet yang terenkripsi menggunakan caesar cipher dengan script sederhana python.

Sebelum lebih lanjut, bagaimana caesar cipher bekerja di python dalam melihat laman berikut http://inventwithpython.com/hacking/chapter6.html setelah jelas kita hanya meggambungkan caesar cipher tersebut dengan koneksi python. sebagai berikut script nya:

Hal yang perlu anda setting sesuai dengan keinginnan ada adalah:

key = 'isi sesuai dengan twitter anda'
secret = 'isi sesuai dengan twitter anda'
token = 'isi sesuai dengan twitter anda'
token_secret = 'isi sesuai dengan twitter anda'
filename=open('filenomor','r')#filenomor = isi sesuai dengan nama file text anda
 key = 3 # angka "3" isi dengan berapa pergeseran yang anda inginkan
time.sleep(4) # jeda antara twitter
import twitter, time, sys
key = 'isi sesuai dengan twitter anda'
secret = 'isi sesuai dengan twitter anda'
token = 'isi sesuai dengan twitter anda'
token_secret = 'isi sesuai dengan twitter anda'

auth=twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)


filename=open('filenomor','r')#filenomor = isi sesuai dengan nama file text anda
f=filename.readlines()
filename.close()
 
for line in f:

	#Caesar Cipher
	MAX_KEY_SIZE = 26
	
	def getMode():
		while True:
			if mode in 'encrypt e decrypt d'.split():
				return mode
			else:
				print('Enter either "encrypt" or "e" or "decrypt" or "d".')


	def getTranslatedMessage(mode, message, key):
		if mode[0] == 'd':
			key = -key
		translated = ''
	
		for symbol in message:
			if symbol.isalpha():
				num = ord(symbol)
				num += key
			
				if symbol.isupper():
					if num &gt; ord('Z'):
						num -= 26
					elif num &lt; ord('A'):
						num += 26
				elif symbol.islower():
					if num &gt; ord('z'):
						num -= 26
				elif num &lt; ord('a'):
					num += 26

				translated += chr(num)
			else:
				translated += symbol
		return translated

	mode = 'encrypt'
	message = line
	key = 3 # angka "3" isi dengan berapa pergeseran yang anda inginkan

	#print('Your translated text is:')
	statusx=getTranslatedMessage(mode, message, key)
	print(statusx)
	client.statuses.update(status=statusx)
	time.sleep(4) # jeda antara twitter 

Mempost twitter dari file text


Sebelum nya telah dibahas tentang bagaimana koneksi python dan twitter serta bagaimana memposting via python. Saat ini kita mencoba untuk metwitt yang berasal dari file text.

1. pertama-tama buat list apa saja yang ingin dibuat di file text dengan batasan di setiap line nya. misal saya mengcopy lirik lagu berikut dan save dengan nama file filelagu

Dan....bila esok...
datang kembali Seperti
sedia kala dimana kau bisa bercandaDan...
perlahan kaupun lupakan akuMimpi burukmu...
dimana t'lah ku tancapkan duri tajamKaupun menangis...
menangis sedihMaafkan aku
Dan...bukan maksudku...
bukan inginkuMelukaimu sadarkan kau di sini kupun terluka
Melupakanmu...menepikanmuMaafkan aku....
Reff : Lupakan saja dirikuBila itu bisa membuatmu
Kembali bersinar dan berpijarSeperti dulu kala
Caci maki saja dirikuBila itu bisa membuatmu
Kembali bersinar dan berpijarSeperti dulu kala
Dan...bukan maksudku...bukan inginku
Melukaimu sadarkan kau di sini kupun terluka
Melupakanmu...menepikanmu
Maafkan aku....

2. tulis script python sebagai berikut

import twitter, time, sys
key = 'isi sesuai dengan twitter anda'
secret = 'isi sesuai dengan twitter anda'
token = 'isi sesuai dengan twitter anda'
token_secret = 'isi sesuai dengan twitter anda'

auth=twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)


filename=open('filelagu','r')
f=filename.readlines()
filename.close()
 
for line in f:
    client.statuses.update(status=line)
    time.sleep(2)#Tweet setiap 2 detik

jeda antara twit bisa diatur di script “time.sleep(2)”

Karena twitter tidak memperkenankan duplicate twitt dalam waktu tertentu, maka pada line yang sama, twitter akan langsung mereject post tersebut.

Koneksi Python Twitter


ide dasarnya bagaimana kita dapat mengelola akun twitter melalui PC kita tanpa harus login di webbrowser ataupun menggunakan program twitter. Kita menggunakan pemograman sederhana python untuk koneksi tersebut.

Berikut step-stepnya:

1.buat token via twitter https://apps.twitter.com/ >Create NewApp> isi data-data yang diminta dan create twitter appilication

2. Ubah Setting sesuai keinginan

3. Ambil data-data berikut: Consumer Key (API Key), Consumer Secret (API Secret), Access Token, Access Token Secret

Setelah itu masuk kedalam instalasi paket twitter kedalam python

sudo pip install twitter

Jika ada problem di pip nya, remove pip dan easy_install pip

sudo apt-get purge python-pip
sudo easy_install pip

4. Tulis program sederhana sebagai berikut dan save kedalam file misal testtwitter.py:

import twitter 
key = 'isi sesuai dengan twitter'
secret = 'isi sesuai dengan twitter
token = 'isi sesuai dengan twitter'
token_secret = 'isi sesuai dengan twitter'
auth=twitter.OAuth(token, token_secret, key, secret)
 

 

5. Setelah itu run file python tersebut di terminal python testtwitter.py , jika tidak ada error python sudah terkoneksi dengan twitter

Jika ingin mencoba posting tambahkan script di testtwitter.py

client = twitter.Twitter(auth=auth)
client.statuses.update(status="#Python test!")

cek di twitter sudah terposting #Python test!