GuildMemberJoin PN Message - java

Hey I want to send a welcome message to new people.
This is my Code. Im very new at Java please help me to get this feature working:
package de.backxtar.listener;
import java.time.OffsetDateTime;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class JoinListener extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Member member = event.getMember();
if((event.getGuild().getDefaultChannel()) != null) {
EmbedBuilder builder = new EmbedBuilder();
builder.setColor(0xf22613);
builder.setThumbnail("http://image.png");
builder.setTitle("Willkommen auf Da Hood!");
builder.setFooter("Powered by Backxtar.");
builder.setTimestamp(OffsetDateTime.now());
builder.setDescription("Herzlich willkommen" + member.getAsMention() + "auf **Da Hood**!\n"
+ "[**Da Hood - The Best Gaming-Discord!**](https://xyz.gg)");
member.getUser().openPrivateChannel().queue((ch) -> {
ch.sendMessage(builder.build()).queue();
});
}
}
}
How does this funktion to be? if((event.getGuild().getDefaultChannel()) != null) {
Thanks!!

first of all, event.getGuild().getDefaultChannel() returns you the channel set for "System Messages Channel" in the server settings, or if none is set there, the first text channel on the Discord Server.
Secondly, unfortunately I cannot tell you why your code does not work because it works perfectly for me, maybe it could be because your Discord server does not have TextChannel if that is the case try if your code works when you create a TextChannel on your Discord server.

Related

Discord bot - JDAs Event Listener sending mutiple messages

I'm creating a discord bot with JDA but I'm a newbie, right now my bot is working, but it's sending multiple messages, I think it's sending one more every time I run the code, I think it's something about the event listener, but not sure and don't know how to solve it, could someone help me with this? thank you.
This is my main file:
package en.devck.dc;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Activity.ActivityType;
public class devck {
public static JDA jda;
public static String prefix = "*";
// Main method
public static void main(String[] args) throws LoginException {
jda = JDABuilder.createDefault("my token").build();
jda.getPresence().setStatus(OnlineStatus.ONLINE);
Activity act = Activity.of(ActivityType.WATCHING, "Cowboy Bebop");
jda.getPresence().setActivity(act);
Commands cmd = new Commands();
jda.addEventListener(cmd);
}
}
this is my commands file:
package en.devck.dc;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Commands extends ListenerAdapter{
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
if(args[0].startsWith(devck.prefix)) {
args[0] = args[0].substring(1);
switch (args[0]) {
case "info":
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage("Hey there! There is a new bot over here").queue();
break;
case "greet":
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage(event.getAuthor().getName()+" is sending greetings to "+args[1]).queue();
break;
default:
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage("I did not understand your command... but I'm learning!").queue();
break;
}
}
}
}
When I type "*info" it says something like:
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
"Hey there! There is a new bot over here"
Depending on your IDE, you might have to stop the java application running.
Eclipse:
Top bar -> Debugging/Run tools -> Red Square (This might have a number showing how many instances are running at the same time)
Intellij:
How to prevent multiple bots running at the same time (Intellij Only):
Disable the "Allow Multiple Instances" in your run options.

Is there an implemented function in Bukkit / Spigot MC (Java) that lets me get a players ping to the server? [duplicate]

This question already has an answer here:
How to get player's ping in spigot 1.16.4
(1 answer)
Closed 2 years ago.
I'm currently trying to code a Minecraft plugin for a server that a Streamer friend of mine wants to run. What I need is the following:
I need a function or method that lets me get the players ping towards the server. So that the player types /ping into the chatbox and gets a response from the server that looks something like [Server]: Your current Ping is 62ms.
I've looked in Bukkit documentation like http://docs.codelanx.com/Bukkit/1.7.10/ or http://bukkit.luricos.de/api/1.7.9-R0.2/, but I couldn't find something that fits my needs.
My Plugin.yml:
name: Beginning
version: ${project.version}
main: de.nightcore.beginning.Main
api-version: 1.16
commands:
date:
description: Shows the current time and Date
ping:
description: Gives the Player its current ping to the server
My Main Class:
package de.nightcore.beginning;
import de.nightcore.beginning.commands.DateCommand;
import de.nightcore.beginning.commands.PingCommand;
import de.nightcore.beginning.listeners.JoinListener;
import de.nightcore.beginning.listeners.QuitListener;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public final class Main extends JavaPlugin {
#Override
public void onEnable()
{
Bukkit.getLogger().fine("Plugin wird geladen!");
listenerRegistration();
commandRegistration();
}
#Override
public void onDisable()
{
Bukkit.getLogger().fine("Plugin wird beendet!");
}
public static String getPrefix()
{
return ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "Server" + ChatColor.DARK_GRAY + "] " + ChatColor.WHITE;
}
private void listenerRegistration()
{
PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new JoinListener(), this);
pluginManager.registerEvents(new QuitListener(), this);
}
private void commandRegistration()
{
getCommand("date").setExecutor(new DateCommand());
getCommand("ping").setExecutor(new PingCommand());
}
}
And finally my PingCommand Class:
package de.nightcore.beginning.commands;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
//TODO: Ping Command / Command that provides Connection Info
public class PingCommand implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
Player player = sender.getServer().getPlayer("%UUID%"); ;
Server server = sender.getServer();
//Source Code to provide information about the players current ping
return false;
}
}
You need to cast Player to CraftPlayer, after that get the EntityPlayer with CraftPlayer#getHandler(), where you can return the player ping as int value.
((CraftPlayer) player).getHandle().ping;
You also need to add the spigot dependency (the API doesn't seem to include it).
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>LATEST</version>
<scope>provided</scope>
</dependency>

How to integrate karate with testrail

I am new to Java and using karate for API automation. I need help to integrate testrail with karate. I want to use tags for each scenario which will be the test case id (from testrail) and I want to push the result 'after the scenario'.
Can someone guide me on this? Code snippets would be more appreciated. Thank you!
I spent a lot of effort for this.
That's how I implement. Maybe you can follow it.
First of all, you should download the APIClient.java and APIException.java files from the link below.
TestrailApi in github
Then you need to add these files to the following path in your project.
For example: YourProjectFolder/src/main/java/testrails/
In your karate-config.js file, after each test, you can send your case tags, test results and error messages to the BaseTest.java file, which I will talk about shortly.
karate-config.js file
function fn() {
var config = {
baseUrl: 'http://111.111.1.111:11111',
};
karate.configure('afterScenario', () => {
try{
const BaseTestClass = Java.type('features.BaseTest');
BaseTestClass.sendScenarioResults(karate.scenario.failed,
karate.scenario.tags, karate.info.errorMessage);
}catch(error) {
console.log(error)
}
});
return config;
}
Please dont forget give tag to scenario in Feature file.
For example #1111
Feature: ExampleFeature
Background:
* def conf = call read('../karate-config.js')
* url conf.baseUrl
#1111
Scenario: Example
Next, create a runner file named BaseTests.java
BaseTest.java file
package features;
import com.intuit.karate.junit5.Karate;
import net.minidev.json.JSONObject;
import org.junit.jupiter.api.BeforeAll;
import testrails.APIClient;
import testrails.APIException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class BaseTest {
private static APIClient client = null;
private static String runID = null;
#BeforeAll
public static void beforeClass() throws Exception {
String fileName = System.getProperty("karate.options");
//Login to API
client = new APIClient("Write Your host, for example
https://yourcompanyname.testrail.io/");
client.setUser("user.name#companyname.com");
client.setPassword("password");
//Create Test Run
Map data = new HashMap();
data.put("suite_id", "Write Your Project SuitId(Only number)");
data.put("name", "Api Test Run");
data.put("description", "Karate Architect Regression Running");
JSONObject c = (JSONObject) client.sendPost("add_run/" +
TESTRAİL_PROJECT_ID, data);
runID = c.getAsString("id");
}
//Send Scenario Result to Testrail
public static void sendScenarioResults(boolean failed, List<String> tags, String errorMessage) {
try {
Map data = new HashMap();
data.put("status_id", failed ? 5 : 1);
data.put("comment", errorMessage);
client.sendPost("add_result_for_case/" + runID + "/" + tags.get(0),
data);
} catch (IOException e) {
e.printStackTrace();
} catch (APIException e) {
e.printStackTrace();
}
}
#Karate.Test
Karate ExampleFeatureRun() {
return Karate.run("ExampleFeatureRun").relativeTo(getClass());
}
}
Please look at 'hooks' documented here: https://github.com/intuit/karate#hooks
And there is an example with code over here: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/hooks/hooks.feature
I'm sorry I can't help you with how to push data to testrail, but it may be as simple as an HTTP request. And guess what Karate is famous for :)
Note that values of tags can be accessed within a test, here is the doc for karate.tagValues (with link to example): https://github.com/intuit/karate#the-karate-object
Note that you need to be on the 0.7.0 version, right now 0.7.0.RC8 is available.
Edit - also see: https://stackoverflow.com/a/54527955/143475

how to bypass lotus notes password log in - JAVA code

My code works great so far, except for one part which I need to bypass somehow because this is going to be an autosys job. That one part is logging in to lotus notes (when I'm logged in and the app is still running); every time my script runs it requires the user to input his password. I've tried code to log in to my account but it still didn't work for me, so I was wondering what am I missing? Any help would be greatly appreciated! My code is below. It is very close to being finished. The popup is the only issue I have; the code below is compilable and runs just fine so far.
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.Session;
import javax.mail.internet.*;
import javax.swing.JOptionPane;
import javax.activation.*;
import lotus.domino.*;
import lotus.notes.addins.util.DominoAddressBook;
public class SendEmail extends NotesThread {
#SuppressWarnings("deprecation")
public static void main(String [] args) throws AddressException, MessagingException {
// runs the program, mainly runNotes()
SendEmail e = new SendEmail();
e.start();
//e.sendMail();
}
public void runNotes() {
try {
// TODO: pop's up dialog box for user password to be input if password is in line 32 else its line 59
// might be because I'm creating a new session each time the program is run?
// this lets you retype the password as many times as you want until you got it correct (no password in argument, line 32)
lotus.domino.Session s = NotesFactory.createSessionWithFullAccess();
// configures so the password entered in the dialog box matches the password here (security check user)
// lotus.domino.Session s = NotesFactory.createSession((String)null, "userID", "pass!");
String p = s.getPlatform();
System.out.println("Platform: " + p);
System.out.println("Username: " + s.getUserName());
System.out.println("Server name: " + s.getServerName());
// self explantory, set's up the email with the message, attachment, etc
Database db = s.getDatabase(null, "C:\\Program Files (x86)\\IBM\\Lotus\\Notes\\Data\\names.nsf");
Document doc = db.createDocument();
doc.setSaveMessageOnSend(true);
RichTextItem attachedFile = doc.createRichTextItem("Attachment");
attachedFile.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "G-Man", "C:\\Users\\F400318\\Desktop\\testDB2.xlsx", "testDB");
StringBuilder body = new StringBuilder();
body.append("This email is a test!");
doc.appendItemValue("\n\n");
doc.appendItemValue("Body", body.toString());
doc.appendItemValue("Subject", "Test E-Mail");
doc.appendItemValue("Sent", "user#emailcompany.com");
doc.send("user#emailcompany.com");
System.out.println("Check email... it should have been sent");
} catch (Exception e) {
e.printStackTrace();
}
}
Where is your code running? On a Domino server, from a Notes client, or outside of Notes/Domino entirely?
The createSessionWithFullAccess() method assumes the code is running on the server and it will prompt for the password when needed unless you pass the password as an argument createSessionWithFullAccess("password").
http://www-12.lotus.com/ldd/doc/domino_notes/rnext/help6_designer.nsf/b3266a3c17f9bb7085256b870069c0a9/5a8f8afb89d617f785256c54004d9eb4?OpenDocument
* Edit *
From the looks of your code, you're trying to create a Swing application with JOptionPane, so using createSessionWithFullAccess() isn't necessary from the Notes client. You could just use NotesFactory.createSession() and it will use the users's Notes ID for credentials. Another option you could consider is if you're calling your code from a Notes agent, then you could pass the Session created by the agent to your code instead of creating a new one.

Having trouble connecting android with MQTT to broker

I am trying to connect to an Apollo broker, this code works perfectly when I use it alone in a normal java project, everything is exactly the the same except now its in an android project and i try to run it when i click a button from MainActivity.
I have a text box that gets updated to "1" before i try to connect MQttClient however the second .setT("2") does not get run so I think the problem is with client.connect(opts) as if i just do client.connect() the text box gets updated to "2" but since i need the username and password it from opts the rest does not run
Just started using MQTT learning as I go along. Thanks for any help.
package com.example.androidmqtt;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;
public class Service {
MqttClient client;
MemoryPersistence persistence = new MemoryPersistence();
public Service()throws Exception{}
public static void main(String[] args) throws Exception {
new Service().doDemo();
}
public void doDemo() {
try {
client = new MqttClient("tcp://10.1.10.1:1883", "testingMyMQTT", persistence);
MainActivity.setT("2");
MqttConnectOptions opts = new MqttConnectOptions();
opts.setUserName("nabi");
opts.setPassword("M4rk3".toCharArray());
opts.setKeepAliveInterval(480);
MainActivity.setT("1");//sets the txt1 in main view to 1 so i know whats going on
client.connect(opts);
MainActivity.setT("2");
MqttMessage msg = new MqttMessage("Works".getBytes());
msg.setRetained(true);
msg.setQos(1);
MainActivity.setT("its working");
MqttTopic topic = client.getTopic("Android/Test");
MqttDeliveryToken token = topic.publish(msg);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Verify that android can connect to your local network 10.1.10.1 and if so, check the logs of the Apollo broker.

Categories