My Twitch bot (using Pircbot) doesn't stay connected to a channel - java

I'm trying to create a twitch bot, and the first thing I'm trying to make it do is respond to chat messages. However, when the bot connects to the chat room, it doesn't seem to stay connected. It sends chat messages fine, but it doesn't recieve them.
Here's the code if you want to look at it. I feel like I'm missing something basic that I should've remembered, so if you can figure out what that is I'd like to know.
package me.acezephyr.lavabot;
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import org.jibble.pircbot.PircBot;
public class LavaStreamBot extends PircBot {
private static LavaStreamBot INSTANCE = new LavaStreamBot();
public static void main(String[] args) {
INSTANCE.setVerbose(true);
INSTANCE.setName("LavaStreamBot");
try {
INSTANCE.connect("irc.twitch.tv", 6667,
"oauth:******************************");
} catch (NickAlreadyInUseException e) {
System.err
.println("Tried to join Twitch server, but someone else online already has the nick LavaStreamBot.");
} catch (IOException e) {
e.printStackTrace();
} catch (IrcException e) {
e.printStackTrace();
}
join("#AceLava");
}
public static void join(String channel) {
INSTANCE.joinChannel(channel);
INSTANCE.sendMessage(channel, "LavaStreamBot is now in this channel.");
}
#Override
public void onConnect() {
System.out.println("Connected to server");
super.onConnect();
}
#Override
public void onMessage(String channel, String sender, String login, String hostname, String message){
System.out.println("Got a message!");
super.onMessage(channel, sender, login, hostname, message);
}
}

You wrote the channel name ("#AceLava") with capitals. In IRC, this is a different channel than #acelava - Twitch always handles the channels with all lowercase. Just change that and you'll be all fine.
Not related to the question, but you might want to know about the fact that twitch will change their Background messaging service soon™ and it won't be done via IRC so you'll have to change your bot accordingly (as well as I'll have to do >.< ).
For more information and to keep up to date, visit http://discuss.dev.twitch.tv/

Related

Sending message does not work in XMPP with Smack library

Problem Description
I'm writing chat application using XMPP and Smack Android library. I'm sending messages using code below and everything is working fine.
final ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addChatListener(this);
....
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(this);
}
#Override
public void processMessage(Chat chat, Message message) {
// Do something here.
}
Chat chat = ChatManager.getInstanceFor(connection).createChat(jid);
chat.sendMessage("message");
Question
Unfortunately the API above is deprecated org.jivesoftware.smack.chat.Chat and instead I should use org.jivesoftware.smack.chat2.Chat, so I am changing implementation as follows
final ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addOutgoingListener(this);
chatManager.addIncomingListener(this);
....
Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid);
chat.send("message");
In this case I can still get Incoming messages, but when I am trying to send message with chat.send("message"); server does not get anything and addOutgoingListener callback is not called.
Any ideas why?
There is an example with an older version of smack:
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class Test {
public static void main(String args[]) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
connection.login("userx", "123456");
ChatManager cm = connection.getChatManager();
Chat chat = cm.createChat("tongqian#tsw-PC", null);
/*
* add listener
*/
cm.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message msg) {
System.out.println(chat.getParticipant() + ":" + msg.getBody());
}
});
}
});
chat.sendMessage("hello");
while(true);
//connection.disconnect();
}
}
Answer
Digging a bit deeper I found the answer, the code below will help to send a message
Sending Message Code
final Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid);
Message newMessage = new Message(jid, Message.Type.chat);
newMessage.setBody(message);
chat.send(newMessage);
Conclusion
So instead of sending a string message, you need to create a Message object and I think what is more important is to specify Message.Type.chat in the constructor and also jid and then call chat.send(...)
You can refer to this code snippet:
public void sendMessage(String to, Message newMessage) {
if(chatManager!=null) {
Chat newChat = chatManager.createChat(to);
try {
if (connection.isConnected() && connection.isAuthenticated()) {
newChat.sendMessage(newMessage);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
else
{
Log.d(TAG,”chatmanager is null”);
}
}
And the link is https://ramzandroidarchive.wordpress.com/2016/03/13/send-messages-over-xmpp-using-smack-4-1/ .

How to import the Gottox/socket.io-java-client api in current Eclipse Android Project?

I'm trying to write a JavaScript server running on node.js using Socket.io that communicates with the client which is my android app (java class). Since I need a combination of a JS server and java client that utilizes the Socket.io (or any other efficient websockets) framework, I found the Gottox/socket-io.-java-client implementation that seemed like it might do the job.
Problem: I'm very new to socket programming and working with Github projects. I tried following the simplistic approach mentioned on the project but ran into build errors with Eclipse, specifically relating to Archiving issues with WebSocket.jar and json-org.jar.
Unable to solve this, I tried importing the project into Android Studio when I ran into a whole different bug, which I'm very unfamiliar with.
I just want to make sure I'm working with this project right in the first place. This is what my client class looks like:
package com.example.culami;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import org.json.JSONException;
import org.json.JSONObject;
public class AcknowledgeExample implements IOCallback {
private SocketIO socket;
/**
* #param args
*/
/*public static void main(String[] args) {
try {
new AcknowledgeExample();
} catch (Exception e) {
e.printStackTrace();
}
}*/
public AcknowledgeExample() throws Exception
{
socket = new SocketIO();
socket.connect("http://192.168.0.108:3000/", this);
// Sends a string to the server.
socket.send("Hello Server");
// Sends a JSON object to the server.
socket.send(new JSONObject().put("key", "value").put("key2",
"another value"));
// Emits an event to the server.
socket.emit("event", "argument1", "argument2", 13.37);
}
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
#Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
#Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
#Override
public void onConnect() {
System.out.println("Connection established");
}
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
}
I imported the socketio.jar and even WebSocket.jar and json-org.jar because it seemed these were needed as well. Any feedback on what I'm doing wrong or how I should incorporate this library in my android project will be highly appreciated since I've already spent countless hours trying to debug the build issue.
Note: I'm using Android L, API 21 and jdk1.7 to run this project.
Instead you can add
socket.io-client-0.1.0.jar
The link for his http://mvnrepository.com/artifact/com.github.nkzawa/socket.io-client/0.1.0

Java Kryonet servers, client not receiving server response

I am trying to teach myself some networking in Java using the Kryonet library. The following code is almost identical to the code in the kyronet tutorial. https://code.google.com/p/kryonet/#Running_a_server
The client is successfully sending the message "Here is the request!" to the server (the server is printing it out) however the client is not receiving any response from the server even though the server is sending one.
I've tried unsuccessfully to fix it, can anyone see or suggest a possible problem/solution with the code?
(The code follows)
Client
public class Client_test {
Client client = new Client();
public Client_test() {
Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
client.start();
try {
client.connect(50000, "127.0.0.1", 54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeResponse) {
SomeResponse response = (SomeResponse)object;
System.out.println(response.text);
}
}
});
SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);
}
}
Server
public class ServerGame {
Server server = new Server();
public ServerGame() {
Kryo kryo = server.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
server.start();
try {
server.bind(54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeRequest) {
SomeRequest request = (SomeRequest)object;
System.out.println(request.text);
SomeResponse response = new SomeResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
}
}
Response & Request classes
public class SomeRequest {
public String text;
public SomeRequest(){}
}
public class SomeResponse {
public String text;
public SomeResponse(){}
}
After many hours watching youtube videos and sifting through the web I found the answer. Which I will post on here as it seems that quite a few people have had this problem so I would like to spread the word.
Basically the client would shut down immediately, before it could receive and output the message packet. This is because "Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing.", the solution is "Maybe you could use this? new Thread(client).start();".
So basically instead of using
client.start();
to start the client thread you must use
new Thread(client).start();
Which I believe stops the thread being made into a daemon thread which therefore stops the problem.
Source: https://groups.google.com/forum/?fromgroups#!topic/kryonet-users/QTHiVmqljgE
Yes, inject a tool like Fiddler in between the two so you can see the traffic going back and forth. It's always easier to debug with greater transparency, more information.

How to send and receive SMS in java?

I want my Java application to send and receive SMS without using any additional hardware devices and it must be free.
I made my search but all i found is titles, i found somethings like SMSLib but at the other hand i didn't find tutorials or books to learn that.
I also found that SMSLib code but didn't understand:
Send Message/SMS Code
package SMSEngine;
import org.smslib.*;
class SendMessage
{
public static void sendMessage(String number, String message)
{
CService srv = new CService("COM4",9600,"huawei","E220");
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.setSmscNumber("");
srv.connect();
COutgoingMessage msg = new COutgoingMessage(number, message);
msg.setMessageEncoding(CMessage.MessageEncoding.Enc7Bit);
msg.setStatusReport(true);
msg.setValidityPeriod(8);
srv.sendMessage(msg);
srv.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
}
Read Message/SMS Codes
package SMSEngine;
import org.smslib.*;
import java.util.*;
class ReadMessages
{
static CService srv;
public static LinkedList receiveMessage()
{
LinkedList msgList = new LinkedList();
/*
To Check COM port Go in following path in Windows7
Control Panel\Hardware and Sound\Bluetooth and Local COM
*/
srv = new CService("COM4",9600,"huawei","E220");//"COM1", 57600, "Nokia", ""
try
{
srv.setSimPin("0000");
srv.setSimPin2("0000");
srv.connect();
srv.readMessages(msgList, CIncomingMessage.MessageClass.Unread);
srv.disconnect();
return msgList;
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(0);
return msgList;
}
}
In order to send SMS messages you have two options: either use a gateway modem, or use a bulk service with an online API.
SMSLib is only a library that makes it easier to interface with a gateway (hardware device) or with a bulk SMS provider. Either way, the library by itself is not enough.
The code sample that you provided appears to try to use a gateway connected to a local serial port but since you don't have such a hardware device it's not going to work for you.
One way is to use SMS gateway and send them like ordinary emails.
"I also found that SMSLib code but didn't understand"-
Assuming that you know java/object oriented programming, read through an online tutorial on smslib for understanding the basics. May be you can start with this one http://smslib.org/doc/smslib/quickstart/

Writing to an AsynchronousSocketChannel and processing the data in an Event-based way

I'm trying to figure out how to send data between sockets in Java (this is part of a bigger project and I'll get back and answer my previous two questions related to that once I can resolve this..). I would like to connect a client and a server socket asynchronously in Java, and then send messages between them, and get a callback, say, when I have sent a message from the client to the server.
I think I have managed to get the set-up working. Here is my code:
private AsynchronousServerSocketChannel socListener;
private AsycnchrnonousSocketChannel socClient;
//This is the GUI callback for the button that initiates the socket server
private void button_StartSocketServerActionPerformed(ava.awt.event.ActionEvent evt)
{
try{
InetAddress ipLocal= InetAddress.getLocalHost();
InetSocketAddress ipSocket=new InetSocketAddress(ipLocal,8221);
m_socListener= AsynchronousServerSocketChannel.open().bind(ipSocket);
m_socListener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>()
{
#Override
public void completed(AsynchronousSocketChannel ch, Void att)
{
// accept the next connection
m_socListener.accept(null, this);
// handle this connection
}
#Override
public void failed(Throwable exc, Void att) { }
}
);
}
catch (Exception e){
}
}
//This is the GUI callback for the button that initiates the client socket
private void button_StartClientSocketActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
socClient=AsynchronousSocketChannel.open();
InetAddress ipLocal= InetAddress.getLocalHost();
InetSocketAddress ipSocket=new InetSocketAddress(ipLocal,8221);
socClient.connect(ipSocket, null, new CompletionHandler<Void,Void>()
{
#Override
public void completed(Void att1, Void att2)
{
// handle this connection
}
#Override
public void failed(Throwable exc, Void att) {}
}
);
}
catch (Exception e){
}
}
I'm including the server and the client in the same file for simplicity of testing.
So supposing the connection is successfully established, and I have a process on a timer (say) that was writing data to the server socket, I'd like to have the client socket 'listen' for this new data being sent from the server and then generate a callback when a write occurs (without doing something like periodically checking via a timer and a while loop to check that whether new data has been added). This is accomplishable in C# and a nice tutorial is available at:
http://www.developerfusion.com/article/3918/socket-programming-in-c-part-1/2/
Any tips on how to do this would be greatly appreciated. Thanks!
Chris
You could use RMI to accomplish that, the documentation can be found there:
http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136424.html
With this, your server could notify your client as much as you need.

Categories