Discord JDA onGuildMemberJoin not working - java

I have this code:
public class Main extends ListenerAdapter {
public static void main(String[] args) {
try{
JDA jda = JDABuilder.createDefault("MyToken")
.addEventListeners(new Main()).build();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event)
{
User user = event.getUser();
TextChannel textChannel = event.getGuild().getTextChannelById("myChannelId");
textChannel.sendMessage(String.format("%s %s", "Welcome, ", user.getName())).queue();
}
}
I think this should working? I just want the bot to say "Welcome" in a specific channel when a member join the server but nothing append when I run that and join my server.
Any solutions?

Related

Java inheritance with Redis

Having subscriber class:
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
public class Subscriber extends JedisPubSub {
private static final org.apache.log4j.Logger logger = LogManager.getLogger(Subscriber.class);
#Override
public void onMessage(String channel, String message) {
logger.info("Message received. Channel: " + channel + ", Msg: " + message);
}
#Override
public void onSubscribe(String channel, int subscribedChannels) {
logger.info("Subscribed to channel: " + channel);
}
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinelsHashSet, password);
Jedis jPublisher = pool.getResource();
Jedis jedis = pool.getResource();
Subscriber subscriber = new Subscriber();
jedis.subscribe(subscriber, channel);
jedis.quit();
} catch (Exception e) {
logger.error(e.toString());
}
}
});
t.run();
}
}
Which basically print all messages received on Redis channel I wanted to create child class with different onMessage or onSubscribe methods. Im calling Subscriber class from Main class by
Subscriber sb = new Subscriber();
sb.main(new String[]{});
So I have tried:
Copy main method and change Subscriber subscriber = new Subscriber(); to SubscriberExtended subscriber = new SubscriberExtended(); and call from Main class by:
1.1)
Subscriber sb = new SubscriberExtended();
sb.main(new String[]{});
or
SubscriberExtended sb = new SubscriberExtended();
sb.main(new String[]{});
import org.apache.log4j.LogManager;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
public class SubscriberExtended extends Subscriber {
private static final org.apache.log4j.Logger logger = LogManager.getLogger(SubscriberExtended.class);
#Override
public void onSubscribe(String channel, int subscribedChannels) {
logger.info("Subscribed to channel from Extended class: " + channel);
}
public SubscriberExtended() {
}
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinelsHashSet, password);
Jedis jPublisher = pool.getResource();
Jedis jedis = pool.getResource();
SubscriberExtended subscriber = new SubscriberExtended();
jedis.subscribe(subscriber, channel);
jedis.quit();
} catch (Exception e) {
logger.error(e.toString());
}
}
});
t.run();
}
Also I have tried to put in constructor
public SubscriberExtended() {
super.main(new String[]{});
}
And few others configuration of those and nothing seems to be working.
What I'm trying to achieve is to create SubscriberExtended class which will behave same as Subscriber class but override onMessage or onSubscribe methods. Can anyone help me?
This appears that it should work, although I am not sure why you are adding a static main to all the classes.
You should be able to do the following:
public class Subscriber extends JedisPubSub {
private static final org.apache.log4j.Logger logger = LogManager.getLogger(Subscriber.class);
#Override
public void onMessage(String channel, String message) {
logger.info("Message received. Channel: "+channel+", Msg: "+message);
}
#Override
public void onSubscribe(String channel, int subscribedChannels) {
logger.info("Subscribed to channel: " + channel);
}
public void start() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinelsHashSet, password);
Jedis jedis = pool.getResource();
jedis.subscribe(this, channel);
jedis.quit();
} catch (Exception e) {
logger.error(e.toString());
}
}
});
t.start();
}
}
public class SubscriberExtended extends Subscriber {
#Override
public void onMessage(String channel, String message) {
logger.info("Extended Message received. Channel: "+channel+", Msg: "+message);
}
}
Then, from your main function somewhere, you would have the following:
public class Main()
{
public static void main(String[] args)
{
SubscriberExtended se = new SubscriberExtended();
se.start();
while(true) {
// do something else or sleep
}
}
}
I believe one mistake you made was to call t.run() instead of t.start(). t.run() will not return, unless the subscribe fails for some reason such as the connection to REDIS was closed. t.start() will kick off the thread.
You also seemed to grab a publisher connection from the jedis pool for no reason.
Another problem is here:
Subscriber sb = new SubscriberExtended();
sb.main(new String[]{});
sb.main will proceed to also call new SubscriberExtended() to use with the subscribe, and so your sb object will not receive any publications - they will go to the instance created inside sb.main instead. Using 'this' inside the start() method to subscribe will address that issue.
Once that is set up, you can go ahead and connect to REDIS with redis-cli and issue a publish to see if your program receives the message.

How to build a Telegram bot to suggest you pizza using java?

I created a Main java file and I added an instruction for the bot: say "I love Pizza" on a public channel I created.
public class Main {
public static void main(String[] args) {
//create a new Telegram bot object to start talking with Telegram
TelegramBot bot = TelegramBotAdapter.build(“HERE YOUR API KEY”);
bot.sendMessage(“#pizzaciaopizza”, “I love Pizza”);
}
}
This worked. Good start. Thankfully my bot loves pizza.
I wanted to enable my bot to answer a command like "/recommendPizza" and to answer something.So how can one do this?
Any help?
You seem to be using https://github.com/pengrad/java-telegram-bot-api, right?
I have previously used https://github.com/rubenlagus/TelegramBots. It provides a simple listener API to receive updates:
public class PizzaBot {
private static final Logger LOG = Logger.getLogger(PizzaBot.class.getName());
public static void main(String... args) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
telegramBotsApi.registerBot(new TelegramLongPollingBot() {
#Override
public void onUpdateReceived(Update update) {
Message message = update.getMessage();
Long chatId = message.getChatId();
String input = message.getText();
if ("/recommendPizza".equals(input)) {
SendMessage request = new SendMessage();
request.setChatId(chatId.toString());
request.setText("Have a calzone!");
try {
sendMessage(request);
} catch (TelegramApiException e) {
LOG.log(Level.SEVERE, "Could not send message", e);
}
}
}
#Override
public String getBotUsername() {
return "YOUR_BOT_USERNAME";
}
#Override
public String getBotToken() {
return "YOUR_BOT_TOKEN";
}
});
}
}

unable to subscribe paho mqtt java

I'm new to mqtt. Getting started I tried publishing and subscribing topics to mosquitto broker. I was able to publish messages. But my subscriber is not listening to the topic, it will start and stop without waiting/polling for messages.
Here is the subscriber code,
public class MqttSubscriber implements MqttCallback {
private static final String TOPIC = "iot/endpoint";
public static void main(String[] args) {
new MqttSubscriber().listen();
}
public void listen() {
MqttClient client = null;
try {
client = MqttClientGenerator.generateSubscriberClient();
client.connect();
System.out.println("Fetching messages...");
client.subscribe(TOPIC);
client.setCallback(this);
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void connectionLost(Throwable t) {
t.printStackTrace();
}
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message received from broker...");
System.out.println("Received Message: -- ");
System.out.println(message.getPayload().toString());
}
}
MqttClientGenerator :
public class MqttClientGenerator {
private static final String BROKER_URI = "tcp://localhost:1883";
private static final String CLIENT_ID = "pub";
private static final String SUBSCRIBER_ID = "sub";
private MqttClientGenerator () {}
public static MqttClient generatePublisherClient() throws MqttException{
//adding timestamp to make client name unique every time
return new MqttClient(BROKER_URI, CLIENT_ID+new Date().getTime());
}
public static MqttClient generateSubscriberClient() throws MqttException{
//adding timestamp to make client name unique every time
return new MqttClient(BROKER_URI, SUBSCRIBER_ID+new Date().getTime());
}
}
what am i missing here?
Try deleting the line where you disconnect the client.

Nullpointer exception using networking with JavaFx GUI

sorry about the title I had trouble finding out what I should call it.
So here is the deal! I am currently creating a chat application where I use a Gui using I've created in JavaFx (a Gui that has some graphics on it but I think that is kinda irrelevant) what I have done so far is that I've setup a small server that each client connect to through the program! The main idea is that the clients sends a message to the server and the server will then send it to the other client (which is the whole idea in a chat program) one important note is that I am not using Threads and do not wish to yet!
So to get down to the real problem:
I've created a client class that contains methods to connect, receive and send. my Connect class works fine with my Gui and I am able to connect to the server without any problems!
The problem begins when I try to send to or receive from my server. No matter how many exceptions I throw or how many try Catch I do I get a nullpointer error! I've looked at the code for about 2 hours trying to figure out the problem but without luck! my code are as following:
Client class:
private PrintWriter pw;
/**
* #param args
* #throws IOException
*/
public void connect() throws IOException{
final int portNumber = 6040;
// du kan vælge at bruge inetadressen til at connecte i socketet.
InetAddress adr = InetAddress.getByName("localhost");
Socket socket = new Socket("localhost", portNumber);
pw = new PrintWriter(socket.getOutputStream());
// outPut - Programmet sender til serveren
pw.println("Connected waiting for input");
pw.flush();
//input - Serveren sender til programmet;
}
public void Send(String x) throws IOException{
if (x != null) {
pw.print(x);
pw.flush();
}else {
System.out.println("ingen meddelse");
}
}
public String getInformation(){
Scanner informationFromServer = new Scanner(System.in);
String x = informationFromServer.nextLine();
if (x== null) {
return "";
}
return x;
}
my simpleController code (the code that controls my GUI):
public class SimpleController implements Initializable{
public Button btn_Connect;
private Client client;
public Label chatPerson3;
public Label chatPerson1;
public Label lbl_Chatperson1_userName;
public TextField txt_userName;
public TextField textField_chat;
public TextField txt_ChatPerson1;
public Button Send;
public TextField txt_ChatPerson2;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
btn_Connect.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
chatPerson1.setVisible(true);
lbl_Chatperson1_userName.setText(txt_userName.getText());
}
});
Send.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String x = textField_chat.getText();
textField_chat.setText("");
txt_ChatPerson1.setVisible(true);
txt_ChatPerson1.setText(x);
System.out.println(x);
try {
client.Send(x);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}}
and last but not least my main:
public class Main extends Application{
public static void main(String[] args) throws IOException{
Application.launch(Main.class, (java.lang.String[]) null);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
Client c = new Client();
c.connect();
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("testingBackground.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Chatten");
primaryStage.show();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
}
}
The exception I get when I try to send is of course in my client.send() method and if I try to receive before I send then it is in the client.getInformation() method.
What have I done wrong? What am I missing?

Smack Presence Doesn't Work

Actually I programming a IM service (inherited google chat) by using smack API. But when i want to print buddy list and their presences, the compile mode show all presences unavailable, but in the debug mode it shows the real availability!
My code is ...
1- create connection
public boolean openConnection() {
ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration("talk.google.com", 5222, "mail.google.com");
this.connection = new XMPPConnection(connectionConfiguration);
try {
this.connection.connect();
} catch (XMPPException e) {
// TODO: Send Error Information To Programmer's Email Address
}
if(this.connection.isConnected()) {
this.roster = this.connection.getRoster();
this.roster.addRosterListener(new RosterListener() {
public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {}
});
return true;
}
return false;
}
2- login
public boolean login(String jid, String password) {
try {
this.connection.login(jid, password, "smack");
} catch (XMPPException e) {
// TODO: Send Error Information To Programmer's Email Address
}
if(this.connection.isAuthenticated()) return true;
return false;
}
3- buddy list
public void buddiesList() {
Collection<RosterEntry> rosterEntries = this.roster.getEntries();
for(RosterEntry rosterEntry: rosterEntries) {
System.out.println(rosterEntry.username() + " === " + this.roster.getPresence(rosterEntry.getUser()));
}
}
4- implementation
public static void main(String args[]) {
IMService imService = new IMService();
imService.openConnection();
imService.login("google account", "password");
imService.buddiesList();
}
Your RosterListener doesn't do anything. This is where you have to put code to update your roster when things like presence messages are received.
The presence you are retrieving is a snapshot in time of what the state was when it was created. To keep the state current, you have to actually code the RosterListener. This is clearly stated in the Javadoc for the getPresence() method.
Adding a Listener to your roster could be better:
https://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions/rosterexchange.html

Categories