Creating a Simple Yahoo Messenger Auto Response with Java and OpenYMSG Library

Hi, several days ago someone asked me to help him on his assignment related to Yahoo Messenger Application with Java. That’s why today im trying to help him by creating a simple example on auto response and message sending using one of the best open source Yahoo Messenger API implementation, OpenYMSG.

It’s actually quite easy, only several lines of codes. This is how i do it

package com.edw.yahoo;

import java.util.Scanner;
import org.apache.log4j.Logger;
import org.openymsg.network.FireEvent;
import org.openymsg.network.ServiceType;
import org.openymsg.network.Session;
import org.openymsg.network.event.SessionEvent;
import org.openymsg.network.event.SessionListener;

/**
 *  com.edw.yahoo.YahooLogin
 *
 *  @author edw
 */
public class YahooLogin implements SessionListener {

    private Logger logger = Logger.getLogger(YahooLogin.class);
    private Session session = new Session();

    public static void main(String[] args) {
        YahooLogin yahooLogin = new YahooLogin();
        yahooLogin.doLogin();
    }

    public YahooLogin() {
    }

    private void doLogin() {
        try {
            // insert your yahoo id
            // as for this example, im using my yahoo ID "dombaganas"
            session.login("dombaganas", "MyYahooPassword", true);
            session.addSessionListener(this);
            Scanner scanner = new Scanner(System.in);

            while (true) {
                System.out.println("please insert your message : ");
                String message = scanner.nextLine();

                // logout if message equals to "bye"
                if (message.equalsIgnoreCase("bye")) {
                    break;
                }
                // send message to targeted yahoo id
                session.sendMessage("TargetYahooID", message);
            }

            // logout from YM
            session.logout();
        } catch (Exception e) {
            logger.error(e, e);

        }
    }

    /*
     *  this is my listener method
     *  it listen for YM message request
     */
    @Override
    public void dispatch(FireEvent fe) {
        ServiceType type = fe.getType();
        SessionEvent sessionEvent = fe.getEvent();

        if (type == ServiceType.MESSAGE) {
            try {
                // log request message
                logger.debug("message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage());

                // give an automatic response
                session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
    }
}

These are some screenshots related to this application.

To my friend, i hope this tutorial can help you getting started with your assignment. As the wise man once said “Answering one good question is like feeding a hungry person one meal, but teaching them research skills by example is showing them how to grow food for a lifetime.”

YNWA
(I)

ps. if somehow you found a NoClassDefFoundError, such as :
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
you need to include apache common logging lib into your project classpath.

Google+

47 Comments

zulkarnain

about 6 years ago

maaf suhu..tutorial di atas kurang jelas ne.. itu yang log4j.properties nya g dijelasin apa isinya.. sama step by step tentang pembuatan project ini di netbeaan nya donk suhu... apa2 aja yang musti di lakuin. mohon bantuannya bener ya suhu...buat skripsi ini. ;-) ;-)

Reply

edwin

about 6 years ago

settingan log4j ane # Global logging configuration log4j.rootLogger=DEBUG,stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c:%L - %m%n

zulkarnain

about 6 years ago

errornya begini suhu pas saya run filenya run: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.openymsg.network.Session.(Session.java:185) at yahoomessengerapp.YahooLogin.(YahooLogin.java:18) at yahoomessengerapp.YahooLogin.main(YahooLogin.java:21) Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) ... 3 more Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

Reply

edwin

about 6 years ago

wah kok errornya aneh, itu karena loe kurang library tuh coba tambahin lib apache common logging.jar btw loe pakek JDK brp tuh?

farham

about 6 years ago

sama ama yang di atas bang.... ;-(

Reply

edwin

about 6 years ago

kayaknya ketinggalan lib apache common logging deh

sen_saven

about 6 years ago

thanks a lot edwin! great job!

Reply

edwin

about 6 years ago

Thank you sen_saven, glad i could help you :)

Ronald

about 5 years ago

Pagi gan. Ane dpt web ini dari paman gugel neh.Kebetulan ane lagi mau buat Ym auto reply juga.Nah masalahnya adalah:ane cuma bisa bahasa vb6&vb.net ajah neh:(. Pertanyaan ane simple gan,Bisa gak lib ini ane pake di vb.net?kalau bisa gimana? Thanks, Ronald

Reply

edwin

about 5 years ago

Alow bro Ronald, sayangnya gag bisa bro, loe harus pakek cara lain. Kalo ga salah gw pernah liat di kaskus programmer forum, caranya bikin auto reply YM pakek vb.

Ashraful

about 5 years ago

how can i get all contacts by openymsg.pls help me

Reply

edwin

about 5 years ago

Hi Ashraful, try using class SessionListEvent, and get your contacts using method getContacts().

faiz fadly

about 5 years ago

log4j:WARN No appenders could be found for logger (org.openymsg.network.Session). log4j:WARN Please initialize the log4j system properly. knapa ada warning kayak gituan ya?? tapi run well sih.

Reply

edwin

about 5 years ago

Hi Faiz, itu terjadi karena kamu ga punya log4j.properties di classpath kamu

faiz fadly

about 5 years ago

owh gitu,, Cara nya gimana ya buat nambahin log4j.properties?? blom ngerti, baru make java soalnya. :)

Reply

edwin

about 5 years ago

Hi Faiz, kalo ga salah gw pernah nulis soal log4j deh disini. Coba kamu buka-buka lagi archieve blog gw. :)

Mr Akhtarul

about 4 years ago

I need auto replay massanger, so can you give me Add skye: liveonline802

faiz fadly

about 5 years ago

OK edwin :) saya mau tanya satu kali lagi, mohon maaf sebelum nya klo banyak tanya, saya baru belajar java dan sangat tertarik ingin mendalami java, pertanyaannya : jadi saya ingin setiap ada chat yang masuk juga tersimpan di database(saya menggunakan mysql), untuk koneksi ke DB sudah berhasil, dimana seharusnya saya meletakkan coding untuk insert ke db? di blok ini kah?? if (type == ServiceType.MESSAGE) { try { trus coding yang ini fungsinya untuk apa? logger.debug(); apakah untuk log message yang masuk? mohon maaf yang sebesar2 nya klo ngerepotin, hehe.. :) tutorial yang sangat bagus :)

Reply

edwin

about 5 years ago

Hi faiz, Logger itu buat debugging alias nulis ke console, klo mo masuk ke db, kamu bener jika taro dibawah blok if (type == ServiceType.MESSAGE) {

faiz fadly

about 5 years ago

ok edwin, terimakasih banyak sudah membantu.

Okta Anang

about 5 years ago

mas mau nanya ane tertarik buat fitur ini cuman library nya saya belum punya dimana ya saya bisa mendapatkan library nya? atau ada contoh project sederhana diatas yang udah satu paket? jujur saya masih buta soal java makanya saya ingin belajar terimakasih

Reply

edwin

about 5 years ago

Halo Okta, libnya bisa didapat di sourceforge, btw pertanyaannya udah kejawab di kaskus yah :D

tuan

about 5 years ago

Dear, I use ikvm tool (http://www.ikvm.net/devguide/net2java.html) to covert OpenYMSG Library to C#. But when C#, i run new Session it returns error May you help me Thanks

Reply

rofi

about 4 years ago

bro, mau tanya ni. gue dah login dari YM ni, trus gue ngeRun program ni, tiba2 YM gue log out otomatis, caranya biar sama2 login gmn ya..??

Reply

edwin

about 4 years ago

ya iya dong, dia ga bisa login pake id yang sama dalam 2 aplikasi yang berbeda. Kalo mao loe pake 2 id ym yang berbeda.

krista

about 4 years ago

saya mau tanya urgent klo buka file "report servlet" pake apa ya?

Reply

edwin

about 4 years ago

ReportServlet dimana? Seinget gw sih dia contentdisposition jadi pdf atau excel gitu.

Rifai

about 4 years ago

Thanks Mas bro, saya sudah mencari2 banyak cara. bru ini yg berhasil.. great job :)

Reply

edwin

about 4 years ago

Hi Rifai, glad it can help :)

irul

about 4 years ago

Cakep mas,, sudah ane coba, and work. Tq sharingnya... (Y) (Y) (Y)

Reply

edwin

about 4 years ago

Hi Irul, Glad it can help :)

ijusran

about 4 years ago

cakep mas, makasih banyak.... Satu pertanyaan lagi mas, gimana cara sortir agar pesan yang akan di-reply, hanya teman saja? apakah ada fungsi untuk lookup friends? thanks

Reply

ijusran

about 4 years ago

mantap mas.. Satu lagi mas, gimana caranya agar reply message hanya untuk teman yang terdaftar saja? apakah ada fungsi untuk lookUp friend terdaftar? biar tinggal tambahin aja looping di list friend nya..

Reply

edwin

about 4 years ago

Nah bisa juga tu, list of friends loe tarik jadi ArrayList nanti sender message yg masuk loe cek di ArrayList, exists atau engga? Jika engga exists berarti belum friend :D

faiz fadly

about 3 years ago

Hi... edwin, jika Tiba2 logout sendiri penyebab nya apa ya? log nya seperti ini : WARN Session:455 - Logging out due to socket exception: -246528520/id=xxxxx primaryID=true loginID=false activated=true ini terjadi setelah beberapa jam aplikasi berjalan. apakah ada cara agar login kembali secara otomatis? terimakasih edwin untuk bantuan nya.. :)

Reply

edwin

about 3 years ago

gw pernah kayak gitu dulu, coba loe pakek library yg terbaru om, dulu gw kayak gitu karena YM ubah protocol messagingnya untuk autoreconnect, loe bisa tempelin listener, jadi kalo disconnected bisa di-autoreconnect.

faiz

about 3 years ago

saya sudah make versi paling baru mas edwin yang 0.6.0 yang saya gak ngerti cara nempelin listener nya itu gimana ya... hehe, saya jarang make java. klo mas edwin gak keberatan saya boleh minta contoh nya. maaf ya mas klo ngerepotin. hehe..

Reply

edwin

about 3 years ago

nah kamu bikin class yg implements listener-nya lalu override method yg ada di interface.

Maheshwar

about 3 years ago

Hi Edwin i want the JSP & Servlet to login using openymsg but i got Problem in session can u post example like that

Reply

edwin

about 3 years ago

Hi Maheswar, i'll try and create a simple example on my free time. Take care.

Bagus Suwandi

about 3 years ago

Salam mas..... Saya baru coba code itu menggunakan Netbeans .... dan berjalan .... Namun beberapa saat kemudian setelah mencoba mengimplementasikan ke Java Desktop ... beberapa saat tidak ada masalah. Namun kemudian terjadi error seperti ini. Maaf saya Copas Log Console di Netbeans yach : 2014-07-20 23:51:47.281 WARN org.openymsg.network.Session:273 - SessionListener not found to be removed. java.lang.Throwable at org.openymsg.network.Session.removeSessionListener(Session.java:273) at org.openymsg.network.Session.resetData(Session.java:3698) at org.openymsg.network.Session.login(Session.java:340) at org.openymsg.network.Session.login(Session.java:295) at learn.YahooLogin.doLogin(YahooLogin.java:38) at learn.YahooLogin.main(YahooLogin.java:28) 2014-07-20 23:51:47.578 DEBUG org.openymsg.network.DirectConnectionHandler:127 - Source socket: /192.168.1.3:3865 yahoo socket: scs.msg.yahoo.com/66.196.121.57:5050 2014-07-20 23:51:47.578 DEBUG org.openymsg.network.Session:3599 - Sending packet on/to the network. SessionId[0x0] ServiceType[AUTH] Status[AVAILABLE] Body[1 center1.bsream ] 2014-07-20 23:51:47.859 DEBUG org.openymsg.network.YMSG9InputStream:110 - Magic:YMSG Version:16 Length:85 Service:AUTH Status:1 SessionId:0x5dcba4 [1] [center1.bsream] [13] [2] [94] [a*1*w|t^b&h^(8/1|r*(x|m|y*y)|r*n|u*8|j*v|e*e|c*5|s*d)] 2014-07-20 23:51:48.546 ERROR org.openymsg.network.InputThread:83 - error on process packet org.openymsg.network.LoginRefusedException: Login locked at org.openymsg.network.Session.yahooAuth16Stage1(Session.java:2008) at org.openymsg.network.Session.receiveAuth(Session.java:1892) at org.openymsg.network.InputThread.processPayload(InputThread.java:139) at org.openymsg.network.InputThread.process(InputThread.java:129) at org.openymsg.network.InputThread.run(InputThread.java:71) 2014-07-20 23:51:48.546 ERROR org.openymsg.network.Session:388 - Never logged in, sessionStatus is: FAILED 2014-07-20 23:51:48.562 DEBUG org.openymsg.network.InputThread:79 - logging out so don't handle exception java.net.SocketException: socket closed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read1(BufferedInputStream.java:275) at java.io.BufferedInputStream.read(BufferedInputStream.java:334) at org.openymsg.network.YMSG9InputStream.readBuffer(YMSG9InputStream.java:154) at org.openymsg.network.YMSG9InputStream.readPacket(YMSG9InputStream.java:63) at org.openymsg.network.DirectConnectionHandler.receivePacket(DirectConnectionHandler.java:180) at org.openymsg.network.InputThread.run(InputThread.java:71) 2014-07-20 23:51:48.562 ERROR learn.YahooLogin:58 - org.openymsg.network.LoginRefusedException: Login locked org.openymsg.network.LoginRefusedException: Login locked at org.openymsg.network.Session.yahooAuth16Stage1(Session.java:2008) at org.openymsg.network.Session.receiveAuth(Session.java:1892) at org.openymsg.network.InputThread.processPayload(InputThread.java:139) at org.openymsg.network.InputThread.process(InputThread.java:129) at org.openymsg.network.InputThread.run(InputThread.java:71) N ah itu errornya kenapa mas Sebelumnya : Terima kasih atas perhatian dan jawabanya.

Reply

edwin

about 3 years ago

Hi Bagus, itu id YM loe udh keblokir, coba buka dari YM biasa lalu cek bisa masuk engga?

aaaa

about 3 years ago

message sending successfuly , but I am getting this error & also n't receiving messge java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at org.openymsg.network.Session.receiveStatus15(Session.java:2992) at org.openymsg.network.InputThread.processPayload(InputThread.java:238) at org.openymsg.network.InputThread.process(InputThread.java:129) at org.openymsg.network.InputThread.run(InputThread.java:71)

Reply

bryan

about 2 years ago

ini awalnya gmn ya ? saya buat class baru terus saya copas scriptnya. di run muncul error a java exception has occured

Reply

edwin

about 2 years ago

error-nya apa?

Rujel

about 4 months ago

Is it work now???it not work for me, it show login failed

Reply

edwin

about 3 months ago

Hi Rujel, i dont know whether it's still work or not, i wrote it like 6years ago.

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)