I'm learning jda and I coded my discord bot so that console send the message that I sent, but after executing this code, I send a random message in my test discord server, the console just prints nothing. Is anything wrong with my code? I also tried e.getMessage().getContentRaw(), but it returns same result.
Main Class
package net.lib.first;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Message;
import net.lib.first.event.Listener;
import javax.security.auth.login.LoginException;
public class Main {
public static void main(String[] args) throws LoginException {
String token = (my bot token);
JDABuilder builder = JDABuilder.createDefault(token);
builder.addEventListeners(new Listener());
builder.setActivity(Activity.playing("Type !ping"));
builder.build();
Message.suppressContentIntentWarning();
}
}
Listener Class
package net.lib.first.event;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class Listener extends ListenerAdapter {
#Override
public void onMessageReceived(#NotNull MessageReceivedEvent e) {
System.out.println(e.getMessage().getContentDisplay());
}
}
Solved the problem, I didn't add the method enableIntents(GatewayIntent.MESSAGE_CONTENT) to builder.
I have the same problem, but there is no option to enable GatewayIntent.MESSAGE_CONTENT
only:
[...]
builder.createDefault("xxx")
.setActivity(Activity.playing("!help") )
.setStatus(OnlineStatus.ONLINE)
.addEventListeners(new CommandListener() )
.addEventListeners(new VoiceListener() )
.enableIntents(GatewayIntent.GUILD_MESSAGES)
.enableIntents(GatewayIntent.DIRECT_MESSAGES)
.build();
[...]
I have enabled the above ones.
Related
So Basically I have been searching the internet for a way to add potion effects while an item is being held. I have found many results but none really seem to be working. My main issue is that when I get to the adding potion effect it throws errors because I am trying to use a non-static to access an abstract. I tried the #Overide several times but it never seems to work. I still need to register in forge as that is how it updates but adding PlayerEntity does not work when I use #SubscribeEvent
package blitz.weapon.weaponmod;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.MainWindow;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerAbilities;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.stream.Collectors;
// The value here should match an entry in the META-INF/mods.toml file
#Mod("weaponmod")
public class Weaponmod {
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "weaponmod");
public static final RegistryObject<Item> RAINBOW_SWORD = ITEMS.register("rainbow_sword", () ->
new Item(new Item.Properties()
.group(ItemGroup.COMBAT)
.maxStackSize(1)
.maxDamage(13)
));
public Weaponmod() {
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register the enqueueIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
// Register the processIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
// Register the doClientStuff method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
}
#SubscribeEvent
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.side.isServer() && event.phase == TickEvent.Phase.START) {
ItemStack stack = event.player.getHeldItemMainhand();
if (stack != null && stack.getItem() !=null) {
if (stack.getItem().equals("1 rainbow_sword")) {
return;
}
}
}
}
private void setup(final FMLCommonSetupEvent event) {
// some preinit code
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
}
private void doClientStuff(final FMLClientSetupEvent event) {
// do something that can only be done on the client
LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().gameSettings);
}
private void enqueueIMC(final InterModEnqueueEvent event) {
// some example code to dispatch IMC to another mod
InterModComms.sendTo("weaponmod", "helloworld", () -> {
LOGGER.info("Hello world from the MDK");
return "Hello world";
});
}
private void processIMC(final InterModProcessEvent event) {
// some example code to receive and process InterModComms from other mods
LOGGER.info("Got IMC {}", event.getIMCStream().
map(m -> m.getMessageSupplier().get()).
collect(Collectors.toList()));
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
#SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
// do something when the server starts
LOGGER.info("HELLO from server starting");
}
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
#Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
// register a new block here
LOGGER.info("HELLO from Register Block");
}
}
}
That is my code for basically my whole mod, can anyone give me any pointers? (Sorry for any mistakes this is my first post)
I have this problem with Discord JDA, and I'm completely frustrated about it. I hope you can help me. The problem is my console won't print a message when a user joins, and I absolutely don't know why it doesn't work.
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Events extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
System.out.println("Ja moin");
/**User user = event.getUser();
Guild guild = event.getGuild();
user.getAsMention();
System.out.println("Der User: " + user + " ist auf den Server: " + guild);**/
}
}
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import de.jonathan.Events;
import javax.security.auth.login.LoginException;
public class Bot extends ListenerAdapter {
public static void main(String[] args) throws LoginException {
JDABuilder builder = new JDABuilder(AccountType.BOT);
String token = "<My Token>";
builder.setActivity(Activity.playing("HARIBOB"));
builder.setStatus(OnlineStatus.DO_NOT_DISTURB);
builder.setToken(token);
builder.build();
// Events
builder.addEventListeners(new Events());
}
}
The solution is / was i needed to enable the Intents on the Discord page. After this I needet to add the line:
.enableIntents(GatewayIntent.GUILD_MEMBERS)
I am using Akka websockets to push data to some client.
This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.http.javadsl.ConnectHttp;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.ws.Message;
import akka.http.javadsl.model.ws.WebSocket;
import akka.japi.Function;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
public class Server {
public static HttpResponse handleRequest(HttpRequest request) {
System.out.println("Handling request to " + request.getUri());
if (request.getUri().path().equals("/greeter")) {
final Flow<Message, Message, NotUsed> greeterFlow = greeterHello();
return WebSocket.handleWebSocketRequestWith(request, greeterFlow);
} else {
return HttpResponse.create().withStatus(404);
}
}
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create();
try {
final Materializer materializer = ActorMaterializer.create(system);
final Function<HttpRequest, HttpResponse> handler = request -> handleRequest(request);
CompletionStage<ServerBinding> serverBindingFuture = Http.get(system).bindAndHandleSync(handler,
ConnectHttp.toHost("localhost", 8080), materializer);
// will throw if binding fails
serverBindingFuture.toCompletableFuture().get(1, TimeUnit.SECONDS);
System.out.println("Press ENTER to stop.");
new BufferedReader(new InputStreamReader(System.in)).readLine();
} finally {
system.terminate();
}
}
public static Flow<Message, Message, NotUsed> greeterHello() {
return Flow.fromSinkAndSource(Sink.ignore(),
Source.single(new akka.http.scaladsl.model.ws.TextMessage.Strict("Hello!")));
}
}
At the client side, I am successfully receiving a 'Hello!' message.
However, now I want to send data dynamically (preferably from an Actor), something like this:
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
public class PushActor extends UntypedActor {
#Override
public void onReceive(Object message) {
if (message instanceof String) {
String statusChangeMessage = (String) message;
// How to push this message to a socket ??
} else {
System.out.println(String.format("'%s':\nReceived unknown message '%s'!", selfActorPath, message));
}
}
}
I am unable to find any example regarding this online.
The following is the software stack being used:
Java 1.8
akka-http 10.0.10
One - not necessarily very elegant - way of doing this is to use Source.actorRef and send the materialized actor somewhere (maybe a router actor?) depending on your requirements.
public static Flow<Message, Message, NotUsed> greeterHello() {
return Flow.fromSinkAndSourceMat(Sink.ignore(),
Source.actorRef(100, OverflowStrategy.fail()),
Keep.right()).mapMaterializedValue( /* send your actorRef to a router? */);
}
Whoever receives the actorRefs of the connected clients must be responsible for routing messages to them.
I've written a Blackjack server in java which starts up fine, but I'm having trouble writing a separate java client to connect to my server. I've followed the Spring Websocket documentation and examples and it looks like my client connects without any errors and I'd expect it to hit the afterConnected() method, but it doesn't get to that point. The client runs and finishes with no errors. Any idea what I'm doing wrong?
WebSocketConfig.java on the server side:
package com.lactaoen.blackjack.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/connect").withSockJS();
}
}
Client side:
package com.lactaoen.blackjack.client;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
import java.util.ArrayList;
import java.util.List;
public class BlackjackClient {
public static void main(String[] args) {
List<Transport> transports = new ArrayList<>();
transports.add(new WebSocketTransport(new StandardWebSocketClient()));
transports.add(new RestTemplateXhrTransport());
SockJsClient sockJsClient = new SockJsClient(transports);
String stompUrl = "ws://localhost:8080/connect";
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
stompClient.setMessageConverter(new StringMessageConverter());
stompClient.connect(stompUrl, new BlackjackSessionHandler());
}
private static class BlackjackSessionHandler extends StompSessionHandlerAdapter {
#Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
// I'd expect it to print this out, but it doesn't get here
System.out.println("Hello, world!");
}
}
}
the main method of the client side is finishing before to connect.
put a Thread.sleep(60000) in the last line of your main method, it's should work
The client will close the connection after communication complete(send or receive), you should block the thread to ensure the application not close.
Add this at the end of main method:
//block the thread
CountDownLatch latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
I am creating a Minecraft mod, and I am getting the error Syntax error on token ";", , expected on this line
public static Block BasaltSmooth;
Here is the code :
package BitBox.Mods.BetterEgg;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
#Mod(modid = "BitBox's Mod", name = "BitBoxMod", version = "V0.1")
#NetworkMod(clientSideRequired = true, serverSideRequired = false)
public class mainClass {
// Initialization
//tabs
public static Item BitBoxTabIcon;
//items
//blocks
public static Block BasaltSmooth;
BasaltSmooth = new BitBoxBlock(500, Material.rock)
.setHardness(0.5F)
.setUnlocalizedName("Basalt Stone")
.setCreativeTab(CreativeTabs.tabBlock);
public static CreativeTabs bitBoxTab;
#EventHandler
public void load(FMLInitializationEvent event) {
LanguageRegistry.addName(BasaltSmooth, "Basalt Stone");
MinecraftForge.setBlockHarvestLevel(BasaltSmooth, "pickaxe", 0);
GameRegistry.registerBlock(BasaltSmooth, "Basalt Stone");
}
public mainClass() {
}
}
You cant do like this
public static Block BasaltSmooth;
BasaltSmooth = new BitBoxBlock(500, Material.rock).setHardness(0.5F).setUnlocalizedName("Basalt
Stone").setCreativeTab(CreativeTabs.tabBlock);
Do like this
public static Block BasaltSmooth = new BitBoxBlock(500, Material.rock).setHardness(0.5F).setUnlocalizedName("Basalt
Stone").setCreativeTab(CreativeTabs.tabBlock);
Prabhakaran's answer should help you with instantiating the Block correctly, Minecraft can be picky at times. Howerever, another issue is that you should register it in the FML PreInit phase:
class{
create block with properties here.
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
Register block with game here
}
}