How verify if a member is admin? - java

I'm working on a bot for supergroups.
How I can verify if member is admin?
my lib:org.telegram 4.2 https://core.telegram.org/bots/api
I tried with ChatMember, GetChatAdministrators and SendMessage methods but I have no idea how insert parameters because they don't ask them but they have only .get option (null respose). Only GetChatAdministrators permit a .set method for ChatID but it give error
GetChatAdministrators getadmin = new GetChatAdministrators().setChatId(ChatIDSupergroup);
ArrayList<ChatMember> s = null;
try {
s = getadmin.deserializeResponse(null); //Unable to deserialize response
} catch (TelegramApiRequestException e) {
e.printStackTrace();
}
ChatMember member = new ChatMember(); //There are only get options
String status=member.getStatus(); //null

I had a same problem but I couldn't find an answer from anywhere. Then I tried myself and finally today I found the following solution:
public List<ChatMember> getChatAdministrators(Long chatId){
List<ChatMember> chatAdministrators = Collections.emptyList();
try {
chatAdministrators = execute(new GetChatAdministrators(String.valueOf(chatId)));
} catch (TelegramApiException e) {
e.printStackTrace();
}
return chatAdministrators;
}
This method returns list of administrators of telegram groups, supergroups or channels.

function adminCheck( id, chat_id ) {
var bAdminCheck = false;
var name = "";
var aChatMember = getChatAdministrators( chat_id );
var contents = JSON.parse( aChatMember );
var i = 0;
while( !bAdminCheck && ( i < contents.result.length ) ) {
if( id == contents.result[i].user.id ) {
bAdminCheck = true;
}
i++;
}
return {
AdminCheck: bAdminCheck,
};
}
Available methods
source:
https://core.telegram.org/bots/api#available-methods
getChatAdministrators
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.

Related

CosmosDB : CosmosPatchOperation not working via Stored Procedure

I want to replace cosmos batch with Stored Proc as my requirement is to upsert 100+ records which cosmos batch does not support. I am adding 2 java objects and 1 CosmosPatchOperations
in List and passing to below method.Whenver I am adding cosmos patch object no rows got inserted/updated otherwise it is working fine.I want to perform both insertion and patch operation in same transaction. Can somebody please guide how to modify SP so that it supports both insert and patch operation.
String rowsUpserted = "";
try
{
rowsUpserted = container
.getScripts()
.getStoredProcedure("createEvent")
.execute(Arrays.asList(listObj), options)
.getResponseAsString();
}catch(Exception e){
e.printStackTrace();
}
Stored Proc
function createEvent(items) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var count = 0;
if (!items) throw new Error("The array is undefined or null.");
var numItems = items.length;
if (numItems == 0) {
getContext().getResponse().setBody(0);
return;
}
tryCreate(items[count], callback);
function tryCreate(item, callback) {
var options = { disableAutomaticIdGeneration: false };
var isAccepted = collection.upsertDocument(collectionLink, item, options, callback);
if (!isAccepted) getContext().getResponse().setBody(count);
}
function callback(err, item, options) {
if (err) throw err;
count++;
if (count >= numItems) {
getContext().getResponse().setBody(count);
} else {
tryCreate(items[count], callback);
}
}
}
Patching doesn't appear to be supported by the Collection type in the Javascript stored proc API. I suspect this was done as it's more an optimisiation for remote calls and SP execute locally so it's not really neccessary.
API reference is here: http://azure.github.io/azure-cosmosdb-js-server/Collection.html
upsertDocument is expecting the full document.

getJSONObject and subsequent getString returns null

This is a very straightforward question, but this error is very mysterious to me as I have not been able to find a solution or anyone else who has had this problem. I've also used a very similar technique in another activity and it worked just fine. I am making an android application which makes a POST request to a server. The response is a JSONObject that must be parsed into a number and another JSONObject which must also be parsed, and its values assigned to an array of CurrentGame objects. The first call to getJSONObject works fine, but calling getString on that JSONObject returns the following error:
java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.xxxxx.xxxxx.CurrentGame.oppEmail' on a null object reference
Here is my java code:
private void handleResponse(JSONObject response){
int numGroups = 0;
try{
numGroups = response.getInt("Number");
}catch(JSONException e){
e.printStackTrace();
}
Log.i("Number of Groups", String.valueOf(numGroups));
CurrentGame[] currentGames = new CurrentGame[numGroups];
JSONObject current;
int yourTurn = 0;
for(int i = 0; i < numGroups; i++){
try{
current = response.getJSONObject(String.valueOf(i));
Log.i("Current JSONObject: ", String.valueOf(current));
if(current.has("OppEmail")){
currentGames[i].oppEmail = current.getString("OppEmail");
}
if(current.has("OppName")) {
currentGames[i].oppName = current.getString("OppName");
}
if(current.has("Group")) {
currentGames[i].group = current.getString("Group");
}
if(current.has("YourTurn")) {
yourTurn = current.getInt("YourTurn");
}
if(yourTurn == 0){
currentGames[i].yourTurn = true;
}
else{
currentGames[i].yourTurn = false;
}
}
catch (JSONException e){
e.printStackTrace();
}
}
}
Shouldn't the JSONObject.has() check at least be preventing this error?
I know the first getInt() and getJSONObject are working. Heres the Log:
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx D/Response:﹕ {"Number":2,"0":{"Group":"Test Group 1","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0},"1":{"Group":"Test Group 2","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":1}}
06-21 21:58:56.644 20116-20116/com.xxxxxx.xxxxxt I/Number of Groups﹕ 2
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx I/Current JSONObject﹕ {"Group":"Test Group 1","OppEmail":"xxxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0}
Here's the server code:
$games['Number'] = $numgames;
if($numgames > 0){
$i = 0;
while($row = mysqli_fetch_array($getgames)){
$currGame['Group'] = $row['GroupName'];
// Get the opponent's email and username
if($row['Player1'] != $email){
$opponent = $row['Player1'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
else if($row['Player2'] != $email){
$opponent = $row['Player2'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
// Determine if it is this player's turn
if($row['CurrentPlayer'] != $email){
$currGame['YourTurn'] = 0;
}
else{
$currGame['YourTurn'] = 1;
}
$games[$i] = $currGame;
$i++;
}
}
//Echo array of groups
header('Content-Type: application/json');
$response = json_encode($games);
echo $response;
Thank you in advance for any ideas as to what I'm doing wrong here. I know similar questions have been asked about getString() returning null, but having read them all I'm still very stumped.
Problem is caused by :
currentGames[i].oppEmail = current.getString("OppEmail");
line.
Because currentGames Array is initialized with size 2 but not added any item of type CurrentGame.
Instead of using currentGames[i].oppEmail create a object of CurrentGame class add all values then add it in currentGames Array like:
CurrentGame objCurrentGame=new CurrentGame();
if(current.has("OppEmail")){
objCurrentGame.oppEmail = current.getString("OppEmail");
}
... same for other fields
...
//Add objCurrentGame to Array
currentGames[i]=objCurrentGame;
Parsing json this way is not robust and error prone, it is recommended to use such libraries as
Gson
Jackson
Retrofit
as these open source libraries offer stable implementation for such purposes and there is no need to reinvent the wheel yourself.
example:
YourPojoClass obj = new Gson().fromJson("{SomeJsonString}", YourPojoClass.class);
In this way, you get the strongly typed pojo instance.You don't even need write the POJO class yourself, and there are many online service that can generate the POJO class out of json strings:
http://www.jsonschema2pojo.org/
http://pojo.sodhanalibrary.com/

How to get followers and following list screen names (Twitter4J)?

I am trying to get my followers and following list via Twitter 4J.
I pass the configuration builder from the main method as a parameter to the method.
Here is the code:
try {
Twitter twitter = new TwitterFactory().getInstance();
long cursor = -1;
IDs ids;
System.out.println("Listing following ids.");
do {
if (0 < args.length) {
ids = twitter.getFriendsIDs(args[0], cursor);
} else {
ids = twitter.getFriendsIDs(cursor);
}
for (long id : ids.getIDs()) {
System.out.println(id);
}
} while ((cursor = ids.getNextCursor()) != 0);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get friends' ids: " + te.getMessage());
System.exit(-1);
}
So far this only returns IDS but it does not return the screen name of the followers. Does anyone have any idea? I am working in Java and printing to the terminal.
Thanks.
String twitterScreenName = twitter.getScreenName();
PagableResponseList<User> statuse = twitter.getFollowersList(twitterScreenName, -1);
for (User follower : statuse) {
System.out.println(follower.getName());
}

This codes can't check NoResultException

This is the Code I was made. It shouldn't get and enter to NoResultException, but it doesn't as expected. There is an unused data. I try to print out, here is the output : "[ ]"
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = tableDataRangka.getSelectedRow();
String idRangka = tableDataRangka.getValueAt(row, 0).toString();
System.out.println( relasiRumahkayuRangkaDAO.getRelasiByIdRangka(idRangka).toString() );
} catch (NoResultException nre) {
// Doing something..
} catch (Exception ex) {
Logger.getLogger(MasterDataProjectUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code of method "getRelasiByIdRangka" :
public List<RelasiRumahKayuRangka> getRelasiByIdRangka(String idRangka) throws Exception{
initEntityManager();
List<RelasiRumahKayuRangka> rrDrs = new ArrayList<>();
Query q = em.createNamedQuery("RelasiRumahKayuRangka.findByIdRangka");
q.setParameter("idRangka", idRangka);
rrDrs.addAll(q.getResultList());
closeEntityManager();
return rrDrs;
}
And this one is the JPA query, findByIdRangka :
#NamedQuery(name = "RelasiRumahKayuRangka.findByIdRangka", query = "SELECT r FROM RelasiRumahKayuRangka r WHERE r.relasiRumahKayuRangkaPK.idRangka = :idRangka"),
Do you guys know the solution, so the code can be catched by NoResultException ?
In your code. if the result set is empty then list will also be empty.
Make use of that situation and throw a desired exception.
In your getRelasiByIdRangka(String idRangka) add following changes.
public List<RelasiRumahKayuRangka>
getRelasiByIdRangka( String idRangka ) throws Exception {
initEntityManager();
// rest of the code here
// ...
// check if some results are found or not
if( rrDrs.isEmpty() ) { // or ( rrDrs.size() == 0 )
throw new NoResultException( "No results found" );
} // if empty
// this should be a filled in list
return rrDrs;
} // end of method

How to find the number of vote up or vote down for a youtube comment through API

I am fetching the comments for a video using Youtube's Java API. I want to know can I find the number of up votes or down votes for all the comment. If yes then how. Currently I am using the code given below. I am getting totalRating for each comment to find upvotes but every-time it outputs 0. I know this is wrong but how do I get the vote up and down for comments.Any pointers in the right direction will be appreciated. Thanks.
private void AddComments(YouTubeVideo ytv,VideoEntry videoEntry,YouTubeService service)
{
try
{
//Get Comments
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
LinkedList<YouTubeComment> commentsLinkedList = new LinkedList<YouTubeComment>();
if(commentUrl!= null && commentUrl.length() > 0)
{
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
if(commentFeed != null)
{
for(CommentEntry comment : commentFeed.getEntries())
{
YouTubeComment youtubeComment = new YouTubeComment();
if(comment.getTotalRating()!=null)
**//comment.getTotalRating() is always equal to 0.**
youtubeComment.setLike(comment.getTotalRating());
else
youtubeComment.setLike(0);
youtubeComment.setSpamStatus(comment.hasSpamHint());
String commentinVideo = comment.getPlainTextContent();
if(commentinVideo != null)
youtubeComment.setComment(comment.getPlainTextContent());
else
youtubeComment.setComment(" ");
commentsLinkedList.add(youtubeComment);
}
ytv.setComments(commentsLinkedList);
}
else
ytv.setComments(commentsLinkedList);
}
else
{
ytv.setComments(commentsLinkedList);
}
}
catch(Exception ex)
{ // This means that "Comments are disabled for this video."
LinkedList<YouTubeComment> comments = new LinkedList<YouTubeComment>();
ytv.setComments(comments);
System.out.println("Could not add comments for video := " + videoUrl);
System.out.println("This happens when comments are disabled for the video");
System.out.println("Exception in function AddComments : " + ex.toString());
}
}
Unfortunately, those values are not exposed via the API, and there are no plans to add them.

Categories

Resources