项目作者: wenewzhang

项目描述 :
java bot for Mixin Network
高级语言: Java
项目地址: git://github.com/wenewzhang/mixin_labs-java-bot.git
创建时间: 2019-01-21T08:29:55Z
项目社区:https://github.com/wenewzhang/mixin_labs-java-bot

开源协议:

下载


Java Bitcoin tutorial based on Mixin Network

cover

A Mixin messenger bot will be created in this tutorial. The bot is powered by Java and echo message and Bitcoin from user.

Full Mixin network resource index

What you will learn from this tutorial

  1. How to create bot in Mixin messenger and reply message to user | Chinese
  2. How to receive Bitcoin and send Bitcoin in Mixin Messenger | Chinese
  3. How to create a Bitcoin wallet based on Mixin Network API | Chinese
  4. How to trade bitcoin through Java: Pay to ExinCore | Chinese
  5. How to trade bitcoin through Java: List your order on Ocean.One | Chinese
  6. How to trade ERC-20 compliant coins on OceanOne through Java | Chinese

Install java on your OS

On macOS, download java jdk from here,double click jdk-11.0.2_osx-x64_bin.dmg, then click on JDK 11.0.2.pkg in popup window, follow the instruction to install java, java could be installed in /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home/bin/ directory, add this path to environment variable $PATH

  1. echo 'export PATH=/Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home/bin/:$PATH' >> ~/.bash_profile
  2. source ~/.bash_profile

Run command java —version to check the installation

  1. wenewzha:mixin_labs-java-bot wenewzhang$ java --version
  2. java 11.0.2 2019-01-15 LTS
  3. Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
  4. Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

on Ubuntu

  1. apt update
  2. apt upgrade
  3. apt install unzip
  4. java --version

On Ubuntu 16.04, the openjdk java has been installed. run command java —version to check installation

  1. root@ubuntu:~# java --version
  2. openjdk 10.0.2 2018-07-17
  3. OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
  4. OpenJDK 64-Bit Server VM (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4, mixed mode)

Install Gradle

This tutorial use Gradle to build whole project. You can download the latest gradle here

macOS

  1. brew update
  2. brew install gradle

Ubuntu: The gradle is too old, we need to update it.

  1. cd ~/Downloads
  2. wget https://services.gradle.org/distributions/gradle-5.1.1-bin.zip
  3. unzip gradle-5.1.1-bin.zip

After unzip the gradle-5.1.1-bin.zip, Add the path to $PATH environment variable

  1. echo 'export PATH=/root/gradle-5.1.1/bin:$PATH' >> ~/.bashrc
  2. source ~/.bashrc

Run gradle -v to check gradle installation

  1. root@ubuntu:~# gradle -v
  2. ------------------------------------------------------------
  3. Gradle 5.1.1
  4. ------------------------------------------------------------
  5. ...

Create your first app in Mixin Network developer dashboard

You need to create an app in dashboard. This tutorial can help you.

Generate parameter of your app in dashboard

After app is created in dashboard, you need to generate parameter
and write down required content, these content will be written into config.java file.

Hello, world in java

Go to your workspace, create the project mixin_labs-java-bot directory by running gradle init.

  1. gradle init --dsl kotlin --type java-application --test-framework junit --project-name mixin_labs-java-bot

Goto src/main/java/mixin_labs/java/bot, create a file called Config.java. Copy the following content into it.

Config.java
```java
package mixin_labs.java.bot;
import mixin.java.sdk.MixinUtil;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Base64;
import mixin.java.sdk.PrivateKeyReader;
public class Config {

public static final String CLIENT_ID = “b1ce2967-a534-417d-bf12-c86571e4eefa”;
public static final String CLIENT_SECRET = “e6b14c6bbb20a43c603c468e225e6e4c666c940792cde43e41b34c3f1dd45713”;
public static final String PIN = “536071”;
public static final String SESSION_ID = “2f1c44a3-d4d2-4dd2-bdb6-8eda67694b91”;
public static final String PIN_TOKEN = “ajJJngHmWgIfH3S2mgH4bAsoPeoXV6hI1KoTZW9AvFUK1R8e28X1zVRCcrOMVeXkvBKQeEMgRdX1kRgH3ksITTBm2mgK5eUnfBHUuRC85oKoQGB9e2Bp4O4ZKGg/6bqLeD66pnBPcO2s7VtgLSAK0tHa2jMzmGlWuxsO6Wo5JHE=”;

private static RSAPrivateKey loadPrivateKey() {
try {

  1. PrivateKey key =
  2. new PrivateKeyReader(Config.class.getClassLoader().getResourceAsStream("rsa_private_key.txt"))
  3. .getPrivateKey();
  4. System.out.println(key);
  5. return (RSAPrivateKey) key;
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. System.exit(1);
  9. return null;
  10. }

}

public static final RSAPrivateKey RSA_PRIVATE_KEY = loadPrivateKey();
public static final byte[] PAY_KEY = MixinUtil.decrypt(RSA_PRIVATE_KEY, PIN_TOKEN, SESSION_ID);
}

  1. Replace the value with content generated in dashboard.
  2. > App.java
  3. ```java
  4. /*
  5. * This Java source file was generated by the Gradle 'init' task.
  6. */
  7. package mixin_labs.java.bot;
  8. import mixin.java.sdk.MixinBot;
  9. import mixin.java.sdk.MixinUtil;
  10. import mixin.java.sdk.MIXIN_Category;
  11. import mixin.java.sdk.MIXIN_Action;
  12. import java.security.PrivateKey;
  13. import java.security.interfaces.RSAPrivateKey;
  14. import com.google.gson.JsonObject;
  15. import com.google.gson.JsonParser;
  16. // import java.util.Base64;
  17. import org.apache.commons.codec.binary.Base64;
  18. import okhttp3.Response;
  19. import okhttp3.WebSocket;
  20. import okhttp3.WebSocketListener;
  21. import okio.ByteString;
  22. public class App {
  23. public static void main(String[] args) {
  24. MixinBot.connectToRemoteMixin(new WebSocketListener() {
  25. @Override
  26. public void onOpen(WebSocket webSocket, Response response) {
  27. System.out.println("[onOpen !!!]");
  28. System.out.println("request header:" + response.request().headers());
  29. System.out.println("response header:" + response.headers());
  30. System.out.println("response:" + response);
  31. // Request unread messages
  32. MixinBot.sendListPendingMessages(webSocket);
  33. }
  34. @Override
  35. public void onMessage(WebSocket webSocket, String text) {
  36. System.out.println("[onMessage !!!]");
  37. System.out.println("text: " + text);
  38. }
  39. @Override
  40. public void onMessage(WebSocket webSocket, ByteString bytes) {
  41. try {
  42. System.out.println("[onMessage !!!]");
  43. String msgIn = MixinUtil.bytesToJsonStr(bytes);
  44. System.out.println("json: " + msgIn);
  45. JsonObject obj = new JsonParser().parse(msgIn).getAsJsonObject();
  46. MIXIN_Action action = MIXIN_Action.parseFrom(obj);
  47. System.out.println(action);
  48. MIXIN_Category category = MIXIN_Category.parseFrom(obj);
  49. System.out.println(category);
  50. if (action == MIXIN_Action.CREATE_MESSAGE && obj.get("data") != null &&
  51. category != null ) {
  52. String userId;
  53. String messageId = obj.get("data").getAsJsonObject().get("message_id").getAsString();
  54. MixinBot.sendMessageAck(webSocket, messageId);
  55. switch (category) {
  56. case PLAIN_TEXT:
  57. String conversationId =
  58. obj.get("data").getAsJsonObject().get("conversation_id").getAsString();
  59. userId =
  60. obj.get("data").getAsJsonObject().get("user_id").getAsString();
  61. byte[] msgData = Base64.decodeBase64(obj.get("data").getAsJsonObject().get("data").getAsString());
  62. MixinBot.sendText(webSocket,conversationId,userId,new String(msgData,"UTF-8"));
  63. break;
  64. default:
  65. System.out.println("Category: " + category);
  66. }
  67. }
  68. } catch (Exception e) {
  69. e.printStackTrace();
  70. }
  71. }
  72. @Override
  73. public void onClosing(WebSocket webSocket, int code, String reason) {
  74. System.out.println("[onClosing !!!]");
  75. System.out.println("code: " + code);
  76. System.out.println("reason: " + reason);
  77. }
  78. @Override
  79. public void onClosed(WebSocket webSocket, int code, String reason) {
  80. System.out.println("[onClosed !!!]");
  81. System.out.println("code: " + code);
  82. System.out.println("reason: " + reason);
  83. }
  84. @Override
  85. public void onFailure(WebSocket webSocket, Throwable t, Response response) {
  86. System.out.println("[onFailure !!!]");
  87. System.out.println("throwable: " + t);
  88. System.out.println("response: " + response);
  89. }
  90. }, Config.RSA_PRIVATE_KEY, Config.CLIENT_ID, Config.SESSION_ID);
  91. }
  92. }

Goto src/main/resources, create a file: rsa_private_key.txt, fill the private key content which you have already generated in dashboard.

rsa_private_key.txt

  1. -----BEGIN RSA PRIVATE KEY-----
  2. ...
  3. -----END RSA PRIVATE KEY-----

Go to the project directory, download the mixin-java-sdk from github,

  1. mkdir libs
  2. cd libs
  3. wget https://github.com/wenewzhang/mixin-java-sdk/releases/download/v5.0/mixin-java-sdk.jar

Add dependencies package info into build.gradle.kts

  1. dependencies {
  2. // This dependency is found on compile classpath of this component and consumers.
  3. implementation("com.google.guava:guava:26.0-jre")
  4. // dependent on mixin-java-sdk, copy it to libs directory
  5. compile(files("libs/mixin-java-sdk.jar"))
  6. implementation("commons-codec:commons-codec:1.11")
  7. implementation("com.auth0:java-jwt:3.5.0")
  8. implementation("com.squareup.okio:okio:2.2.1")
  9. implementation("com.squareup.okhttp3:okhttp:3.12.1")
  10. implementation("com.google.code.gson:gson:2.8.5")
  11. implementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.20")
  12. // Use JUnit test framework
  13. testImplementation("junit:junit:4.12")
  14. }

Goto the directory src/test/java/mixin_labs/java/bot, comment the test code,

AppTest.java

  1. // assertNotNull("app should have a greeting", classUnderTest.getGreeting());

The last step, go back in mixin_labs-java-bot directory, build it and run,

  1. gradle build
  2. gradle run

Console will output:

  1. response:Response{protocol=http/1.1, code=101, message=Switching Protocols, url=https://blaze.mixin.one/}
  2. [onMessage !!!]
  3. json: {"id":"4ee01b68-817e-4f29-bcb4-b40f7c163f61","action":"LIST_PENDING_MESSAGES"}
  4. LIST_PENDING_MESSAGES

Add the bot(for example, this bot id is 7000101639) as your friend in Mixin Messenger and send your messages.
mixin_messenger

Source code summary

Create websocket and connect to Mixin Messenger Server

  1. MixinBot.connectToRemoteMixin(new WebSocketListener() {
  2. @Override
  3. public void onOpen(WebSocket webSocket, Response response) {
  4. MixinBot.sendListPendingMessages(webSocket);
  5. }

Send message “LISTPENDINGMESSAGES” to Mixin Messenger server and server will send unread messages to your bot.

Receive message callback

  1. public void onMessage(WebSocket webSocket, ByteString bytes) {
  2. try {
  3. System.out.println("[onMessage !!!]");
  4. String msgIn = MixinUtil.bytesToJsonStr(bytes);

onMessage func will be called when server push message to bot

Send message response

  1. String messageId = obj.get("data").getAsJsonObject().get("message_id").getAsString();
  2. MixinBot.sendMessageAck(webSocket, messageId);

Send a READ operation message to the server let it knows this message has been read. The bot will receive the duplicated message when the bot connected to server again if bot don’t send response.

Echo chat contant

  1. switch (category) {
  2. case PLAIN_TEXT:
  3. String conversationId =
  4. obj.get("data").getAsJsonObject().get("conversation_id").getAsString();
  5. userId =
  6. obj.get("data").getAsJsonObject().get("user_id").getAsString();
  7. byte[] msgData = Base64.decodeBase64(obj.get("data").getAsJsonObject().get("data").getAsString());
  8. MixinBot.sendText(webSocket,conversationId,userId,new String(msgData,"UTF-8"));

Not only texts, images and other type message will be pushed to your bot. You can find more details about Messenger message.

End

Now your bot worked. You can hack it.

Full code is here