From c1e1ad802488625e7abc632cec317ecdd501a0df Mon Sep 17 00:00:00 2001 From: Yannick Badoual Date: Thu, 22 Sep 2016 14:41:57 +0200 Subject: [PATCH] Added some samples --- .gitignore | 5 +- .../badoualy/telegram/api/TelegramClient.kt | 6 +- sample/.gitignore | 2 +- .../badoualy/telegram/KotlogramSample.java | 179 ------------------ .../github/badoualy/telegram/sample/C.java | 118 ++++++++++++ .../sample/SampleDownloadMessageMedia.java | 82 ++++++++ .../telegram/sample/SampleGetDialogs.java | 111 +++++++++++ .../telegram/sample/SampleGetHistory.java | 78 ++++++++ .../telegram/sample/SampleSendMessage.java | 43 +++++ .../telegram/sample/SampleSendSticker.java | 58 ++++++ .../telegram/sample/SampleSignIn.java | 42 ++++ 11 files changed, 542 insertions(+), 182 deletions(-) delete mode 100644 sample/src/main/java/com/github/badoualy/telegram/KotlogramSample.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/C.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleDownloadMessageMedia.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetDialogs.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetHistory.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendMessage.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendSticker.java create mode 100644 sample/src/main/java/com/github/badoualy/telegram/sample/SampleSignIn.java diff --git a/.gitignore b/.gitignore index 6dd1cec12..0eca3bb86 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,7 @@ gradle-app.setting # Cache of project .gradletasknamecache -version.properties \ No newline at end of file +version.properties +src/main/resources/ +src/test/ +src/main/java/com/github/badoualy/telegram/sample/SampleSignIn.java diff --git a/api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClient.kt b/api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClient.kt index a80f006a1..550d14a1b 100644 --- a/api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClient.kt +++ b/api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClient.kt @@ -133,5 +133,9 @@ interface TelegramClient : TelegramApi { /** Convenience method to download a file synchronously */ @Throws(RpcErrorException::class, IOException::class) - fun downloadSync(inputLocation: InputFileLocation, size: Int, partSize: Int = 512 * 1024, outputStream: OutputStream) + fun downloadSync(inputLocation: InputFileLocation, size: Int, outputStream: OutputStream) = downloadSync(inputLocation, size, 512 * 1024, outputStream) + + /** Convenience method to download a file synchronously */ + @Throws(RpcErrorException::class, IOException::class) + fun downloadSync(inputLocation: InputFileLocation, size: Int, partSize: Int, outputStream: OutputStream) } \ No newline at end of file diff --git a/sample/.gitignore b/sample/.gitignore index 2a2d7172e..ba976b6dc 100644 --- a/sample/.gitignore +++ b/sample/.gitignore @@ -6,6 +6,6 @@ auth*.key src/test/java/com/github/badoualy/telegram/C.java *.save *.jpg -Sample*.java +/src/test/**/Sample*.java /src/main/resources/* tmp \ No newline at end of file diff --git a/sample/src/main/java/com/github/badoualy/telegram/KotlogramSample.java b/sample/src/main/java/com/github/badoualy/telegram/KotlogramSample.java deleted file mode 100644 index 196b4c34f..000000000 --- a/sample/src/main/java/com/github/badoualy/telegram/KotlogramSample.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.github.badoualy.telegram; - -import com.github.badoualy.telegram.api.Kotlogram; -import com.github.badoualy.telegram.api.TelegramApiStorage; -import com.github.badoualy.telegram.api.TelegramApp; -import com.github.badoualy.telegram.api.TelegramClient; -import com.github.badoualy.telegram.mtproto.model.DataCenter; -import com.github.badoualy.telegram.mtproto.auth.AuthKey; -import com.github.badoualy.telegram.mtproto.model.MTSession; -import com.github.badoualy.telegram.tl.api.TLAbsMessage; -import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; -import com.github.badoualy.telegram.tl.api.TLInputPeerUser; -import com.github.badoualy.telegram.tl.api.TLMessage; -import com.github.badoualy.telegram.tl.api.TLUser; -import com.github.badoualy.telegram.tl.api.auth.TLAuthorization; -import com.github.badoualy.telegram.tl.api.auth.TLSentCode; -import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; -import com.github.badoualy.telegram.tl.exception.RpcErrorException; - -import org.apache.commons.io.FileUtils; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Random; -import java.util.Scanner; - -@SuppressWarnings("ALL") -public class KotlogramSample { - - public static final int API_ID = 99999; - public static final String API_HASH = ""; - public static final String MODEL = "Model"; - public static final String SYSTEM_VERSION = "SysVer"; - public static final String APP_VERSION = "AppVer"; - public static final String LANG_CODE = "en"; - - public static TelegramApp application = new TelegramApp(API_ID, API_HASH, MODEL, SYSTEM_VERSION, APP_VERSION, LANG_CODE); - public static final String PHONE_NUMBER = "+00000000000"; // TODO: you need to fill this - - public static final File AUTH_KEY_FILE = new File("sample" + File.separator + "auth.key"); - public static final File NEAREST_DC_FILE = new File("sample" + File.separator + "dc.save"); - public static final File SALT_FILE = new File("sample" + File.separator + "salt.save"); - - public static void main(String[] args) throws InterruptedException { - // Activate debug log or not, false by default - // Kotlogram.setDebugLogEnabled(true); - - // Replace the following constants with your app's information - // This informations are used in initConnection and sendCode rpc methods - TelegramApp app = new TelegramApp(API_ID, API_HASH, MODEL, SYSTEM_VERSION, APP_VERSION, LANG_CODE); - - // This is a synchronous client, that will block until the response arrive (or until timeout) - // A client which return an Observable where T is the response type will be available soon - TelegramClient client = Kotlogram.getDefaultClient(app, new ApiStorage()); - - // You can start making requests - try { - // Send code to account - TLSentCode sentCode = client.authSendCode(false, PHONE_NUMBER, true); - System.out.println("Authentication code: "); - String code = new Scanner(System.in).nextLine(); - - // Auth with the received code - TLAuthorization authorization = client.authSignIn(PHONE_NUMBER, sentCode.getPhoneCodeHash(), code); - TLUser self = authorization.getUser().getAsUser(); - System.out.println("You are now signed in as " + self.getFirstName() + " " + self.getLastName()); - - // Start making cool stuff! - // Get a list of 10 most recent conversations - TLAbsDialogs dialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), 10); - for (TLAbsMessage message : dialogs.getMessages()) { - if (message instanceof TLMessage) { - System.out.println("Found message " + ((TLMessage) message).getMessage()); - } else { - System.out.println("Found a service message or empty message"); - } - } - - // Take the first user in the list, and send a message to him - // It'll probably be Telegram bot, since he'll send you the code - TLUser randomUser = dialogs.getUsers().get(0).getAsUser(); - TLInputPeerUser inputUser = new TLInputPeerUser(randomUser.getId(), randomUser.getAccessHash()); - int randomId = new Random(System.currentTimeMillis()).nextInt(); - client.messagesSendMessage(inputUser, "Kotlogram is awesome!", randomId); - System.out.println("Message sent"); - } catch (RpcErrorException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - client.close(); // Important, do not forget this, or your process won't finish - } - System.out.println("------------------------- GOOD BYE"); - } - - /** - * Implement ApiStorage to save your connection, to avoid having to use sendCode every time you launch your app - */ - private static class ApiStorage implements TelegramApiStorage { - - - @Override - public void saveAuthKey(@NotNull AuthKey authKey) { - try { - FileUtils.writeByteArrayToFile(AUTH_KEY_FILE, authKey.getKey()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Nullable - @Override - public AuthKey loadAuthKey() { - try { - return new AuthKey(FileUtils.readFileToByteArray(AUTH_KEY_FILE)); - } catch (IOException e) { - if (!(e instanceof FileNotFoundException)) - e.printStackTrace(); - } - - return null; - } - - @Override - public void saveDc(@NotNull DataCenter dataCenter) { - try { - FileUtils.write(NEAREST_DC_FILE, dataCenter.toString()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Nullable - @Override - public DataCenter loadDc() { - try { - String[] infos = FileUtils.readFileToString(NEAREST_DC_FILE).split(":"); - return new DataCenter(infos[0], Integer.parseInt(infos[1])); - } catch (IOException e) { - if (!(e instanceof FileNotFoundException)) - e.printStackTrace(); - } - - return null; - } - - @Override - public void deleteAuthKey() { - try { - FileUtils.forceDelete(AUTH_KEY_FILE); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void deleteDc() { - try { - FileUtils.forceDelete(NEAREST_DC_FILE); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void saveSession(@NotNull MTSession session) { - - } - - @Nullable - @Override - public MTSession loadSession() { - return null; - } - } -} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/C.java b/sample/src/main/java/com/github/badoualy/telegram/sample/C.java new file mode 100644 index 000000000..9fca486d9 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/C.java @@ -0,0 +1,118 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.TelegramApiStorage; +import com.github.badoualy.telegram.api.TelegramApp; +import com.github.badoualy.telegram.mtproto.auth.AuthKey; +import com.github.badoualy.telegram.mtproto.model.DataCenter; +import com.github.badoualy.telegram.mtproto.model.MTSession; + +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; + +public final class C { + + // Get them from Telegram's console + public static final int API_ID = 0; + public static final String API_HASH = ""; + + // What you want to appear in the "all sessions" screen + public static final String APP_VERSION = "AppVersion"; + public static final String MODEL = "Model"; + public static final String SYSTEM_VERSION = "SysVer"; + public static final String LANG_CODE = "en"; + + public static TelegramApp application = new TelegramApp(API_ID, API_HASH, MODEL, SYSTEM_VERSION, APP_VERSION, LANG_CODE); + + // Phone number used for tests + public static final String PHONE_NUMBER = "+00000000000"; // International format + + public static final File ROOT_DIR = new File("sample" + File.separator); + public static final File AUTH_KEY_FILE = new File(ROOT_DIR, "auth.key"); + public static final File NEAREST_DC_FILE = new File(ROOT_DIR, "dc.save"); + + public static class ApiStorage implements TelegramApiStorage { + + @Override + public void saveAuthKey(@NotNull AuthKey authKey) { + try { + FileUtils.writeByteArrayToFile(AUTH_KEY_FILE, authKey.getKey()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Nullable + @Override + public AuthKey loadAuthKey() { + try { + return new AuthKey(FileUtils.readFileToByteArray(AUTH_KEY_FILE)); + } catch (IOException e) { + if (!(e instanceof FileNotFoundException)) + e.printStackTrace(); + } + + return null; + } + + @Override + public void saveDc(@NotNull DataCenter dataCenter) { + try { + FileUtils.write(NEAREST_DC_FILE, dataCenter.toString()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Nullable + @Override + public DataCenter loadDc() { + try { + String[] infos = FileUtils.readFileToString(NEAREST_DC_FILE).split(":"); + return new DataCenter(infos[0], Integer.parseInt(infos[1])); + } catch (IOException e) { + if (!(e instanceof FileNotFoundException)) + e.printStackTrace(); + } + + return null; + } + + @Override + public void deleteAuthKey() { + try { + FileUtils.forceDelete(AUTH_KEY_FILE); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void deleteDc() { + try { + FileUtils.forceDelete(NEAREST_DC_FILE); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void saveSession(@Nullable MTSession session) { + + } + + @Nullable + @Override + public MTSession loadSession() { + return null; + } + } + + private C() { + + } +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleDownloadMessageMedia.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleDownloadMessageMedia.java new file mode 100644 index 000000000..c5cacb978 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleDownloadMessageMedia.java @@ -0,0 +1,82 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.api.utils.MediaInput; +import com.github.badoualy.telegram.api.utils.TLMediaUtilsKt; +import com.github.badoualy.telegram.tl.api.TLAbsInputPeer; +import com.github.badoualy.telegram.tl.api.TLAbsMessage; +import com.github.badoualy.telegram.tl.api.TLAbsMessageMedia; +import com.github.badoualy.telegram.tl.api.TLDocument; +import com.github.badoualy.telegram.tl.api.TLDocumentAttributeFilename; +import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; +import com.github.badoualy.telegram.tl.api.TLMessage; +import com.github.badoualy.telegram.tl.api.TLMessageMediaDocument; +import com.github.badoualy.telegram.tl.api.TLMessageMediaPhoto; +import com.github.badoualy.telegram.tl.api.TLMessageMediaWebPage; +import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; +import com.github.badoualy.telegram.tl.api.messages.TLAbsMessages; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.ROOT_DIR; +import static com.github.badoualy.telegram.sample.C.application; +import static com.github.badoualy.telegram.sample.SampleGetHistory.getInputPeer; + +/** + * This snippet will get the most recent conversation and download the media attached with the message (if any) + */ +public class SampleDownloadMessageMedia { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // You can start making requests + try { + TLAbsDialogs tlAbsDialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), 1); + TLAbsInputPeer inputPeer = getInputPeer(tlAbsDialogs); + + // Get most recent message + TLAbsMessages tlAbsMessages = client.messagesGetHistory(inputPeer, 0, 0, 0, 1, 0, 0); + TLAbsMessage tlAbsMessage = tlAbsMessages.getMessages().get(0); + + if (tlAbsMessage instanceof TLMessage && ((TLMessage) tlAbsMessage).getMedia() != null) { + TLAbsMessageMedia media = ((TLMessage) tlAbsMessage).getMedia(); + + // Magic utils method from api module + MediaInput mediaInput = TLMediaUtilsKt.getAbsMediaInput(media); + + if (mediaInput != null) { + String filename; + if (media instanceof TLMessageMediaPhoto || media instanceof TLMessageMediaWebPage) { + filename = "photo.jpg"; + } else { + // Retrieve real name + TLDocument tlDocument = ((TLMessageMediaDocument) media).getDocument().getAsDocument(); + filename = ((TLDocumentAttributeFilename) tlDocument.getAttributes().stream() + .filter(attr -> attr instanceof TLDocumentAttributeFilename) + .findFirst().get()).getFileName(); + } + + FileOutputStream fos = new FileOutputStream(new File(ROOT_DIR, filename)); + client.downloadSync(mediaInput.getInputFileLocation(), mediaInput.getSize(), fos); + // downloadSync closes the stream automatically + } else { + System.err.println("MessageMedia type not supported" + media.getClass().getSimpleName()); + } + } else { + System.err.println("Latest message has no media attached"); + } + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetDialogs.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetDialogs.java new file mode 100644 index 000000000..85549489e --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetDialogs.java @@ -0,0 +1,111 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.tl.api.TLAbsMessage; +import com.github.badoualy.telegram.tl.api.TLAbsMessageAction; +import com.github.badoualy.telegram.tl.api.TLAbsPeer; +import com.github.badoualy.telegram.tl.api.TLAbsUser; +import com.github.badoualy.telegram.tl.api.TLChannel; +import com.github.badoualy.telegram.tl.api.TLChannelForbidden; +import com.github.badoualy.telegram.tl.api.TLChat; +import com.github.badoualy.telegram.tl.api.TLChatEmpty; +import com.github.badoualy.telegram.tl.api.TLChatForbidden; +import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; +import com.github.badoualy.telegram.tl.api.TLMessage; +import com.github.badoualy.telegram.tl.api.TLMessageService; +import com.github.badoualy.telegram.tl.api.TLPeerChannel; +import com.github.badoualy.telegram.tl.api.TLPeerChat; +import com.github.badoualy.telegram.tl.api.TLPeerUser; +import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.IOException; +import java.util.HashMap; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.application; + +/** + * This snippet will get the 10 most recent conversations and display the title + the latest message + */ +public class SampleGetDialogs { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // Number of recent conversation you want to get (Telegram has an internal max, your value will be capped) + int count = 10; + + // You can start making requests + try { + TLAbsDialogs tlAbsDialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), count); + + // Map peer id to displayable string + HashMap nameMap = createNameMap(tlAbsDialogs); + + // Map message id to message + HashMap messageMap = new HashMap<>(); + tlAbsDialogs.getMessages().forEach(message -> messageMap.put(message.getId(), message)); + + tlAbsDialogs.getDialogs().forEach(dialog -> { + System.out.print(nameMap.get(getId(dialog.getPeer())) + ": "); + TLAbsMessage topMessage = messageMap.get(dialog.getTopMessage()); + if (topMessage instanceof TLMessage) { + // The message could also be a file, a photo, a gif, ... + System.out.println(((TLMessage) topMessage).getMessage()); + } else if (topMessage instanceof TLMessageService) { + TLAbsMessageAction action = ((TLMessageService) topMessage).getAction(); + // action defined the type of message (user joined group, ...) + System.out.println("Service message"); + } + }); + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } + + /** + * @param tlAbsDialogs result from messagesGetDialogs + * @return a map where the key is the peerId and the value is the chat/channel title or the user's name + */ + public static HashMap createNameMap(TLAbsDialogs tlAbsDialogs) { + // Map peer id to name + HashMap nameMap = new HashMap<>(); + + tlAbsDialogs.getUsers().stream() + .map(TLAbsUser::getAsUser) + .forEach(user -> nameMap.put(user.getId(), + user.getFirstName() + " " + user.getLastName())); + + tlAbsDialogs.getChats().stream() + .forEach(chat -> { + if (chat instanceof TLChannel) { + nameMap.put(chat.getId(), ((TLChannel) chat).getTitle()); + } else if (chat instanceof TLChannelForbidden) { + nameMap.put(chat.getId(), ((TLChannelForbidden) chat).getTitle()); + } else if (chat instanceof TLChat) { + nameMap.put(chat.getId(), ((TLChat) chat).getTitle()); + } else if (chat instanceof TLChatEmpty) { + nameMap.put(chat.getId(), "Empty chat"); + } else if (chat instanceof TLChatForbidden) { + nameMap.put(chat.getId(), ((TLChatForbidden) chat).getTitle()); + } + }); + + return nameMap; + } + + public static int getId(TLAbsPeer peer) { + if (peer instanceof TLPeerUser) + return ((TLPeerUser) peer).getUserId(); + if (peer instanceof TLPeerChat) + return ((TLPeerChat) peer).getChatId(); + + return ((TLPeerChannel) peer).getChannelId(); + } +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetHistory.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetHistory.java new file mode 100644 index 000000000..d3341fe76 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleGetHistory.java @@ -0,0 +1,78 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.tl.api.TLAbsInputPeer; +import com.github.badoualy.telegram.tl.api.TLAbsPeer; +import com.github.badoualy.telegram.tl.api.TLChannel; +import com.github.badoualy.telegram.tl.api.TLChat; +import com.github.badoualy.telegram.tl.api.TLInputPeerChannel; +import com.github.badoualy.telegram.tl.api.TLInputPeerChat; +import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; +import com.github.badoualy.telegram.tl.api.TLInputPeerUser; +import com.github.badoualy.telegram.tl.api.TLMessage; +import com.github.badoualy.telegram.tl.api.TLPeerUser; +import com.github.badoualy.telegram.tl.api.TLUser; +import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; +import com.github.badoualy.telegram.tl.api.messages.TLAbsMessages; +import com.github.badoualy.telegram.tl.core.TLObject; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.IOException; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.application; +import static com.github.badoualy.telegram.sample.SampleGetDialogs.getId; + +/** + * This snippet will get the most recent conversation and print the last 10 messages + */ +public class SampleGetHistory { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // How many messages we want to get (same than dialogs, there is a cap) + int count = 10; + + // You can start making requests + try { + TLAbsDialogs tlAbsDialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), 1); + TLAbsInputPeer inputPeer = getInputPeer(tlAbsDialogs); + + TLAbsMessages tlAbsMessages = client.messagesGetHistory(inputPeer, 0, 0, 0, count, 0, 0); + tlAbsMessages.getMessages().forEach(message -> { + if (message instanceof TLMessage) + System.out.println(((TLMessage) message).getMessage()); + else + System.out.println("Service message"); + }); + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } + + /** + * Get the first peer and return it as an InputPeer to use with methods + */ + public static TLAbsInputPeer getInputPeer(TLAbsDialogs tlAbsDialogs) { + TLAbsPeer tlAbsPeer = tlAbsDialogs.getDialogs().get(0).getPeer(); + int peerId = getId(tlAbsPeer); + TLObject peer = tlAbsPeer instanceof TLPeerUser ? + tlAbsDialogs.getUsers().stream().filter(user -> user.getId() == peerId).findFirst().get() + : tlAbsDialogs.getChats().stream().filter(chat -> chat.getId() == peerId).findFirst().get(); + + if (peer instanceof TLChannel) + return new TLInputPeerChannel(((TLChannel) peer).getId(), ((TLChannel) peer).getAccessHash()); + if (peer instanceof TLChat) + return new TLInputPeerChat(((TLChat) peer).getId()); + if (peer instanceof TLUser) + return new TLInputPeerUser(((TLUser) peer).getId(), ((TLUser) peer).getAccessHash()); + + return new TLInputPeerEmpty(); + } +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendMessage.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendMessage.java new file mode 100644 index 000000000..ba3bf43a8 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendMessage.java @@ -0,0 +1,43 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.tl.api.TLAbsInputPeer; +import com.github.badoualy.telegram.tl.api.TLAbsUpdates; +import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; +import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.IOException; +import java.util.Random; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.application; +import static com.github.badoualy.telegram.sample.SampleGetHistory.getInputPeer; + +/** + * This snippet will get the most recent conversation and send a message in this conversation. + */ +public class SampleSendMessage { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // You can start making requests + try { + TLAbsDialogs tlAbsDialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), 1); + TLAbsInputPeer inputPeer = getInputPeer(tlAbsDialogs); + + TLAbsUpdates tlAbsUpdates = client.messagesSendMessage(inputPeer, "Sent from Kotlogram :)", Math.abs(new Random().nextLong())); + + // tlAbsUpdates contains the id and date of the message in a TLUpdateShortSentMessage + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } + +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendSticker.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendSticker.java new file mode 100644 index 000000000..a00a58926 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSendSticker.java @@ -0,0 +1,58 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.tl.api.TLAbsInputPeer; +import com.github.badoualy.telegram.tl.api.TLAbsUpdates; +import com.github.badoualy.telegram.tl.api.TLDocument; +import com.github.badoualy.telegram.tl.api.TLInputDocument; +import com.github.badoualy.telegram.tl.api.TLInputMediaDocument; +import com.github.badoualy.telegram.tl.api.TLInputPeerEmpty; +import com.github.badoualy.telegram.tl.api.messages.TLAbsDialogs; +import com.github.badoualy.telegram.tl.api.messages.TLStickers; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.IOException; +import java.util.Random; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.application; +import static com.github.badoualy.telegram.sample.SampleGetHistory.getInputPeer; + +/** + * This snippet will get the most recent conversation and send a sticker in thie conversation. + */ +public class SampleSendSticker { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // You can start making requests + try { + TLAbsDialogs tlAbsDialogs = client.messagesGetDialogs(0, 0, new TLInputPeerEmpty(), 1); + TLAbsInputPeer inputPeer = getInputPeer(tlAbsDialogs); + + // Get the stickers available for emoji sunglass + TLStickers tlStickers = (TLStickers) client.messagesGetStickers("\uD83D\uDE0E", ""); + if (!tlStickers.getStickers().isEmpty()) { + // Take first available one + TLDocument tlDocument = tlStickers.getStickers().get(0).getAsDocument(); + TLInputDocument tlInputDocument = new TLInputDocument(tlDocument.getId(), tlDocument.getAccessHash()); + + TLAbsUpdates tlAbsUpdates = client.messagesSendMedia(false, false, false, + inputPeer, null, new TLInputMediaDocument(tlInputDocument, ""), + Math.abs(new Random().nextLong()), null); + // tlAbsUpdates contains the id and date of the message in a TLUpdateShortSentMessage + } else { + System.err.println("No sticker found"); + } + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } + +} diff --git a/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSignIn.java b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSignIn.java new file mode 100644 index 000000000..bffbbe362 --- /dev/null +++ b/sample/src/main/java/com/github/badoualy/telegram/sample/SampleSignIn.java @@ -0,0 +1,42 @@ +package com.github.badoualy.telegram.sample; + +import com.github.badoualy.telegram.api.Kotlogram; +import com.github.badoualy.telegram.api.TelegramClient; +import com.github.badoualy.telegram.tl.api.TLUser; +import com.github.badoualy.telegram.tl.api.auth.TLAuthorization; +import com.github.badoualy.telegram.tl.api.auth.TLSentCode; +import com.github.badoualy.telegram.tl.exception.RpcErrorException; + +import java.io.IOException; +import java.util.Scanner; + +import static com.github.badoualy.telegram.sample.C.ApiStorage; +import static com.github.badoualy.telegram.sample.C.PHONE_NUMBER; +import static com.github.badoualy.telegram.sample.C.application; + +public class SampleSignIn { + + public static void main(String[] args) { + // This is a synchronous client, that will block until the response arrive (or until timeout) + // A client which return an Observable where T is the response type will be available soon + TelegramClient client = Kotlogram.getDefaultClient(application, new ApiStorage()); + + // You can start making requests + try { + // Send code to account + TLSentCode sentCode = client.authSendCode(false, PHONE_NUMBER, true); + System.out.println("Authentication code: "); + String code = new Scanner(System.in).nextLine(); + + // Auth with the received code + TLAuthorization authorization = client.authSignIn(PHONE_NUMBER, sentCode.getPhoneCodeHash(), code); + TLUser self = authorization.getUser().getAsUser(); + System.out.println("You are now signed in as " + self.getFirstName() + " " + self.getLastName() + " @" + self.getUsername()); + } catch (RpcErrorException | IOException e) { + e.printStackTrace(); + } finally { + client.close(); // Important, do not forget this, or your process won't finish + } + } + +}