Using Telegram API for Java Desktop App? - java

I am not that new to Java Programming, but I have never worked with external libraries etc. Now I want to develop a desktop client for the "Telegram" open-source messaging platform, and I'm stuck when it comes to API-Usage.
There is pretty much documentation about the Telegram API, found at https://core.telegram.org/api, and I've already downloaded mtproto, telegram-api and tl-core from github, and compiled my own library jar from source by using gradle. As well, I've already written a small application, where the user clicks a button and is promted to enter his phone number, I'm using the Java-swing-Libraries and an ActionListener for this.
The phone number entered by the user should now be checked if it is already registered, the auth.checkPhone method seems to be capable for that. But how can I refer to it within my eclipse project? I don't see any method "checkPhone" in any of the classes! What should I do?
Please help me, I can't help myself and I am desperately stuck in my project. Even a small hint would help.
Thanks in Advance,
Lukas

Essentially you will have to fill out the blanks in the code given on GitHub in the ex3ndr/telegram-api repository. If you've got the library Jar file you built and the tl-api-v12.jarfile on your Eclipse project's Java build path, then look at the RPC Calls section of the README and
First you need to set up an AppInfo object with your API credentials, then you will also have to create some new classes that implement the AbsApiState and ApiCallback interfaces. Once these are available, you can create the TelegramApi object and make an RPC call to the Telegram service as follows; in this case using the suggested auth.checkPhone method:
// TODO set up AbsApiState, AppInfo and ApiCallback objects
TelegramApi api = new TelegramApi(state, appInfo, apiCallback);
// Create request
String phoneNumber = "1234567890";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
The TelegramApi object represents your connection to the remote service, which is a request response style of API. RPC calls are made via the doRpcCall method, which takes a request object from the org.telegram.api.requests package (the TLRequestAuthCheckPhone type in the example) filled in with the appropriate parameters. A response object (TLCheckedPhone above) is then returned with the result when it is available.
In the case of an asynchronous call the method returns immediately, and the onResult callback method is executed when the result is available:
// Call service aynchronously
api.doRpcCall(checkPhone, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() { }
public void onResult(TLCheckedPhone result) {
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
}
public void onError(int errorCode, String message) { }
});

Or just look at this API https://github.com/pengrad/java-telegram-bot-api
It is really simple to use

Related

Codename One - Json in Dropbox 2

I am using firebase to send Json thru my CN1 app. This is my code and it's working fine, but I want to send the stuff to Dropbox instead and I just can't make it work. (I already got my token, key and secret from their site)
Could you please tell me what I need to change in order to be able to upload my stuff into Dropbox?
#Override
protected void onPrincipal_ButtonJsonAction(Component c, ActionEvent event) {
final String data = Result.fromContent(hashtableWithInfo).toString();
String firebase = "https://fire-game-258.firebaseio.com/example.json";
ConnectionRequest request = new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(data.getBytes("UTF-8"));
}
};
request.setUrl(firebase);
request.setPost(true);
request.setHttpMethod("POST");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
}
Many many many thanks.
Firebase and Dropbox are completely different API's and need to go thru completely different processes. Saving a file to dropbox requires an OAuth process for the specific user whereas firebase is a global API.
I would recommend you look at parse which more closely resembles firebase and already has standardized builtin mappings in Java: https://github.com/sidiabale/parse4cn1/

GreenDao how to implement callbacks

I have a trouble, i need to get event/callback when i try to write to database.
I added greenDao lib to project, and i able to write/delete in db.
But no idea how to get callback after some operation under db.
In introduction to lib i read "AsyncOperationListener for asynchronous callback when operations complete".
Used this tutorial:
http://blog.surecase.eu/using-greendao-with-android-studio-ide/
Can anybody help me with this trouble?
UPD:
ok here we added some list in storage
getMyObjectDao().getSession().startAsyncSession().insertOrReplaceInTx(MyObject.class, list);
error here
List<MyObject> items = getBoxDao(c).getSession().startAsyncSession().loadAll(MyObject.class);
How can we asynchronously load data from db?
Is this correct solution?
#Override
public void onAsyncOperationCompleted(AsyncOperation operation) {
String operationIs = null;
switch (operation.getType()) {
case LoadAll:
itemsList = BoxRepository.getAllBoxes(getApplicationContext());
By default all the operations are performed synchronously, eliminating the need to get any callback. But the recent version of GreenDAO introduces AsyncSession, which can be used to perform operations asynchronously and also provides a way set listener on it. See the example below:
AsyncSession asyncSession = App.getInstance().daoSession.startAsyncSession();
asyncSession.setListener( new AsyncOperationListener() {
#Override
public void onAsyncOperationCompleted(AsyncOperation operation) {
// do whats needed
}
});
asyncSession.insert(MyObject);
Simple ask if anything unclear!

Android SDK, Check if device is Amazon-FireTV

I am trying to write a simple piece of code that will execute some other code if true. What I want to do is check if my app is running on the 'Amazon Fire-TV (BOX, not the Fire-TV stick)' I think it would not be that hard to do but I am guessing it would be something like this?
String osName = android.getSystemOS();
if(!osName.equals("AMAZON FIRE-TV")){
Toast.makeText(MainActivity.class, "This app may not be compatible with your device..., Toast.LENGTH_LONG").show();
...
}
You can check any device name specifically using:
boolean isFireTV = Build.MODEL.equalsIgnoreCase("AFTB");
(see this page for FireTV model strings, and this one for Fire Tablets)
I'd also check out this answer for a more generic test to help you determine if your app is running on an Amazond device, or installed via the Amazon AppStore (eg on a Blackberry device)
the following function:
public static boolean isTV() {
return android.os.Build.MODEL.contains("AFT");
}
should detect either firetv or fire tv stick
see
https://developer.amazon.com/public/solutions/devices/fire-tv/docs/amazon-fire-tv-sdk-frequently-asked-questions
for details

Cannot insert object in Parse.com with parse4j API in JAVA

I am using Parse.com for communicating with iOS application and Web Browser. I have registered in parse.com and created an application. Now I have an iOS application ready to insert an object in that application which is working fine. Now comes the backend part, I am using JAVA for web application. Now,
https://parse.com/docs/api_libraries
According to this link, I can see the API/ Libraries I can use in JAVA is
Almonds
mobile-parse-api
Parse4j
ParseFacade
Among this 4, I have selected Parse4j to build web application with.
I am using Eclipse, I have installed GWT plugin, created a web application. Now I am adding this parse4j.jar file to that project, Added it to the build path also. And then I try to write this code
try {
Parse.initialize("my app id", "my rest app id");
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.save();
return "OK";
} catch(IllegalArgumentException e){
e.printStackTrace();
return "KO";
}
catch(ParseException e){
e.printStackTrace();
return "KO";
}
It doesn't insert the object to parse cloud. Please help why isn't working? Am I missing anything to write?
As far as I see, the code is correct. However, if Parse4j does not save the entry
this means that you write wrong the attribute name or class name. Just check the names
and class name then reply back.
Regards.
One way to validate is the do a Query, get the object and print all the attributes / data types. Then store these as static class level constants and use them throughout your class for setting values in new objects to persist.
If the get query doesn't work (without any filters), which means your class name is incorrect.
Good Luck!

Capturing windows event with java windows services

I want to capture lock/unlock/start/shutdown/log off and log on events through a windows service and then I want to fire a function for each event so that I can capture the time when Event occured.
I want to do this through a windows service so that I need not run the program manually. And I want to run this program through java language.
Looks like you will need to use JNA and write the capture code with native Windows calls.
There is a class java.awt.Robot that does the reverse -- simulating OS events but I am not aware of the way to capture events in pure Java.
In C# it is pretty straightforward. I can show you code in C#, you can then convert it to Ja.Net if you want to use Java as a language. (if you actually want to use JVM, this won't help as much though).
Create empty C# service.
Inside your program Main method set CanHandleSessionChangeEvent property to true:
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
LogService logService = new LogService();
logService.CanHandleSessionChangeEvent = true;
ServicesToRun = new ServiceBase[]
{
logService
};
ServiceBase.Run(ServicesToRun);
}
in service implementation override OnSessionChange event, where you can dump information on user logon/logoff and session connect/disconnect
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
EventLog.WriteEvent(
new EventInstance(100, 0, EventLogEntryType.Information),
String.Format("Reason: {0}, SessionId:{1}", changeDescription.Reason, changeDescription.SessionId));
base.OnSessionChange(changeDescription);
}
Register service, start it up and see records in event log.

Categories