Detect user when joining chat room - java

so i am using the PircBot to create an IRC chat bot for twitch strictly with java. I want to add a welcome message when a user connect to my chat which i thought the onJoin() method did but sadly did not. The onJoin() method only responded when the bot itself joined a channel and not when all other users joined. Any help?
Ex: "John has joined the channel." - "Bob has joined the channel"
public void onJoin(String channel, String sender, String login, String hostname)
{
//check to see if another user joines
}

onJoin() is an abstract method, meaning you should not use it directly. Just add an implementation in your bot class.
For example, mine is
public void onJoin(String channel, String sender, String login, String hostname)
{
if (sender.equalsIgnoreCase(NICK))
sendMessage(channel, "Connected to Channel");
}
Also you should edit your post to show your code. People can't help much if they can't see what you're doing.

Related

JDA - Event if new user joined to Guild

I have a problem, I am trying to code a bot using Java Discord API (JDA).
When a new user joins a server, the bot shall send a message, but my code is not working.
Code:
public class UserJoinModule extends ListenerAdapter {
public void onGuildMemberJoined(GuildMemberJoinEvent event) throws LoginException {
String user = event.getMember().getAsMention();
JDA client = new JDABuilder("awesome token").build();
final List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
for (final TextChannel ch : channels) {
ch.sendMessage("New member joined: " + user).queue();
}
}
}
Can someone tell me what is wrong?
For me the issue was not from the listener and method I override.
I believe you have to add GatewayIntent.GUILD_MEMBERS to your JDABuilder.
builder.enableIntents(GatewayIntent.GUILD_MEMBERS);
This fixed the same issue for me.
In your Main.java or whatever the file is, there is a variable of type JDABuilder, on it's same line of code, there is your token, a .build() at the end etc...
Insert this code into that line:
.enableIntents(GatewayIntent.GUILD_MEMBERS)
So it looks like this:
jda = JDABuilder.createDefault("TOKEN").enableIntents(GatewayIntent.GUILD_MEMBERS).build();
For it to work, go to your Discord Developer Portal, click your bot, from the menu on the left, click Bot, then scroll down and enable:
Server Members Intent
There are still noticeable errors like registering a new client on every message and other issues, fix them, then start your bot and it shall work.
Your code should look like this:
public class UserJoinModule extends ListenerAdapter {
#Override // USE THIS WHEN YOU WANT TO OVERRIDE A METHOD
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
String user = event.getMember().getAsMention();
JDA client = event.getJDA(); // DO NOT CREATE A NEW JDA INSTANCE EVERY TIME
List<TextChannel> channels = client.getTextChannelsByName("awesome channel name", true);
for (TextChannel ch : channels) {
ch.sendMessage("New member joined: " + user).queue();
}
}
}
And you must register this listeners in your JDABuilder instance, preferably you only have one of these in your entire codebase. See addEventListeners.
You have 2 problems in your code.
You are creating a new JDA client every time a member joins.
You are sending messages to every channel with that name, in every guild. Not just the guild that the user joined.
Here is what you want to do:
public class UserJoinModule extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Guild guild = event.getGuild(); // Get the guild that the user joined.
User user = event.getUser(); // Get the user that joined.
JDA client = event.getJDA(); // Get the already existing JDA instance.
List<TextChannel> channels = guild.getTextChannelsByName("awesome channel name", true); // Get the list of channels in the guild that matches that name.
for (TextChannel channel : channels) { // Loops through the channels and sends a message to each one.
channel.sendMessage("New member joined: " + user).queue();
}
}
}

Server-Sent Events using Play 2 Java

I'm trying to implement Server-sent events in the Play 2 framework (version 2.3.9) using Java. I'd like for an event to be sent to the client every time a "Message" entity is saved to the database. The entity should be sent to the client in Json format.
Message message = new Message();
//some code to populate bean here
message.save(); //save to db
//What do I do with message here?
I was thinking of making a service class that will send events.
public class SSEService {
public static void sendEvent(String data, String id, String name){
EventSource eventSource = new EventSource() {
#Override
public void onConnected() {
//no idea what to do here
}
};
EventSource.Event event = new EventSource.Event(data, id, name);
eventSource.send(event);
}
}
I would then call SSEService.sendEvent() after saving the message. Am I on the right track? What does data, id, and name correspond to in the Event constructor?
Can someone provide a good example in Java 7?

SNS aws not working properly

Hello all i wrote an application grabbing photos from facebook. I did that successfully. Now i wrote a notification service using SNS in java. Basically sending out subscription for first time users who log into my application and also when a pictured has been deleted from the repository. My first problem is when i download the pics and user info from facebook, i want to check if its a new user or not. If a new user send out a subscription and if not(basically user exist in mongoDb dont send out email for subscription) but my code keeps sending out email to everyuser. And lastly when a user deletes a photo they get a notification but when i tested it i failed to get an email. Below is my code could someone tell me what im doing wrong.
public class EmailNotifications {
private static final String accessKey = "****************";
private static final String secretAccess ="***********************";
//Notification when user gets info from facebook app for first time.
public static void SignUP(String email, String Topic){
AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(accessKey, secretAccess));
snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
//create a Topic
CreateTopicRequest createTopicRequest = new CreateTopicRequest().withName(Topic);
CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
//subscribes to a topic
SubscribeRequest subscribeRequest = new SubscribeRequest().withTopicArn(createTopicResult.getTopicArn())
.withProtocol("email").withEndpoint(email);
snsClient.subscribe(subscribeRequest);
}
//Notification when photo is deleted
public static void deletePic(String email, String topic, String message){
AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(accessKey,secretAccess));
snsClient.setRegion(Region.getRegion(Regions.US_WEST_1));
CreateTopicRequest create = new CreateTopicRequest(topic);
CreateTopicResult result = snsClient.createTopic(create);
System.out.println(result);
//String msg = "My text published to SNS topic with email endpoint";
PublishRequest publishRequest = new PublishRequest(result.getTopicArn(), message);
publishRequest.setSubject("Deleted Pic");
/*PublishResult pu= */snsClient.publish(publishRequest);
}
}
Below is my implementation of both delete and grabbing data for first assuming mongodb is empty:
Delete photo implementation:
#Override
//deletes photo from mongoDB... but doesn't send out an email stating phootid
public String deletePhoto(String id, String PhotoId){
String mssg="";
if(accountRepo.exists(id)){
UserAccounts userAccounts=accountRepo.findById(id);
UserPhotos photos = photoRepo.findByPhotoId(PhotoId);
mssg="The picture "+photos.getPhotoId()+" has been deleted from the application";
EmailNotifications.deletePic(userAccounts.getEmail(),topic,mssg);
photoRepo.delete(PhotoId);
return "Photo is deleted";
}
else
return "Photo does not exist";
}
Grabbing photo from face for the first time. The user should get only one notification max. But i keep getting several messages.
#Override
public UserAccounts create(FacebookClient facebookClient){
User me = facebookClient.fetchObject("me", User.class);
UserAccounts userAccounts = new UserAccounts();
userAccounts.setEmail(me.getEmail());
userAccounts.setGender(me.getGender());
userAccounts.setId(me.getId());
userAccounts.setName(me.getName());
accountRepo.save(userAccounts);
EmailNotifications.SignUP(me.getEmail(), topic);
return userAccounts;
}
Could some one assist me on this
Judging by your description and the code, it would guess the email you keep getting when you download for a user is the subscription confirmation email because all EmailNotifications.SignUp does is subscribe the email address.
I would guess that the reason you haven't getting any email when you delete a picture is because you haven't confirmed the subscription. In the subscription confirmation emails, there should be a link you can click on to confirm the subscription.
As for why you keep getting the email every time you download, I can't tell from your code, but in the create method you show there is not if block around calling SignUp to check if the user already existed, which I imagine is your problem.
As an aside, if your application is interacting with users and you want a good email experience, you would probably be better off using SES, which allows you to completely control the formatting and branding of your email.

JADE agent data communication

In my agent program(using jade), I have 5 agents, in which one agent is a coordinator others are device agents. All 4 device agents send a array to coordinator.
I want coordinator to receive all 4 arrays and store them as single array. How can I do it?
I send messages via ACLmessage(strings)
You should send your arrays in the 4 messages with msg.setContentObject((Serializable)yourObject)
At the reception :
do a cast : yourLocalObject=(yourObjectType) msg.getContentObject();
Then globalarray.merge(yourLocalObject)
I suggest using jade.proto.AchieveREInitiator behaviour by the Coordinator. This allows for a simple conversation with multiple responders.
The responders, your 4 device agents will respond with jade.proto.AchieveREResponder behiours.
The code should look alil something like this on the Coordinator side
class CoordinatorRequestService extends AchieveREInitiator
{
String agentName;
String Service;
public CoordinatorRequestService (Agent a, ACLMessage msg,String Service ,String agentLocalID) {
super(a, msg);
// TODO Auto-generated constructor stub
this.agentName=agentLocalID;
this.Service=Service;
}
protected Vector prepareRequests(ACLMessage predefinedRequest)
{
ACLMessage requestmsg=new ACLMessage(ACLMessage.REQUEST);
requestmsg.addreciever(//add your agents here)
requestMsgVector.add(requestmsg);
return requestMsgVector;
}
protected void handleInform(ACLMessage inform)
{
recieveData=inform.extractDataRecieved();
globalarray.append(recieveData)
}
Google to find more examples of Contract net and achieve communication.
Goodluck

Java ssh client

I'm trying to create a web app which will check several service status, server stats etc. I found this http://www.jcraft.com/jsch/ seems to be pretty nice ssh java implementation. But every time I log in in to server I'm prompted to confirm RSA key fingerprint like this :
How can I override this, to always confirm yes without any prompts? I want to remove the whole swing part, I want to make this without any interaction, like this example code I took from the examples available on jscraft.com :
http://www.jcraft.com/jsch/examples/Exec.java
I'm not so familiar with swing and with java in general.
public class ManoUserInfo implements UserInfo {
String passwd;
public void setPassword(String pass) {
passwd = pass;
}
#Override
public String getPassphrase() {
return null;
}
public String getPassword() {
return passwd;
}
public boolean promptPassword(String arg0) {
return true;
}
public boolean promptPassphrase(String arg0) {
return true;
}
//this method responsible for that message, so just make it return true
public boolean promptYesNo(String arg0) {
// Object[] options = {"yes", "no"};
/* int foo = JOptionPane.showOptionDialog(null,
arg0,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);*/
return true;
}
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
You have to understand why this message pops up.
SSH is a secure service, meaning that the identity of the client and the identity of the server are guaranteed. To guarantee that you actually reached the server you want to reach (for how it is possible that you connect to the wrong server without your knowledge, google "DNS cache poisoning"), the client displays the recieved server name and fingerprint. These values identify the server. You are supposed to look if this is in fact the fingerprint you generated on the server by comparing the fingerprint through a secure channel (via telephone with the server admin, for instance).
Having said that, usual SSH clients save your decision to accept the fingerprint/server name and do not ask again. It seems that your client does not. So you either have the option to change the source code (if it's licensed under an open license) or find a way to automatically press "Yes" whenever this question pops up (this can be achieved with toolkits like Autoit 3 with a very short script).
check out http://sourceforge.net/projects/sshtools/

Categories

Resources