I want to make a discord bot, that when the user types -m skelt a picture will be shown from the bot. Here is what I got so far: Can somone please help me. Thanks!
package lairex59.Commands;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import lairex59.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Comment extends ListenerAdapter
{
public void onGuildMessageReceived(GuildMessageReceivedEvent event){
String[] args = event.getMessage().getContentRaw().split("\\s+");
if (args[0].equalsIgnoreCase(Main.prefix + "help")) {
EmbedBuilder info = new EmbedBuilder();
info.setTitle(":among_us_lime:Among Us help cnter");
info.setDescription("Among Us code center :office:");
info.setColor(0xf45642);
info.setFooter("Created by Laraib", event.getMember().getUser().getAvatarUrl());
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage(info.build()).queue();
info.clear();
}
if ((args[0].equalsIgnoreCase(Main.prefix + "m")) && (args[1].equalsIgnoreCase("polus"))) {
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage("Polus file").queue();
}
if (args[0].equalsIgnoreCase(Main.prefix + "m") && (args[1].equalsIgnoreCase("mira"))) {
event.getChannel().sendTyping().queue();
event.getChannel().sendMessage("Mira file").queue();
}
if (args[0].equalsIgnoreCase(Main.prefix + "m") && (args[1].equalsIgnoreCase("skelt"))) {
event.getChannel().sendTyping().queue();
BufferedImage image = null;
File f = null;
try {
f = new File ("D:\\Laraib\\Images\\Skelt.jpg");
image = ImageIO.read(f);
}
catch(IOException e) {
System.out.println("Error"+e);
}
try {
f = new File ("D:\\Laraib\\Images\\Skelt.jpg");
ImageIO.write(image, "jpg", f);
}
catch (IOException e) {
System.out.println("Error"+e);
}
}
}
}
I managed to read the file but don't know how i can tell the bot to send an image. Every help is needed. Thanks!
Discord does not ask to specify if the file sent is an image or something else, it just sends the file, it is the client who, from the file extension, will display the image as an image, so your BufferedImage is useless.
So, to send your image, it's just plain silly:
The MessageAction interface you have a method MessageAction#addFile(File)
All you have to do is to call this method, and to send all this to the wrong person (like the queue method for example).
File file = new File("path");
if (Objects.nonNull(file)) {
event.getChannel().sendMessage("Here is my image !").addFile(file).queue();
} else {
event.getChannel().sendMessage("Sorry, I can't found the image :c").queue();
}
Here's the java doc : https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/requests/restaction/MessageAction.html
EDIT:
Or, as #minn reminded me, you don't have to add the file in the MessageAction but you can directly send the file without additional content with the method MessageChannel#sendFile(file).
Here's the doc: https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/entities/MessageChannel.html
Related
The code is as follows:
package volmbot.commands;
import lombok.SneakyThrows;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SandBox extends ListenerAdapter {
#SneakyThrows
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String[] args = e.getMessage().getContentRaw().split(" ");
e.getMessage().getAttachments();
String authId = e.getMessage().getAuthor().getId();
//Grab file and save it as the user's ID
FileOutputStream saveFile = new FileOutputStream(authId + ".txt");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(e.getMessage().getAttachments());
save.close();
}
}
My goal is to do the following:
Save the file that the user sent in a message (if the message has an attachment)
Ignore it if the message does not contain a message
Save to a file with the user's ID as id.txt
I've tried using a Filestream, but I might be doing something wrong.
How would I manage so grab the messages attachment, assuming it has an attachment, then save the file?
You can use downloadToFile(name):
List<Message.Attachment> attachments = event.getMessage().getAttachments();
if (attachments.isEmpty()) return; // no attachments on the message!
CompletableFuture<File> future = attachments.get(0).downloadToFile(authId + ".txt");
future.exceptionally(error -> { // handle possible errors
error.printStackTrace();
return null;
});
Some years ago I took a couple of courses in programming. Now I'm in a situation where some very basic image processing might save me loads of time. Unfortunately I'm a bit stuck trying to read an image. I haven't done this before and basically just copied some code I found, but I get "javax.imageio.IIOException: Can't read input file!". I've tried moving the image "Test.jpg" and change the path. I don't understand what is causing the issue. I use macOS, not sure if this is relevant.
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class MyImage{
public static void main(String args[])throws IOException{
BufferedImage image = null;
File f = null;
try {
f = new File("Users/simonprobert/eclipse-workspace/LineLengthCounter/src/Test.jpg");
image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
image = ImageIO.read(f);
System.out.println("Reading complete.");
} catch(IOException e){
System.out.println("Error: "+e);
}
}
}
(Currently I'm just trying to read the image, the rest is not important at this point)
I am trying to upload a file into Azure Blob.
and I am trying to achieve through Upload in vaadin framework. Vaadin Version : 6.7.8
I am able to develop a code for uploading the file into azure blob.
My Problem Statement Lies below :
I have written a class UploadToBlob.java to upload a file into azure blob.
If I run the class UploadToBlob.java indivually (ran from eclipse run as java application), I am able to upload the file into azure blob.
If I create a object of the UploadToBlob class in my other class[ModifyComplaintComponent.java], storageAccount = CloudStorageAccount.parse(storageConnectionString); is not getting execute.
Below is the UploadToBlob.java code:
package com.---.trs.scms.ui.components;
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.StorageCredentials;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
public class UploadToBlob {
public static void main(String[] args) {
try {
final String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=abcd;AccountKey=bmiA7+****==;EndpointSuffix=core.windows.net";
System.out.println("---I am getting called Main-1 ");
CloudStorageAccount storageAccount;
storageAccount = CloudStorageAccount.parse(storageConnectionString);
com.microsoft.azure.storage.blob.CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient.getContainerReference("container2");
container.createIfNotExists();
String filePath = "C:\\Users\\----\\Desktop\\Timesheet - 19th Aug,2019.pdf";
com.microsoft.azure.storage.blob.CloudBlockBlob blob = container.getBlockBlobReference("Timesheet.pdf");
java.io.File source = new java.io.File(filePath);
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(source);
blob.upload(fileInputStream, source.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}
For now , I am passing manual file PATH as above to upload in azure blob, as I told above , this class is getting called till the line of code System.out.println("---I am getting called Main-1 ");
Here is the ModifyComplaintComponent code from where I am calling UploadToBlob.java:
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Upload;
public class ModifyComplaintComponent extends CustomComponent {
//other component code which I haven't pasted here
private Upload uploadnew;
try {
System.out.println("------Inside try block-----------");
UploadToBlob fileReceiver= new UploadToBlob ();
uploadnew = new Upload("Upload a file", fileReceiver);
uploadnew.setReceiver(fileReceiver);
uploadnew.addListener(fileReceiver);
System.out.println("------end of try block-----------");
} catch (Exception e) {
System.out.println("------catch block-----------");
e.printStackTrace();
}
HorizontalLayout hlayout = new HorizontalLayout();
hlayout.setSpacing(true);
hlayout.addComponent(uploadnew);
}
The Reason why I have given a manual file path in my UploadToBlob code is because I firstly wanted to make this code called from ModifyComplaintComponent class.
Secondly when I try to browse the file , and file gets selected but when I click on upload , I get NullPointerException On Vaadin Upload UI Part and even if i selected the file , UI says "no file choosen"
The challenge I am facing is If I run the Upload.java file individually I am able to upload static file into azure blob , but I wanted to browse and upload a file in vaadin framework into azure blob storage.
Firstly, Upload is a Component of Vaadin. You should not create your own Upload class.
Secondly, the public static main method is an entrance where your program starts. If you want to use a method of a class, you need to explicitly invoke it.
TheClassName.MethodName(...) // For static method
new TheClassName(...).MethodName(...) //For non-static method
Thirdly, I did some tests, the following is a successful sample. Two classes will be created:
Class UploadReceiver
This class implements the Receiver interface and some listeners.
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.vaadin.ui.Upload;
import org.springframework.stereotype.Component;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
#Component
public class UploadReceiver implements Upload.Receiver, Upload.StartedListener, Upload.SucceededListener, Upload.ProgressListener {
// Storage account connection string.
public static String conn = "DefaultEndpointsProtocol=https;AccountName=stora***789;AccountKey=G3***w==;EndpointSuffix=core.windows.net";
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
System.out.println("Uploading -> " + mimeType + " ; File name -> " + filename);
return GetOutputStream("vaadin",filename);
}
#Override
public void uploadStarted(Upload.StartedEvent startedEvent) {
System.out.println("Upload started!");
}
#Override
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
System.out.println("Upload succeeded!");
}
public OutputStream GetOutputStream(String container, String blob){
OutputStream outputStream = null;
try{
CloudStorageAccount storageAccount = CloudStorageAccount.parse(conn);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.getContainerReference(container);
CloudBlockBlob cloudBlockBlob = blobContainer.getBlockBlobReference(blob);
outputStream = cloudBlockBlob.openOutputStream();
} catch (StorageException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return outputStream;
}
#Override
public void updateProgress(long readBytes, long contentLength) {
System.out.println("Progress: readBytes -> " + readBytes + " ; contentLength -> " + contentLength);
}
}
Class MainUI
This is the UI page. I just add an upload component.
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.UI;
import com.vaadin.ui.Upload;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.factory.annotation.Autowired;
#SpringUI
public class MainUI extends UI {
private VerticalLayout layout;
private Upload upload;
private UploadReceiver uploadReceiver;
#Autowired
public MainUI(UploadReceiver uploadReceiver){
this.uploadReceiver = uploadReceiver;
}
#Override
protected void init(VaadinRequest vaadinRequest) {
// Set layout
layout = new VerticalLayout();
layout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);
setContent(layout);
// Add upload
upload = new Upload("Upload a file", uploadReceiver);
upload.addStartedListener(uploadReceiver);
upload.addSucceededListener(uploadReceiver);
upload.addProgressListener(uploadReceiver);
layout.addComponent(upload);
}
}
Result:
After I clicked the upload button and chose a file to upload, I could get the following outputs from console:
And, by checking the storage account with Storage Explorer, I could see that the file was successfully uploaded:
Update:
This is how the upload works:
I do not know how your code passed the compiling. To construct an Upload object, you need to pass a caption string and a receiver which implements Upload.Receiver interface.
public Upload(String caption, Receiver uploadReceiver)
And to implement the Upload.Receiver interface, you have to override the receiveUpload method.
OutputStream receiveUpload(String filename, String mimeType)
The receiveUpload will return an output stream, where vaadin will finally write contents to.
That's all. Give vaadin an output stream, and it will write all the contents to the stream.
The input file is sent from your browser and handled by vaadin. I did not find a way to manually set the input content in vaadin. Sorry.
How do I get the images I stored in my web pages folder out so I can read them into a buffered image?
I found many explanations online on how it works but it's so confusing!
Maybe someone could help me by explaining it to me in a scenario familiar to me?
This is my server folder tree:
I want to read PNG pictures from images in Web Pages from within my ItemStorage class.
Here's what that class looks like:
import java.util.ArrayList;
import java.util.List;
import be.pxl.minecraft.model.Item;
import com.sun.jersey.spi.resource.Singleton;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Singleton
public class ItemStorage {
private ImageStorage test;
private HashMap<String, Image> categories;
private HashMap<String, BufferedImage> images;
private List<Item> recipesList;
public ItemStorage() {
File directory = new File("/images");
if (directory.isDirectory()) { //FILE PATH NOT A DIRECTORY
BufferedImage img = null;
for (File f : directory.listFiles()) {
try {
img = ImageIO.read(f);
images.put(f.getName(), img);
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
}
}
}
recipesList = new ArrayList<Item>();
//BufferedImage air = getImage("air"); //TRIED DIFFERENT APPROACH, SEE getImage()
//Armor
recipesList.add(new Item(7, 2, getImage("diamond_boots"), "Boots (Diamond)",
"0,0,0,1,0,1,1,0,1", String.format("%d,%d", getImage("air"), R.drawable.diamond_ingot )));
}
public void setItems(List<Item> list) {
recipesList = list;
}
public List<Item> getItems() {
return recipesList;
}
#Path("/images")
#Produces("image/png")
public Response getImage(String imageName) { //TRYING TO HTTP TO THE IMAGE
BufferedImage img = null;
try {
File imageFile = new File(imageName + ".png");
img = ImageIO.read(imageFile);
return Response.ok(img).build();
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
} finally {
return Response.ok(img).build();
}
}
}
As you can see, I tried to call the images both through HTTP and a simple IO directory.
This is a restful server running under tomcat 7.0.41.0
Please collaborate.
what puzzles me with your approach is, that you access a file from within your service, that is supposed to be located at the "root" ("/") directory. This is not inside your application.
In the rest service, there is no "context", as you have it in the servlet world. You need to identify the images folder somehow using a config option. You can also check the documentation of your REST server to see how to access the MessageContext and HTTPRequest. Then you can use them to access your web-application's runtime folder and access the images.
Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.