rampatra / jbot

Make Slack and Facebook Bots in Java.
GNU General Public License v3.0
1.2k stars 352 forks source link

How to upload a mp3 File #179

Closed MOEVR closed 4 years ago

MOEVR commented 4 years ago

I want to upload files like mp3, but i cann't find the function in JBot code, can anyone help me plz

Lionelsy commented 4 years ago

LoL. Just like the issue166. You can try the steps in the following: First, replace the code:

   /**
 * Invoked when the bot receives a direct mention (@botname: message) or a
 * direct message. NOTE: These two event types are added by jbot to make your
 * task easier, Slack doesn't have any direct way to determine these type of
 * events.
 *
 * @param session
 * @param event
 */
@Controller(events = { EventType.DIRECT_MENTION, EventType.DIRECT_MESSAGE })
public void onReceiveDM(WebSocketSession session, Event event) {
    if (event.getText().contains("music")) {
        try {
            postFileToSlack(session, event);
        } catch (Exception e) {
            ;
        }
    } else {
        reply(session, event, "Hi, I am " + slackService.getCurrentUser().getName());
    }
}

/**
 * Invoked when bot receives an event of type DIRECT_MENTION or DIRECT_MESSAGE
 * with text containing "music"
 *
 * @param session: The seesion between slack and jbot
 * @param event:   including the main message prefer to send
 */
public void postFileToSlack(WebSocketSession session, Event event) throws IOException {
    File file = new File("Wait.mp3");
    okhttp3.Response response = new Meteoroid.Builder().token(slackToken).channels(event.getChannelId())
            .uploadFile(file).build().post();
    reply(session, event, "Enjoy the music!");
    response.close();
}

in SlackBot.java

Here you need to install the okhttp3 and Meteoroid, (For Convenience), i just download the Meteoroid.java to the same directory of SlackBot.java

You can add more check or operations to send different files.

The result as shown: (Here due to the bandwidth in my server. So it seems slow.)

Screen Shot 2020-05-31 at 18 25 14
MOEVR commented 4 years ago

Get it, thank you a lot